use*_*743 2 subprocess tcsh nonblocking python-2.7
对于围绕perl的包装,我需要python中的非阻塞子进程(有各种类型的shell io)。另外,我对shell输出和返回值感兴趣。有时返回值为0,但是代码实际上并没有执行任何操作。
所以我现在可以使用subprocess.call()(非阻塞但不输出shell)或subprocess.Popen()(阻塞但shell输出)来执行。
我做了一些阅读,但是唯一的解决方案看起来像是拥有一个单独的队列来执行此操作。有什么更容易错过的吗?
subprocess.Popen不是天生的阻碍。您仍然可以使用proc.stdin.write()和proc.stdout.read(); 唯一的问题是,如果管道填满,您可能会在一侧阻塞甚至死锁[1]。如果您知道子流程只会读取或写入少量数据,则不必担心。
因此,您可以执行以下操作:
proc = subprocess.Popen(['perl', 'somescript.pl'], stdout=subprocess.PIPE)
buf = StringIO()
CHUNKSIZE = 1024 # how much to read at a time
while True:
# do whatever other time-consuming work you want here, including monitoring
# other processes...
# this keeps the pipe from filling up
buf.write(proc.stdout.read(CHUNKSIZE))
proc.poll()
if proc.returncode is not None:
# process has finished running
buf.write(proc.stdout.read())
print "return code is", proc.returncode
print "output is", buf.getvalue()
break
Run Code Online (Sandbox Code Playgroud)
在更大的应用程序中,您可以安排在事件循环,反应堆等中发生这种情况。
[1]操作系统一次只允许将如此多的数据放入管道中。假设您cat以子流程运行,并将大量数据写入其标准输入。 cat会将数据写入其自己的stdout直到填满,然后阻塞,直到程序从stdout读取一些数据并清空管道。但是您的程序仍在写入stdin,并且cat不再从其中读取数据,因此管道也将填满。这两个进程都将阻塞写操作,等待另一个进程读取,这将永远不会发生。
| 归档时间: |
|
| 查看次数: |
3446 次 |
| 最近记录: |