Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why am I getting IOError: (9, 'Bad file descriptor') error while making print statements?

Tags:

I am running a python2.5 script on a windows 2003 server as a service. I am getting this error for simple print statments:

IOError: (9, 'Bad file descriptor') 

I deleted all the print statements because they were only used for development purposes, but I am unsure why a print statement would cause me any greif. I ran the same script not as a service without any major problems. Just wondering if anyone else has any insight?

like image 203
Richard Avatar asked Nov 20 '10 02:11

Richard


People also ask

What is Errno 9 Bad file descriptor?

Reason for getting error “oserror: [errno 9] bad file descriptor” : The internal state of the file object indicates the file is still open since f. close() was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.

What is bad file descriptor error?

In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons: The fd is already closed somewhere. The fd has a wrong value, which is inconsistent with the value obtained from socket() api.

What does Errno 9 mean?

It shows an error like: OSError: [Errno 9] Bad file descriptor. It means that the file defined in the program is already closed automatically while running the code.


1 Answers

You can't print because sys.stdout is not available when not running as a console session.

Instead of using print statements you can consider using the logging module so you can set the loglevel and write all critical things to the system event log.


It should be noted that you can still get it to work (or silently ignore the problem) by doing something like this:

To write to a file per output stream:

import sys sys.stdout = open('stdout.txt', 'w') sys.stderr = open('stderr.txt', 'w') 

To write to a single file:

import sys sys.stdout = sys.stderr = open('output.txt', 'w') 

Or to silently ignore all print statements:

import sys class NullWriter(object):     def write(self, value): pass  sys.stdout = sys.stderr = NullWriter() 
like image 80
Wolph Avatar answered Sep 20 '22 15:09

Wolph