打印大量格式化数据时,如何避免管道破裂的错误? [英] How to avoid a Broken Pipe error when printing a large amount of formatted data?

查看:143
本文介绍了打印大量格式化数据时,如何避免管道破裂的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印以 stdout 格式设置的元组列表。为此,我使用了 str.format 方法。一切正常,但是当我使用 head 命令通过管道输出以查看
第一行时,出现 IOError

I am trying to print a list of tuples formatted in my stdout. For this, I use the str.format method. Everything works fine, but when I pipe the output to see the first lines using the head command a 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)

这是我运行后收到的错误命令: pyt hon myscript.py |头

And here is the error I get after running the command: 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

有人可以帮我吗?

我试图将打印放在 try-except 块来处理错误
,但此后控制台中又出现了一条消息:

I tried to put print in a try-except block to handle the error, but after that there was another message in the console:

close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

我还尝试通过两个连续的
sys.stdout.write 和<$ c立即刷新数据$ c> sys.stdout.flush 调用,但没有任何反应。.

I also tried to flush immediately the data through a two consecutive sys.stdout.write and sys.stdout.flush calls, but nothing happend..

推荐答案

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

head reads from stdout then closes it. This causes print to fail, internally it writes to sys.stdout, now closed.

您可以简单地 catch IOError 并静默退出:

You can simply catch the IOError and exit silently:

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

这篇关于打印大量格式化数据时,如何避免管道破裂的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆