Python newbie here. I am writing a script that can upload some output to a file or stdout, depending on the arguments passed to it. When interpreting the arguments, I assign the file open 'ed or stdout global variable called output_file , which can be used by the rest of the script to write the output no matter what type of stream was selected. At the very end of the script, I close output_file . This needs to be done for the file stream, and although it is redundant for stdout, my experience with other programming languages โโsuggests that there is no harm in explicitly closing stdout just before the program terminates.
However, when stdout is used for output (and subsequently closed), I get a ValueError: 'I / O operation in a closed file.' ". I know that this error is not directly caused by my call to close stdout, but it arises after returning my script. My question is: why is this happening, and is there a way to manually close stdout without running it? (I know that I can easily get around the problem by conditionally closing the stream only when the file was selected, but I want to know if / why it is necessary.)
A very simple demo fragment:
from sys import stdout stdout.close()
source share