为什么在执行打印语句时出现 IOError: (9, 'Bad file descriptor') 错误? [英] why am I getting IOError: (9, 'Bad file descriptor') error while making print statements?
问题描述
我在 Windows 2003 服务器上作为服务运行 python2.5 脚本.对于简单的打印语句,我收到此错误:
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?
推荐答案
您无法打印,因为 sys.stdout
在不作为控制台会话运行时不可用.
You can't print because sys.stdout
is not available when not running as a console session.
您可以考虑使用 logging
模块代替 print
语句,这样您就可以设置日志级别并将所有关键内容写入系统事件日志.
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')
写入单个文件:
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()
这篇关于为什么在执行打印语句时出现 IOError: (9, 'Bad file descriptor') 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!