注意:我没有试图重现下面在Windows下面描述的问题,或者使用2.7.3以外的Python版本。如何沉默“sys.excepthook失踪”错误?
最可靠的方法来引起讨论的问题是管下面的测试脚本通过:
输出(bash
下):
try:
for n in range(20):
print n
except:
pass
即:
% python testscript.py | :
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
我的问题是:
How can I modify the test script above to avoid the error message when the script is run as shown (under Unix/
bash
)?
(正如测试脚本所示,错误不能被捕获一个try-except
。)
上面的例子是,诚然,高度人工化,但我遇到了同样的问题有时我的一个脚本的输出通过一些第三方的管道软件。
错误信息当然是无害的,但对最终用户来说是令人不安的,所以我想让它沉默。
编辑:下面的脚本,它不同于上面的原始只是因为它重新定义sys.excepthook,行为完全像上面给出的。
import sys
STDERR = sys.stderr
def excepthook(*args):
print >> STDERR, 'caught'
print >> STDERR, args
sys.excepthook = excepthook
try:
for n in range(20):
print n
except:
pass
一个非常清晰和简洁的解释,通常会让我抓住氧气罐(溺水,需要更多,空气!),谢谢! –
在其他程序需要python脚本的输出的情况下,例如, grep,有没有比python printer.py更好的实现方式grep“abc”'? –
@MarkZ。诚实地说,最好的解决方案不是将Python脚本的输出传递给不读取它的程序 - 即避免造成这个问题首先出现的整个情况。如果由于某种奇怪的原因而无法实现,可以使用'--quiet'或'--silent'等命令行选项来抑制Python脚本的所有输出。 –