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

后端 未结 2 404
生来不讨喜
生来不讨喜 2020-12-30 02:33

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         


        
2条回答
  •  鱼传尺愫
    2020-12-30 02:36

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

提交回复
热议问题