代码之家  ›  专栏  ›  技术社区  ›  shodanex

python标准件齐平和T形三通

  •  2
  • shodanex  · 技术社区  · 17 年前

    以下代码在管道连接到T形三通时以断管结束,但在未连接管道时行为正确:

    #!/usr/bin/python
    import sys
    def testfun():
        while 1:
            try :
                s = sys.stdin.readline()
            except(KeyboardInterrupt) :
                print('Ctrl-C pressed')
                sys.stdout.flush()
                return
            print s
    
    if __name__ == "__main__":
        testfun()
        sys.exit()
    

    预期产出:

    ./bug.py 
    Ctrl-C pressed
    

    当管道连接到T形三通时,观察到的情况要么是管道破裂,要么根本没有输出,即T形三通标准输出上没有任何内容,bug.log中也没有任何内容:

    ./bug.py | tee bug.log
    Traceback (most recent call last):
      File "./bug.py", line 14, in <module>
        sys.stdout.flush()
    IOError: [Errno 32] Broken pipe
    

    这是什么原因呢?

    3 回复  |  直到 17 年前
        1
  •  9
  •   GED    15 年前

    不,点击Ctrl-C并不会终止这两个进程。它仅终止tee进程,

    为了解决这个问题,tee有一个选项可以将Ctrl-C传递到管道中的上一个进程:-i

    试试看:男式T恤

    ./bug.py
    ^CCtrl-C pressed
    ./bug.py | tee log
    ^CTraceback (most recent call last):
      File "./bug.py", line 14, in <module>
        testfun()
      File "./bug.py", line 9, in testfun
        sys.stdout.flush()
    IOError: [Errno 32] Broken pipe
    
    ./bug.py | tee -i log
    ^CCtrl-C pressed
    
        2
  •  5
  •   shodanex    17 年前

    mknod mypipe p
    cat mypipe | tee somefile.log &
    ./bug.py > mypipe
    
        3
  •  4
  •   Brian Agnew    17 年前

    当您点击Ctrl-C时,shell将终止 二者都 进程( python 和 tee

    因此,当您在 python 处理和冲洗,它会发现 已终止,且管道不再存在。因此出现了错误消息。

    (顺便说一句,您是否希望日志中有任何内容?我没有看到您的进程输出任何内容,除了退出时刷新)