Errors at Python program exit: "close failed in file object destructor"; "sys.excepthook is missing"
16,872
Solution 1
Adding the following statement to the very end of my main function fixes this issue for me:
try:
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass
Solution 2
Doing flush and close worked for me.
sys.stdout.flush()
sys.stdout.close()
sys.stderr.flush()
sys.stderr.close()
Author by
user20408
Updated on June 05, 2022Comments
-
user20408 almost 2 years
After the last line (print statement) in my python code, I get the following error:
close failed in file object destructor: sys.excepthook is missing lost sys.stderr
Anyone know where this might be coming from?
Update: My python code is extremely long but I will post portions that may have something to do with this error:
For one, near the beginning of the process I redirect stdout and stderr to a log file like this:
so = se = open(logfile, 'w', 0) sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno())
I do this all the time though and have never run into this error but it seems the most likely reason I'm seeing this.