为什么在打印语句时我会收到IOError: (9, 'Bad file descriptor')错误?

2024-04-20 06:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Windows2003服务器上作为服务运行python2.5脚本。对于简单的打印语句,我将得到此错误:

IOError: (9, 'Bad file descriptor')

我删除了所有打印报表,因为它们只用于开发目的,但我不确定打印报表为什么会导致我任何greif。我运行同一个脚本,而不是作为一个服务,没有任何重大问题。只是想知道其他人是否有什么见解?


Tags: 目的服务器脚本报表错误语句filebad
2条回答

无法打印,因为sys.stdout不作为控制台会话运行时不可用。

不要使用print语句,您可以考虑使用logging模块,这样您就可以设置日志级别,并将所有关键内容写入系统事件日志。


需要注意的是,您仍然可以通过执行以下操作来让它正常工作(或默默地忽略问题):

要在每个输出流中写入文件,请执行以下操作:

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

要写入单个文件:

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

或者忽略所有打印语句:

import sys
class NullWriter(object):
    def write(self, value): pass

sys.stdout = sys.stderr = NullWriter()

在Python2.x中,这是预期的行为。在this bug report中,Christian Heimes解释说这是一个设计决策:

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.

他还建议在Python 2.7中获得Python 3.x风格的print()行为的解决方法:

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.")

相关问题 更多 >