Skip to main content
 首页 » 编程设计

python之查看管道的写端是否关闭

2025年05月04日14davidwang456

我正在尝试找出一种方法来了解管道的写入端何时关闭。有办法以某种方式做到这一点吗?

from subprocess import Popen, PIPE 
p = subprocess.Popen('ls -lh', stdout = PIPE, shell = True) 
 
def read_output(out,queue): 
    for line in iter(out.readline,b''): 
        print('.') 
 
t = Thread(target=enqueue_output, args=(p.stdout,q)) 
t.daemon = True 
t.start() 
 
while True: 
    #this only works if I put  
    #if line == '' :  
    #    out.close() 
    #in the for loop of read_output, which I want to avoid. 
 
    if p.stdout.closed :  #need to find something else than closed here... 
        break 

iow 我试图避免在 io 线程中执行 out.close() ....我想以某种方式读取 p.stdout 的属性或方法以了解其写入端是否已关闭.

这真的不是要寻找另一种方式来优雅地阅读 Popen 的 p.stdout,我已经有 2 种其他方式了。更多的是学习一些我认为应该可行的东西,但我还没有想出如何去做...

干杯!

请您参考如下方法:

如果管道损坏,写入标准输出将引发 IOError。 您可以通过捕获 IOError 并检查其 errno 属性来检测此问题:

import errno 
 
while True: 
    print "Hello" 
except IOError as e: 
    if e.errno == errno.EPIPE: 
        print >>sys.stderr, "Error writing to closed pipe" 

或者,您可以在收到 SIGPIPE 时安装信号处理程序。

import signal 
def sigpipe_handler(e): 
    # Do whatever in response to a SIGPIPE signal 
 
signal.signal(signal.SIGPIPE, sigpipe_handler)