Errors at Python program exit: "close failed in file object destructor"; "sys.excepthook is missing"
Asked Answered
O

2

6

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.

Overstock answered 10/3, 2017 at 15:48 Comment(6)
What do you do with the error (stderr) stream when you call the program?Lomax
Are you importing any modules you wrote yourself named sys?Stope
I think the error might be coming from your code, but since you haven't shown us any of it, the world may never know.Suffragan
@Suffragan hah well, the code is super long and i don't know which parts are relevant to this error so that's why i didn't post anythingOverstock
@WillemVanOnsem please see the edit to my postOverstock
Validate that the portion you post is actually sufficient to reproduce the problem. See stackoverflow.com/help/mcve for the rules on creating a Minimal, Complete, Verifiable Example. Yes, this means you need to do some work yourself before asking your question.Thurstan
O
9

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
Overstock answered 17/3, 2017 at 15:46 Comment(0)
N
4

Doing flush and close worked for me.

sys.stdout.flush()
sys.stdout.close()

sys.stderr.flush()
sys.stderr.close()
Northumbria answered 21/11, 2017 at 19:9 Comment(1)
The answer by user20408 works for me. This answer works too and sheds light with a new error message: sys.stdout.flush() IOError: [Errno 32] Broken pipeMaillot

© 2022 - 2024 — McMap. All rights reserved.