【发布时间】:2013-04-03 17:18:08
【问题描述】:
我正在尝试打印我的stdout 格式的元组列表。为此,我使用str.format 方法。一切正常,但是当我通过管道输出查看
使用head 命令的第一行会出现IOError。
这是我的代码:
# creating the data
data = []$
for i in range(0, 1000):
pid = 'pid%d' % i
uid = 'uid%d' % i
pname = 'pname%d' % i
data.append( (pid, uid, pname) )
# find max leghed string for each field
pids, uids, pnames = zip(*data)
max_pid = len("%s" % max( pids) )
max_uid = len("%s" % max( uids) )
max_pname = len("%s" % max( pnames) )
# my template for the formatted strings
template = "{0:%d}\t{1:%d}\t{2:%d}" % (max_pid, max_uid, max_pname)
# print the formatted output to stdout
for pid, uid, pname in data:
print template.format(pid, uid, pname)
这是我运行命令后得到的错误:python myscript.py | head
Traceback (most recent call last):
File "lala.py", line 16, in <module>
print template.format(pid, uid, pname)
IOError: [Errno 32] Broken pipe
谁能帮我解决这个问题?
我尝试将print 放入try-except 块中以处理错误,
但之后控制台中出现另一条消息:
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
我还尝试通过两个连续的方法立即刷新数据
sys.stdout.write 和 sys.stdout.flush 打电话,但什么也没发生..
【问题讨论】:
-
发生这种情况是因为
head关闭stdout,导致print尝试写入已关闭的文件。你希望发生什么? -
好的,谢谢!我想避免在控制台中打印此类消息。我想将此代码的变体用于命令行工具。
-
这个问题可能是重复的;见:stackoverflow.com/questions/11423225/…
标签: python format string-formatting ioerror broken-pipe