でフォーマットされたタプルのリストを印刷しようとしてい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
が、何も起こりませんでした..