Why does my Python3 script balk at piping its output to head or tail (sys module)?

前端 未结 2 1435
猫巷女王i
猫巷女王i 2020-12-30 07:05

I have a Python3 script that writes its output to stdout, but it complains when I pipe that output into head or tail. Note in the sample output below that it sort of works,

相关标签:
2条回答
  • 2020-12-30 07:21
    ./script.py '../Testdata/*indels.ss' -m 5 | awk 'NR >= 3 {exit} 1'
    

    would show the same behavior as head -2.

    You can turn set the SIGPIPE handler to one which quietly kills your program instead:

    import signal
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    
    0 讨论(0)
  • 2020-12-30 07:33

    I'll cite from here:

    If a sequence of commands appears in a pipeline, and one of the

    reading commands finishes before the writer has finished, the

    writer receives a SIGPIPE signal.

    That's what head does. Your script hasn't finished writing, but head is already done, so stdout is closed, hence the exception.

    0 讨论(0)
提交回复
热议问题