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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user20408
  • 679
  • 2
  • 7
  • 23
  • 1
    What do you do with the error (`stderr`) stream when you call the program? – Willem Van Onsem Mar 10 '17 at 15:49
  • Are you importing any modules you wrote yourself named `sys`? – Ivan Mar 10 '17 at 15:51
  • 2
    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. – jwodder Mar 10 '17 at 16:11
  • @jwodder 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 anything – user20408 Mar 10 '17 at 16:22
  • @WillemVanOnsem please see the edit to my post – user20408 Mar 10 '17 at 16:26
  • 2
    Validate that the portion you post is actually **sufficient to reproduce the problem**. See http://stackoverflow.com/help/mcve for the rules on creating a **M**inimal, **C**omplete, **V**erifiable **E**xample. Yes, this means you need to do some work yourself before asking your question. – Charles Duffy Mar 10 '17 at 16:28

2 Answers2

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
user20408
  • 679
  • 2
  • 7
  • 23
4

Doing flush and close worked for me.

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

sys.stderr.flush()
sys.stderr.close()
Joonatan Samuel
  • 641
  • 4
  • 17
  • 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 pipe` – WinEunuuchs2Unix Oct 08 '20 at 22:32