I'm having trouble with a printing information that is input from a yaml file using PyYAML. I'm trying to reduce line-count, without affecting functionality. In some runs the output has to be appended to a file, in others to stdout.
At first I used this multiple times in my function processData:
if logName:
fp = open(logName, 'a')
else:
fp = sys.stdout
print(........, file=fp)
print(........, file=fp)
if logName:
fp.close()
That worked, but has the disadvantages of not using the with statement when something goes wrong.
The actual problem is not the complex print statements, but that I
1) don't want to duplicate code when printing to file or to sys.stdout
2) want to use the with statement so that files get closed if there are print errors
3) there are several such blocks, I don't want to call a different function for each of them, and so preventing code duplication
Then what I tried is:
def processData(yamlData, logName=None):
......
with open(logName, 'a') if logName else sys.stdout as fp:
print(........, file=fp)
print(........, file=fp)
.....
with open(logName, 'a') if logName else sys.stdout as fp:
print(........, file=fp)
print(........, file=fp)
If there is not a logName, this errors to "ValueError: I/O operation on closed file". Any suggestions on how to get this to work without the original duplication? Can I reopen sys.stdout?