打印大量格式化数据时如何避免出现管道错误?

Tha*_*sas 10 python format broken-pipe string-formatting ioerror

我正在尝试打印在我的格式化的元组列表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)
Run Code Online (Sandbox Code Playgroud)

这是运行命令后得到的错误: 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
Run Code Online (Sandbox Code Playgroud)

谁可以帮我这个事?

我试图放入print一个try-except块来处理错误,但在那之后控制台中还有另一条消息:

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr
Run Code Online (Sandbox Code Playgroud)

我也试图通过连续两次立即刷新数据 sys.stdout.write和sys.stdout.flush电话,但没有happend ..

Mar*_*ers 12

head读取stdout然后关闭它.这导致print失败,在内部写入sys.stdout,现在关闭.

你可以简单地赶上了IOError和退出默默:

try:
    for pid, uid, pname in data:
        print template.format(pid, uid, pname)
except IOError:
    # stdout is closed, no point in continuing
    # Attempt to close them explicitly to prevent cleanup problems:
    try:
        sys.stdout.close()
    except IOError:
        pass
    try:
        sys.stderr.close()
    except IOError:
        pass
Run Code Online (Sandbox Code Playgroud)

  • 好的,我找到了!它只需要你的答案的补充.只需在print语句后放一个`sys.stdout.flush()`!但错误就是你所描述的!我也注意到,由于某些原因,如果我把冲洗器放出循环,它也可以工作..无论如何.谢谢!:) (2认同)