gpt4 book ai didi

python-2.7 - python中的非阻塞子进程

转载 作者:行者123 更新时间:2023-12-02 05:14:11 30 4
gpt4 key购买 nike

对于 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

在更大的应用程序中,您可以安排它在您的事件循环、 react 器等中发生。


[1] 操作系统一次只允许管道中容纳这么多数据。假设您将 cat 作为您的子进程运行,并将大量数据写入其标准输入。 cat 会将数据写入它自己的标准输出,直到它填满,然后它会阻塞,直到您的程序从标准输出读取一些数据并清空管道。但是您的程序仍在写入 stdin,并且 cat 不再从中读取,因此管道也会被填满。两个进程都将阻塞写入,等待另一个进程读取,这种情况永远不会发生。

关于python-2.7 - python中的非阻塞子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14924890/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com