我试图想办法知道管道的写入结束何时关闭。有办法以某种方式这样做吗?
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 Thread中做out.close()....我想以某种方式读取p.stdout的属性或方法,以了解它的写入结尾是否有已关闭。
这真的不是要找到另一种方式来优雅地阅读Popen的p.stout,我还有另外两种方式。它更多的是学习我认为应该可行的东西,但我还没想到该怎么做......
干杯!
答案 0 :(得分:1)
如果管道损坏,写入标准输出将导致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)