11

でフォーマットされたタプルのリストを印刷しようとしてい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また、2 回連続して and を呼び出してデータをすぐにフラッシュしようとしました sys.stdout.flushが、何も起こりませんでした..

4

4 に答える 4

13

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
于 2013-04-03T17:26:00.580 に答える
2

表示されている動作は、Python3 のバッファー出力の実装に​​リンクされています。この問題は、-u オプションを使用するか、環境変数 PYTHONUNBUFFERED=x を設定することで回避できます。-u の詳細については、man ページを参照してください。

$ python2.7 testprint.py | echo

Exc: <type 'exceptions.IOError'>
$ python3.5 testprint.py | echo

Exc: <class 'BrokenPipeError'>
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe
$ python3.5 -u testprint.py | echo

Exc: <class 'BrokenPipeError'>
$ export PYTHONUNBUFFERED=x
$ python3.5 testprint.py | echo

Exc: <class 'BrokenPipeError'>
于 2016-05-17T20:18:22.460 に答える