python 中 subprocess.PIPE 的非阻塞读取
-
22-08-2019 - |
题
我正在使用 子流程模块 启动子进程并连接到其输出流(stdout)。我希望能够在其标准输出上执行非阻塞读取。有没有办法使 .readline 非阻塞或在调用之前检查流上是否有数据 .readline
?我希望它是可移植的或者至少可以在 Windows 和 Linux 下工作。
这是我现在的做法(它阻塞了 .readline
如果没有可用数据):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
解决方案
fcntl
, select
, asyncproc
在这种情况下没有帮助。
无论操作系统如何,无阻塞地读取流的可靠方法是使用 Queue.get_nowait()
:
import sys
from subprocess import PIPE, Popen
from threading import Thread
try:
from queue import Queue, Empty
except ImportError:
from Queue import Queue, Empty # python 2.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
p = Popen(['myprogram.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
# ... do other things here
# read line without blocking
try: line = q.get_nowait() # or q.get(timeout=.1)
except Empty:
print('no output yet')
else: # got line
# ... do something with line
其他提示
我经常有类似的问题;我经常写Python程序必须执行一些主要功能,同时在命令行(标准输入)接受用户输入的能力。简单地把用户输入处理功能在另一个线程并不能解决问题,因为readline()
块,并没有超时。如果主功能已经完成,不再有任何需要等待进一步的用户输入通常我希望我的程序退出,但不能因为readline()
仍然在其他线程等待线端阻塞。我发现这个问题的解决方案是让使用的fcntl模块标准输入非阻塞文件:
import fcntl
import os
import sys
# make stdin a non-blocking file
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# user input handling thread
while mainThreadIsRunning:
try: input = sys.stdin.readline()
except: continue
handleInput(input)
在我看来,这比使用选择或信号模块来解决这个问题,清洁一下,但随后又只能在UNIX ...
蟒蛇3.4引入了新的 临时API 异步IO-- asyncio
模块.
这种方法是相似的 twisted
基于答复的布莱恩*沃德 -定义的协议及其方法称为尽快数据是准备:
#!/usr/bin/env python3
import asyncio
import os
class SubprocessProtocol(asyncio.SubprocessProtocol):
def pipe_data_received(self, fd, data):
if fd == 1: # got stdout data (bytes)
print(data)
def connection_lost(self, exc):
loop.stop() # end loop.run_forever()
if os.name == 'nt':
loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(loop.subprocess_exec(SubprocessProtocol,
"myprogram.exe", "arg1", "arg2"))
loop.run_forever()
finally:
loop.close()
看看 "子流程"的文档.
有一个高级别的接口 asyncio.create_subprocess_exec()
返回 Process
对象 ,允许宣读一线asynchroniosly使用 StreamReader.readline()
协程
(与 async
/await
蟒蛇3.5+语法):
#!/usr/bin/env python3.5
import asyncio
import locale
import sys
from asyncio.subprocess import PIPE
from contextlib import closing
async def readline_and_kill(*args):
# start child process
process = await asyncio.create_subprocess_exec(*args, stdout=PIPE)
# read line (sequence of bytes ending with b'\n') asynchronously
async for line in process.stdout:
print("got line:", line.decode(locale.getpreferredencoding(False)))
break
process.kill()
return await process.wait() # wait for the child process to exit
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
with closing(loop):
sys.exit(loop.run_until_complete(readline_and_kill(
"myprogram.exe", "arg1", "arg2")))
readline_and_kill()
执行以下任务:
- 启动子流程,重新定向其stdout到管道
- 读线子流程'stdout异步
- 杀死子流程
- 等待它退出
每个步骤可能是有限的超时几秒钟内,如果有必要的。
尝试 asyncproc 模块。例如:
import os
from asyncproc import Process
myProc = Process("myprogram.app")
while True:
# check to see if process has ended
poll = myProc.wait(os.WNOHANG)
if poll != None:
break
# print any new output
out = myProc.read()
if out != "":
print out
由美国洛特作为建议的模块通吃螺纹的照顾。
您可以在扭曲做到这一点真的很容易。根据您现有的代码库,这可能不是那么容易使用,但如果你正在建设一个扭曲的应用程序,那么像这样的事情变得几乎微不足道。您创建一个ProcessProtocol
类,并重写outReceived()
方法。扭曲(取决于使用的反应器)通常为只是一个大select()
环安装处理来自不同的文件描述符(通常网络套接字的)数据的回调。所以outReceived()
方法简单地安装用于处理数据从STDOUT
到来的回调。一个简单的例子展示这种行为如下:
from twisted.internet import protocol, reactor
class MyProcessProtocol(protocol.ProcessProtocol):
def outReceived(self, data):
print data
proc = MyProcessProtocol()
reactor.spawnProcess(proc, './myprogram', ['./myprogram', 'arg1', 'arg2', 'arg3'])
reactor.run()
对此有一些好的信息扭曲文档。
如果您围绕扭转整个应用程序,它与其他进程,本地或远程,真正优雅的这样的异步通信。在另一方面,如果你的程序不是建立在扭曲的顶部,这是不是真的会是有益的。希望这可以帮助其他读者,即使它并不适用于您的特定应用。
使用选择&读取(1)。
import subprocess #no new requirements
def readAllSoFar(proc, retVal=''):
while (select.select([proc.stdout],[],[],0)[0]!=[]):
retVal+=proc.stdout.read(1)
return retVal
p = subprocess.Popen(['/bin/ls'], stdout=subprocess.PIPE)
while not p.poll():
print (readAllSoFar(p))
有关的ReadLine() - 这样的:
lines = ['']
while not p.poll():
lines = readAllSoFar(p, lines[-1]).split('\n')
for a in range(len(lines)-1):
print a
lines = readAllSoFar(p, lines[-1]).split('\n')
for a in range(len(lines)-1):
print a
的一个解决方案是使另一个进程执行您的过程中读出,或使该方法的一个线程以超时。
下面是一个超时功能的螺纹版本:
http://code.activestate.com/recipes/473878/
不过,你需要阅读的标准输出作为它的到来? 另一种解决方案可以是将输出转储到一个文件,并等待过程中使用完成的 p.wait()强>
f = open('myprogram_output.txt','w')
p = subprocess.Popen('myprogram.exe', stdout=f)
p.wait()
f.close()
str = open('myprogram_output.txt','r').read()
声明:本仅适用于龙卷风
可以通过设置FD是非阻塞,然后使用ioloop注册回调做到这一点。我曾在一个名为 tornado_subprocess 鸡蛋包装这一点,你可以通过PyPI中安装:
easy_install tornado_subprocess
现在你可以做这样的事情:
import tornado_subprocess
import tornado.ioloop
def print_res( status, stdout, stderr ) :
print status, stdout, stderr
if status == 0:
print "OK:"
print stdout
else:
print "ERROR:"
print stderr
t = tornado_subprocess.Subprocess( print_res, timeout=30, args=[ "cat", "/etc/passwd" ] )
t.start()
tornado.ioloop.IOLoop.instance().start()
也可以用RequestHandler使用它
class MyHandler(tornado.web.RequestHandler):
def on_done(self, status, stdout, stderr):
self.write( stdout )
self.finish()
@tornado.web.asynchronous
def get(self):
t = tornado_subprocess.Subprocess( self.on_done, timeout=30, args=[ "cat", "/etc/passwd" ] )
t.start()
现有的解决方案并没有为我工作(详情见下文)。最后是什么工作来实现readline使用读(1)(基于 这个答案).后者不块:
from subprocess import Popen, PIPE
from threading import Thread
def process_output(myprocess): #output-consuming thread
nextline = None
buf = ''
while True:
#--- extract line using read(1)
out = myprocess.stdout.read(1)
if out == '' and myprocess.poll() != None: break
if out != '':
buf += out
if out == '\n':
nextline = buf
buf = ''
if not nextline: continue
line = nextline
nextline = None
#--- do whatever you want with line here
print 'Line is:', line
myprocess.stdout.close()
myprocess = Popen('myprogram.exe', stdout=PIPE) #output-producing process
p1 = Thread(target=process_output, args=(dcmpid,)) #output-consuming thread
p1.daemon = True
p1.start()
#--- do whatever here and then kill process and thread if needed
if myprocess.poll() == None: #kill process; will automatically stop thread
myprocess.kill()
myprocess.wait()
if p1 and p1.is_alive(): #wait for thread to finish
p1.join()
为什么现有的解决方案没有工作:
- 解决方案,需要readline(包括在队列中基于的)总块。它是困难(不可能的吗?) 杀线程的执行readline.它只是被杀害时的创建进程的完成,但不是输出时的生产过程中被杀害。
- 混合的低水平fcntl与高级别readline电话可能不正常工作anonnn已经指出。
- 使用选择。调查()整,但不工作,在Windows根据python文档。
- 使用第三方图书馆似乎矫枉过正为此任务,并添加附加依赖关系。
该版本的非阻塞读不需要特殊的模块,将工作外的开箱上大多数Linux发行版的。
import os
import sys
import time
import fcntl
import subprocess
def async_read(fd):
# set non-blocking flag while preserving old flags
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# read char until EOF hit
while True:
try:
ch = os.read(fd.fileno(), 1)
# EOF
if not ch: break
sys.stdout.write(ch)
except OSError:
# waiting for data be available on fd
pass
def shell(args, async=True):
# merge stderr and stdout
proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if async: async_read(proc.stdout)
sout, serr = proc.communicate()
return (sout, serr)
if __name__ == '__main__':
cmd = 'ping 8.8.8.8'
sout, serr = shell(cmd.split())
我添加此问题阅读一些subprocess.Popen标准输出。 这是我的非阻塞读溶液:
import fcntl
def non_block_read(output):
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
try:
return output.read()
except:
return ""
# Use example
from subprocess import *
sb = Popen("echo test && sleep 1000", shell=True, stdout=PIPE)
sb.kill()
# sb.stdout.read() # <-- This will block
non_block_read(sb.stdout)
'test\n'
下面是我的代码,用来捕捉从子每个输出的ASAP,包括局部线。它泵在几乎正确的顺序相同的时间和输出和错误。
测试和关于Python 2.7 Linux和窗口工作正常。
#!/usr/bin/python
#
# Runner with stdout/stderr catcher
#
from sys import argv
from subprocess import Popen, PIPE
import os, io
from threading import Thread
import Queue
def __main__():
if (len(argv) > 1) and (argv[-1] == "-sub-"):
import time, sys
print "Application runned!"
time.sleep(2)
print "Slept 2 second"
time.sleep(1)
print "Slept 1 additional second",
time.sleep(2)
sys.stderr.write("Stderr output after 5 seconds")
print "Eol on stdin"
sys.stderr.write("Eol on stderr\n")
time.sleep(1)
print "Wow, we have end of work!",
else:
os.environ["PYTHONUNBUFFERED"]="1"
try:
p = Popen( argv + ["-sub-"],
bufsize=0, # line-buffered
stdin=PIPE, stdout=PIPE, stderr=PIPE )
except WindowsError, W:
if W.winerror==193:
p = Popen( argv + ["-sub-"],
shell=True, # Try to run via shell
bufsize=0, # line-buffered
stdin=PIPE, stdout=PIPE, stderr=PIPE )
else:
raise
inp = Queue.Queue()
sout = io.open(p.stdout.fileno(), 'rb', closefd=False)
serr = io.open(p.stderr.fileno(), 'rb', closefd=False)
def Pump(stream, category):
queue = Queue.Queue()
def rdr():
while True:
buf = stream.read1(8192)
if len(buf)>0:
queue.put( buf )
else:
queue.put( None )
return
def clct():
active = True
while active:
r = queue.get()
try:
while True:
r1 = queue.get(timeout=0.005)
if r1 is None:
active = False
break
else:
r += r1
except Queue.Empty:
pass
inp.put( (category, r) )
for tgt in [rdr, clct]:
th = Thread(target=tgt)
th.setDaemon(True)
th.start()
Pump(sout, 'stdout')
Pump(serr, 'stderr')
while p.poll() is None:
# App still working
try:
chan,line = inp.get(timeout = 1.0)
if chan=='stdout':
print "STDOUT>>", line, "<?<"
elif chan=='stderr':
print " ERROR==", line, "=?="
except Queue.Empty:
pass
print "Finish"
if __name__ == '__main__':
__main__()
加入这个答案在这里,因为它提供了能力设置非阻挡的管道上的窗户和Unix。
所有 ctypes
细节谢谢 @techtonik的答案.
有一个略微的修改版本可以使用两on Unix and Windows系统。
- Python3兼容 (仅有微小的变化需要的).
- 包括posix版本,并限定的例外使用。
这种方式可以使用相同的功能和异常for Unix and Windows代码。
# pipe_non_blocking.py (module)
"""
Example use:
p = subprocess.Popen(
command,
stdout=subprocess.PIPE,
)
pipe_non_blocking_set(p.stdout.fileno())
try:
data = os.read(p.stdout.fileno(), 1)
except PortableBlockingIOError as ex:
if not pipe_non_blocking_is_error_blocking(ex):
raise ex
"""
__all__ = (
"pipe_non_blocking_set",
"pipe_non_blocking_is_error_blocking",
"PortableBlockingIOError",
)
import os
if os.name == "nt":
def pipe_non_blocking_set(fd):
# Constant could define globally but avoid polluting the name-space
# thanks to: https://stackoverflow.com/questions/34504970
import msvcrt
from ctypes import windll, byref, wintypes, WinError, POINTER
from ctypes.wintypes import HANDLE, DWORD, BOOL
LPDWORD = POINTER(DWORD)
PIPE_NOWAIT = wintypes.DWORD(0x00000001)
def pipe_no_wait(pipefd):
SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
SetNamedPipeHandleState.restype = BOOL
h = msvcrt.get_osfhandle(pipefd)
res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
if res == 0:
print(WinError())
return False
return True
return pipe_no_wait(fd)
def pipe_non_blocking_is_error_blocking(ex):
if not isinstance(ex, PortableBlockingIOError):
return False
from ctypes import GetLastError
ERROR_NO_DATA = 232
return (GetLastError() == ERROR_NO_DATA)
PortableBlockingIOError = OSError
else:
def pipe_non_blocking_set(fd):
import fcntl
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
return True
def pipe_non_blocking_is_error_blocking(ex):
if not isinstance(ex, PortableBlockingIOError):
return False
return True
PortableBlockingIOError = BlockingIOError
为了避免读不完整的数据,我结束了写作我自己的readline发电机(其返回字节串每个线)。
其一生所以你可以例如...
def non_blocking_readlines(f, chunk=1024):
"""
Iterate over lines, yielding b'' when nothings left
or when new data is not yet available.
stdout_iter = iter(non_blocking_readlines(process.stdout))
line = next(stdout_iter) # will be a line or b''.
"""
import os
from .pipe_non_blocking import (
pipe_non_blocking_set,
pipe_non_blocking_is_error_blocking,
PortableBlockingIOError,
)
fd = f.fileno()
pipe_non_blocking_set(fd)
blocks = []
while True:
try:
data = os.read(fd, chunk)
if not data:
# case were reading finishes with no trailing newline
yield b''.join(blocks)
blocks.clear()
except PortableBlockingIOError as ex:
if not pipe_non_blocking_is_error_blocking(ex):
raise ex
yield b''
continue
while True:
n = data.find(b'\n')
if n == -1:
break
yield b''.join(blocks) + data[:n + 1]
data = data[n + 1:]
blocks.clear()
blocks.append(data)
我有原来的提问的问题,但不希望调用线程。我混杰西的解决方案从管道直接读取(),和我自己的缓冲处理程序行的内容(但是,我的子进程 - 平 - 总是写全行<系统页面大小)。我避免忙等待只在GObject的注册IO表读数。这些天我通常GObject的MainLoop语句中运行的代码来避免线程。
def set_up_ping(ip, w):
# run the sub-process
# watch the resultant pipe
p = subprocess.Popen(['/bin/ping', ip], stdout=subprocess.PIPE)
# make stdout a non-blocking file
fl = fcntl.fcntl(p.stdout, fcntl.F_GETFL)
fcntl.fcntl(p.stdout, fcntl.F_SETFL, fl | os.O_NONBLOCK)
stdout_gid = gobject.io_add_watch(p.stdout, gobject.IO_IN, w)
return stdout_gid # for shutting down
在观察者是
def watch(f, *other):
print 'reading',f.read()
return True
和主程序设置了一个平,然后调用的GObject邮件循环。
def main():
set_up_ping('192.168.1.8', watch)
# discard gid as unused here
gobject.MainLoop().run()
任何其他工作连接到回调中的GObject。
href="http://www.python.org/doc/2.5.2/lib/module-select.html" rel="nofollow noreferrer">选择模块
但是,你几乎用单独的线永远快乐。一个不阻塞读标准输入,另一位则无论它是你不想阻止。
为什么困扰螺纹&排队? 不像的ReadLine(),BufferedReader.read1()不会阻塞等待\ r \ n,它就返回尽快如果在未来任何输出。
#!/usr/bin/python
from subprocess import Popen, PIPE, STDOUT
import io
def __main__():
try:
p = Popen( ["ping", "-n", "3", "127.0.0.1"], stdin=PIPE, stdout=PIPE, stderr=STDOUT )
except: print("Popen failed"); quit()
sout = io.open(p.stdout.fileno(), 'rb', closefd=False)
while True:
buf = sout.read1(1024)
if len(buf) == 0: break
print buf,
if __name__ == '__main__':
__main__()
在我的情况下,我需要从背景应用捕获输出和去扩充记录模块(添加时间标记,颜色,等等)。
我结束了后台线程完成实际I / O。下面的代码只对POSIX平台。我剥离非必要的部分。
如果有人会长期运行管理考虑打开的描述符使用此兽。在我而言,这不是一个大问题。
# -*- python -*-
import fcntl
import threading
import sys, os, errno
import subprocess
class Logger(threading.Thread):
def __init__(self, *modules):
threading.Thread.__init__(self)
try:
from select import epoll, EPOLLIN
self.__poll = epoll()
self.__evt = EPOLLIN
self.__to = -1
except:
from select import poll, POLLIN
print 'epoll is not available'
self.__poll = poll()
self.__evt = POLLIN
self.__to = 100
self.__fds = {}
self.daemon = True
self.start()
def run(self):
while True:
events = self.__poll.poll(self.__to)
for fd, ev in events:
if (ev&self.__evt) != self.__evt:
continue
try:
self.__fds[fd].run()
except Exception, e:
print e
def add(self, fd, log):
assert not self.__fds.has_key(fd)
self.__fds[fd] = log
self.__poll.register(fd, self.__evt)
class log:
logger = Logger()
def __init__(self, name):
self.__name = name
self.__piped = False
def fileno(self):
if self.__piped:
return self.write
self.read, self.write = os.pipe()
fl = fcntl.fcntl(self.read, fcntl.F_GETFL)
fcntl.fcntl(self.read, fcntl.F_SETFL, fl | os.O_NONBLOCK)
self.fdRead = os.fdopen(self.read)
self.logger.add(self.read, self)
self.__piped = True
return self.write
def __run(self, line):
self.chat(line, nl=False)
def run(self):
while True:
try: line = self.fdRead.readline()
except IOError, exc:
if exc.errno == errno.EAGAIN:
return
raise
self.__run(line)
def chat(self, line, nl=True):
if nl: nl = '\n'
else: nl = ''
sys.stdout.write('[%s] %s%s' % (self.__name, line, nl))
def system(command, param=[], cwd=None, env=None, input=None, output=None):
args = [command] + param
p = subprocess.Popen(args, cwd=cwd, stdout=output, stderr=output, stdin=input, env=env, bufsize=0)
p.wait()
ls = log('ls')
ls.chat('go')
system("ls", ['-l', '/'], output=ls)
date = log('date')
date.chat('go')
system("date", output=date)
我已经基于 J. F.塞巴斯蒂安的解决方案。你可以使用它。
从J.F.塞巴斯蒂安的回答,和其他几个来源的工作,我已经把一个简单的子经理。它提供了要求无阻塞读数,以及并行运行几个过程。它不使用任何特定的操作系统调用(据我所知),因此应该在任何地方工作。
这是从PyPI中,所以才pip install shelljob
。请参考例子和全文档的项目页面。
编辑:仍然此实现的块。使用J.F.Sebastian的回答代替。
<击>我试过顶端回答,但额外的风险和线程代码维护是令人担忧的。击>
<击> 击><击>寻找通过 IO模块(和被限制到2.6),我发现BufferedReader类。这是我的无螺纹的,非封闭溶液。击>
import io
from subprocess import PIPE, Popen
p = Popen(['myprogram.exe'], stdout=PIPE)
SLEEP_DELAY = 0.001
# Create an io.BufferedReader on the file descriptor for stdout
with io.open(p.stdout.fileno(), 'rb', closefd=False) as buffer:
while p.poll() == None:
time.sleep(SLEEP_DELAY)
while '\n' in bufferedStdout.peek(bufferedStdout.buffer_size):
line = buffer.readline()
# do stuff with the line
# Handle any remaining output after the process has ended
while buffer.peek():
line = buffer.readline()
# do stuff with the line
我最近偶然发现同样的问题 我需要时间从流(尾翼在子运行)读取一行 在非阻塞模式 我想避免下一个问题:不烧CPU,不要用一个字节读取数据流(如readline的那样)等
下面是我的实现 https://gist.github.com/grubberr/5501e1a9760c3eab5e0a 它不支持Windows(调查),不处理EOF, 但它为我好
这是运行在子交互式命令一个示例,并且stdout是通过使用伪终端互动。可以参考: https://stackoverflow.com/a/43012138/3555925
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import select
import termios
import tty
import pty
from subprocess import Popen
command = 'bash'
# command = 'docker run -it --rm centos /bin/bash'.split()
# save original tty setting then set it to raw mode
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
# open pseudo-terminal to interact with subprocess
master_fd, slave_fd = pty.openpty()
# use os.setsid() make it run in a new process group, or bash job control will not be enabled
p = Popen(command,
preexec_fn=os.setsid,
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
universal_newlines=True)
while p.poll() is None:
r, w, e = select.select([sys.stdin, master_fd], [], [])
if sys.stdin in r:
d = os.read(sys.stdin.fileno(), 10240)
os.write(master_fd, d)
elif master_fd in r:
o = os.read(master_fd, 10240)
if o:
os.write(sys.stdout.fileno(), o)
# restore tty settings back
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
我的问题是有点不同,因为我想收集来自正在运行的进程既stdout和stderr,但最终由于我想呈现一个插件的输出作为相同将其产生的。
我不希望诉诸许多使用队列或额外的线程所提出的解决方法,因为他们没有必要进行这样一个共同的任务,运行另一个脚本,并收集其输出。
阅读所提出的解决方案和python文档后,我决心与下面的执行了我的问题。是的,它是我使用的select
函数调用仅适用于POSIX。
我同意文档是混乱和实现是笨拙这种共同的脚本的任务。我认为,旧版本的Python有Popen
和不同的解释,这样造就了很多混乱的不同的默认值。这似乎也为双方的Python 2.7.12和3.5.2工作。
的关键是对行缓冲设置bufsize=1
然后universal_newlines=True
处理为一个文本文件,而不是一个二值这似乎设置bufsize=1
时成为默认值。
class workerThread(QThread):
def __init__(self, cmd):
QThread.__init__(self)
self.cmd = cmd
self.result = None ## return code
self.error = None ## flag indicates an error
self.errorstr = "" ## info message about the error
def __del__(self):
self.wait()
DEBUG("Thread removed")
def run(self):
cmd_list = self.cmd.split(" ")
try:
cmd = subprocess.Popen(cmd_list, bufsize=1, stdin=None
, universal_newlines=True
, stderr=subprocess.PIPE
, stdout=subprocess.PIPE)
except OSError:
self.error = 1
self.errorstr = "Failed to execute " + self.cmd
ERROR(self.errorstr)
finally:
VERBOSE("task started...")
import select
while True:
try:
r,w,x = select.select([cmd.stdout, cmd.stderr],[],[])
if cmd.stderr in r:
line = cmd.stderr.readline()
if line != "":
line = line.strip()
self.emit(SIGNAL("update_error(QString)"), line)
if cmd.stdout in r:
line = cmd.stdout.readline()
if line == "":
break
line = line.strip()
self.emit(SIGNAL("update_output(QString)"), line)
except IOError:
pass
cmd.wait()
self.result = cmd.returncode
if self.result < 0:
self.error = 1
self.errorstr = "Task terminated by signal " + str(self.result)
ERROR(self.errorstr)
return
if self.result:
self.error = 1
self.errorstr = "exit code " + str(self.result)
ERROR(self.errorstr)
return
return
ERROR,DEBUG和VERBOSE只是打印输出到终端宏。
此溶液是IMHO 99.99%有效,因为它仍然使用阻挡readline
功能,所以我们假设子过程是好的和输出完整的生产线。
我欢迎反馈来改进解决方案,我仍然新到Python。
此解决方案使用select
模块“读取任何可用的数据”从IO流。此功能块最初,直到可用的数据,但随后只读取可用,并且不进一步阻挡。数据
鉴于它使用select
模块的事实,这仅适用于Unix。
的代码是完全PEP8兼容。
import select
def read_available(input_stream, max_bytes=None):
"""
Blocks until any data is available, then all available data is then read and returned.
This function returns an empty string when end of stream is reached.
Args:
input_stream: The stream to read from.
max_bytes (int|None): The maximum number of bytes to read. This function may return fewer bytes than this.
Returns:
str
"""
# Prepare local variables
input_streams = [input_stream]
empty_list = []
read_buffer = ""
# Initially block for input using 'select'
if len(select.select(input_streams, empty_list, empty_list)[0]) > 0:
# Poll read-readiness using 'select'
def select_func():
return len(select.select(input_streams, empty_list, empty_list, 0)[0]) > 0
# Create while function based on parameters
if max_bytes is not None:
def while_func():
return (len(read_buffer) < max_bytes) and select_func()
else:
while_func = select_func
while True:
# Read single byte at a time
read_data = input_stream.read(1)
if len(read_data) == 0:
# End of stream
break
# Append byte to string buffer
read_buffer += read_data
# Check if more data is available
if not while_func():
break
# Return read buffer
return read_buffer
我也遇到了所描述的问题 杰西 并通过使用“select”作为解决它 布拉德利, 安迪 和其他人这样做,但处于阻塞模式以避免繁忙循环。它使用虚拟管道作为假标准输入。select 阻塞并等待 stdin 或管道准备就绪。当按下某个键时,stdin 会解锁选择,并且可以使用 read(1) 检索键值。当不同的线程写入管道时,管道会解锁选择,并且可以将其视为对 stdin 的需求结束的指示。这是一些参考代码:
import sys
import os
from select import select
# -------------------------------------------------------------------------
# Set the pipe (fake stdin) to simulate a final key stroke
# which will unblock the select statement
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
writeFile = os.fdopen(writeEnd, "w")
# -------------------------------------------------------------------------
def getKey():
# Wait for stdin or pipe (fake stdin) to be ready
dr,dw,de = select([sys.__stdin__, readFile], [], [])
# If stdin is the one ready then read it and return value
if sys.__stdin__ in dr:
return sys.__stdin__.read(1) # For Windows use ----> getch() from module msvcrt
# Must finish
else:
return None
# -------------------------------------------------------------------------
def breakStdinRead():
writeFile.write(' ')
writeFile.flush()
# -------------------------------------------------------------------------
# MAIN CODE
# Get key stroke
key = getKey()
# Keyboard input
if key:
# ... do your stuff with the key value
# Faked keystroke
else:
# ... use of stdin finished
# -------------------------------------------------------------------------
# OTHER THREAD CODE
breakStdinRead()
东西在现代的Python好多了。
下面是一个简单的子程序, “hello.py”:
#!/usr/bin/env python3
while True:
i = input()
if i == "quit":
break
print(f"hello {i}")
和一个程序来与它进行交互:
import asyncio
async def main():
proc = await asyncio.subprocess.create_subprocess_exec(
"./hello.py", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE
)
proc.stdin.write(b"bob\n")
print(await proc.stdout.read(1024))
proc.stdin.write(b"alice\n")
print(await proc.stdout.read(1024))
proc.stdin.write(b"quit\n")
await proc.wait()
asyncio.run(main())
打印出:
b'hello bob\n'
b'hello alice\n'
请注意,实际的模式,该模式在这里和相关的问题也被几乎所有的以前的答案的,是孩子的标准输出文件描述符设置为非阻塞,然后在某种选择循环轮询它。这些天,当然,该环由ASYNCIO提供。
下面是一种支持非阻塞一个模块读取和背景在python写道:
https://pypi.python.org/pypi/python-nonblock
提供一个功能,
nonblock_read将从流中读取数据,如果有的话,否则返回一个空字符串(或无如果流被关闭在另一侧上和所有可能的数据已被读取)
您也可以考虑蟒-subprocess2模块,
https://pypi.python.org/pypi/python-subprocess2
,这增加了子模块。因此,从“subprocess.Popen”返回的对象上加入另外的方法,runInBackground。这将启动一个线程,并返回它会自动填充作为东西被写入stdout / stderr的一个对象,而不会阻塞主线程。
享受!