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

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


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 syssys.stdout = open('stdout.txt', 'w')sys.stderr = open('stderr.txt', 'w')

To write to a single file:

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

Or to silently ignore all print statements:

import sysclass NullWriter(object):    def write(self, value): passsys.stdout = sys.stderr = NullWriter()


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_functionimport sysif sys.executable.endswith("pythonw.exe"):    sys.stdout = sys.stdout = Noneprint("can handle sys.stdout = None just fine.")