Python 了解管道的写入端是否已关闭

Python 了解管道的写入端是否已关闭,python,Python,我正试图找到一种方法来知道管道的写入端何时关闭。有没有办法做到这一点 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_outpu

我正试图找到一种方法来知道管道的写入端何时关闭。有没有办法做到这一点

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
看,我正试图避免在io线程中执行out.close()。。。。我想以某种方式读取p.stdout的属性或方法,以了解其写入端是否已关闭

这并不是要找到另一种方式来优雅地阅读波本的p.stdout,我已经有了另外两种方式。这更多的是学习一些我认为可能的东西,但我还没有想到怎么做


干杯

如果管道破裂,写入标准输出将导致引发
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)

谢谢你的回答,但这不是我想要的。p是生成shell的子进程。p、 stdout由shell进程编写,由我读取。我不能也不想模拟shell进程并尝试写入其标准输出。我只是想知道shell进程是否已经结束了它的管道。如果我在p.stdout上执行read_raw而不是readline,会产生一个EOFError,但由于readline捕捉到了这一点,我什么也得不到。我仍然相信有一种方法可以看到p.stdout的写入端句柄是关闭的。