下面是我所看到的一个例子:
❯ cat /tmp/test.py
#!/usr/bin/env python3
import csv
with open("/dev/stdout", "w") as f:
csvwriter = csv.writer(f)
csvwriter.writerows((_,) for _ in range(10000))
当重定向到文件或发送到标准输出时,它运行得很好.
❯ /tmp/test.py > /dev/null
❯ echo $?
0
然而,当发送到Head以及其他一些工具时,它会引发异常.
❯ /tmp/test.py | head > /dev/null
Traceback (most recent call last):
File "/tmp/test.py", line 7, in <module>
csvwriter.writerows((_,) for _ in range(10000))
BrokenPipeError: [Errno 32] Broken pipe
During handling of the above exception, another exception occurred:
BrokenPipeError: [Errno 32] Broken pipe
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/tmp/test.py", line 5, in <module>
with open("/dev/stdout", "w") as f:
BrokenPipeError: [Errno 32] Broken pipe
如果我有range(15)
个左右,那就没问题.问题是,有没有一些我可以在Python中使用的设置来避免这种行为?