我正在尝试打印我的格式的元组列表stdout
。为此,我使用字符串格式 http://docs.python.org/2/library/string.html#string-formatting方法。一切工作正常,但是当我通过管道输出看到
第一行使用head
命令一个IOError
occurs.
这是我的代码:
# 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
in a try-except
块来处理错误,
但之后控制台中又出现了另一条消息:
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
我还尝试通过两个连续的立即刷新数据sys.stdout.write
and sys.stdout.flush
打电话,但什么也没发生..