Print: "IOError: [Errno 9] Bad file descriptor"

I understand why I get the "Bad file descriptor" error when printing without the console from this message: Why do I get IOError: (9, "Bad file descriptor") an error while executing print statements? .

My question is, how can I determine if stdout is available? Can I just do something like this:

if os.path.isfile(2): print "text" 

thanks

+4
source share
2 answers

os.path.isfile () takes the file path (string), not the file descriptor (number), so your solution will not work as you would expect.

Instead of os.isatty (), you can use

 if os.isatty(1): print "text" 

os.isatty() will return True if its argument is an open file descriptor connected to the terminal.

(Interim note that stdout is a file descriptor 1 stderr is a file descriptor 2 ).

+8
source

This answer did not help me. But maybe this is a bug in Python 2.x:

https://bugs.python.org/issue706263

I am using 2.7. os.isatty (1) always returns true, but printing still throws an exception after 4k bytes. I am using pythonw.exe to run a script in the background.

0
source

Source: https://habr.com/ru/post/1500540/


All Articles