I'm programming a script where I have an option, to be passed on the command line, whether the script should print its results to stdout or to a predefined results file. A code outline for this is shown below. I now have read a little bit about context managers in Python, but am not really sure whether and how to use a context manager in this specific situation. So I am looking for advice
- whether it makes sense to use a context manager in this problem
- how to go about implementing it.
So, the code without context manager is:
option_file = True # would come from OptionParser in real code
if option_file:
out = open("resultsfile", "w")
else:
out = sys.stdout
# do some computations
out.write("Results of script")
# more computations and calls to out.write
if option_file:
out.close()