我正在尝试打印在我的stdout
. 为此,我使用str.format方法。head
一切正常,但是当我使用命令 a管道输出以查看第一行时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
调用立即刷新数据
,但什么也没发生。