I would like to summarize the input parameters for a python calculation using text strings. I can summarize the input parameters using print()
but I don't know how to also save these as text strings.
Sample Code
First, define the scan of input parameters:
import numpy as np
gapsize = np.arange(0.5,0.8,0.1)
ringwidth = np.arange(1.25,5,0.75)
outputangle = [28.43]
Now define a function that prints a parameter-specific summary of these values
def printSCANvalues(parameter):
## Do cases for text descriptions
if parameter is ringwidth:
paramTEXT = "RW"
elif parameter is gapsize:
paramTEXT = "Gap"
elif parameter is outputangle:
paramTEXT = "Facet Angle"
if parameter is ringwidth or parameter is gapsize:
unit = 'um'
elif parameter is outputangle:
unit = 'deg.'
## only calculate the gradient for arrays with more than one value
if len(parameter) > 1:
step = round(1000*np.gradient(parameter)[0])/1000
elif len(parameter) == 1:
step = 0
stopVAL = round(1000*parameter[-1])/1000
print("")
print(paramTEXT, "Scan: qty =", len(parameter),", start = ", parameter[0],
unit, ", stop = ", stopVAL, unit, ", step = ", step, unit)
print(paramTEXT, "values: ", parameter, unit)
Now use function to generate the text that summarizes the input parameter scan:
print("")
print("====== Input Parameter Scan Values ======")
print("")
printSCANvalues(ringwidth)
printSCANvalues(gapsize)
printSCANvalues(outputangle)
Screenshot of output:
The problem
I would also like to save this output as a text string so that it can be written to a text file. Is there a way to save the associated string for each parameter type before print()
is executed so that I can use it later?
print()
function indicates it accepts an optionalfile
keyword argument — which implies that anything you can print can be sent to an (open) file. You can also do it using thecontextlib.redirect_stdout()
function.