Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I understand why I am getting the "Bad file descriptor" error when printing with no console from this post: why am I getting IOError: (9, 'Bad file descriptor') error while making print statements?.

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

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

Thanks

like image 933
Doo Dah Avatar asked Sep 04 '13 13:09

Doo Dah


1 Answers

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

You can use os.isatty() instead:

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

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

(In passing, note that stdout is file descriptor 1. stderr is file descriptor 2).

like image 73
Frédéric Hamidi Avatar answered Sep 24 '22 14:09

Frédéric Hamidi