Python 2.7 如何在不阻止python输出的情况下捕获输出
我想用python运行命令行,并捕获输出。我可以使用Python 2.7 如何在不阻止python输出的情况下捕获输出,python-2.7,subprocess,Python 2.7,Subprocess,我想用python运行命令行,并捕获输出。我可以使用子流程。检查\u输出。但是它会抑制输出,我如何在不抑制控制台输出的情况下进行呢 from subprocess import Popen, PIPE proc = Popen(["/usr/bin/nc", "-l", "9999"], stdout=PIPE) buffer = [] line = proc.stdout.readline() while line: buffer.append(line) print "L
子流程。检查\u输出
。但是它会抑制输出,我如何在不抑制控制台输出的情况下进行呢
from subprocess import Popen, PIPE
proc = Popen(["/usr/bin/nc", "-l", "9999"], stdout=PIPE)
buffer = []
line = proc.stdout.readline()
while line:
buffer.append(line)
print "LINE", line.strip()
line = proc.stdout.readline()
print "buffer", ''.join(buffer)
使用另一个终端发送一些文本
nc localhost 9999
# type something. the text should appear from the python code
断开nc,您将在缓冲区中获得输出
这如何
from subprocess import Popen, PIPE
proc = Popen(["/usr/bin/nc", "-l", "9999"], stdout=PIPE)
buffer = []
line = proc.stdout.readline()
while line:
buffer.append(line)
print "LINE", line.strip()
line = proc.stdout.readline()
print "buffer", ''.join(buffer)
使用另一个终端发送一些文本
nc localhost 9999
# type something. the text should appear from the python code
断开nc,您将在
缓冲区中获得输出@KenjiNoguchi我需要它在控制台上输出,我不想打印返回值,因为有时我想调试子进程是否挂起以支持多个管道,请参阅(基于线程的实现+指向异步版本的链接)相关:(来自的问题)@KenjiNoguchi我需要它在控制台上输出,我不想打印返回值,因为有时我想调试子进程是否挂起以支持多个管道,请参阅(基于线程的实现+指向异步版本的链接)相关:(来自的问题)@demonguy:或者更简洁地说:。无关:您可以使用socket
模块而不是nc
命令。但我看到的文档类似于警告使用communicate()而不是.stdin.write、.stdout.read或.stderr.read,以避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。
如何避免它?@demonguy:如果您只需要读取单个管道,则不适用。请查看我在注释中提供的链接,这些链接使用线程async.io来使用多个pipes,以避免死锁。@demonguy:或更简洁地说:。无关:您可以使用socket
模块而不是nc
命令。但是我看到这样的文档警告使用communicate()而不是.stdin.write、.stdout.read或.stderr.read,以避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。
如何避免它?@demonguy:如果您只需要读取单个管道,则不适用。请查看我在注释中提供的链接,这些链接使用线程async.io来使用多个pip为了避免僵局。