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

17,733

Solution 1

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()

Solution 2

In Python 2.x, this is the expected behavior. In this bug report, Christian Heimes explains that it is a design decision:

I recommend against changing the code so late in the Python 2.7 release cycle. A change in behavior is too confusing. And it's not a bug but a design decision, too. Over five years ago I implement parts of the IO interaction with the operating system for Python 3.0. I deliberately did NOT port modifications to 2.6.

He also recommends a workaround for obtaining Python 3.x-style print() behavior in Python 2.7:

from __future__ import print_function
import sys
if sys.executable.endswith("pythonw.exe"):
    sys.stdout = sys.stdout = None

print("can handle sys.stdout = None just fine.")
Share:
17,733

Related videos on Youtube

Richard
Author by

Richard

Updated on March 15, 2020

Comments

  • Richard
    Richard about 4 years

    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?

  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams over 13 years
    More specifically, the first three file descriptors (corresponding to stdin, stdout, and stderr) are unavailable if your program doesn't run in a console.
  • Brendan Abel
    Brendan Abel almost 10 years
    Another way to silently ignore all print statements sys.stdout = open(os.devnull, 'w')
  • SuperBiasedMan
    SuperBiasedMan over 8 years
    This fixed my problem for me. Would you know why this only happens on some print calls, after a series of them have already been ignored? As in, I have a script being run windowless and it can get halfway through (which involves a lot of print calls) before failing, always at the same print call, with this error.
  • Cody Gray
    Cody Gray about 8 years
    Derrick, there has been a fair bit of contention over this answer. Experienced users who work hard to keep the quality of information on this site as high as possible flagged it as containing only a link to off-site information. We tend to discourage such types of answers, as the link could go down, which would make the answer useless. This is why it has been downvoted, and why it has had multiple votes to delete cast against it. However, I do see value in the link you provided, and don't think that deleting this answer is the appropriate solution.
  • Cody Gray
    Cody Gray about 8 years
    Instead, I and another user have edited the relevant information from the link into your answer. This should help avoid the answer's pending deletion, and possibly gain you some more upvotes. As you're a new user, I'm sorry that you've had a bad experience with the site. When posting answers in the future, please try to keep in mind that good answers are entirely self-contained. The best thing to do is what I've done here, and edit the relevant information into the answer, including the link only as a supplement. Anyway, just wanted to explain the funny business. Best of luck to you!
  • Derrick
    Derrick about 8 years
    Thanks for the update. Even I am still undecided on whether I consider it a bug. The print statement is the de facto debug tool so something so simple should almost never fail in my opinion. In your edit there is a line of code: "sys.stdout = sys.stdout = None"; should this instead be "sys.stdout = sys.stderr = None"?
  • Cody Gray
    Cody Gray about 8 years
    I just copied the code exactly from Christian's post in the linked bug report. You might be right, I really don't know. Honestly I don't know anything about Python, I just stepped in to help resolve the answer-quality concerns. I didn't think this answer merited removal.