Python 中生成并等待子进程

发布于 2024-09-04 10:23:59 字数 529 浏览 4 评论 0原文

代码的相关部分如下所示:

pids = [] 
for size in SIZES:
    pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions]))

# Wait for all spawned imagemagick processes to finish
while pids:
    (pid, status) = os.waitpid(0, 0)
    if pid:
        pids.remove(pid)

这应该做的是关闭所有进程,然后等待每个进程完成后再继续。它所做的大部分工作都是有效的,但有时会在下一部分中崩溃(当它期望所有这些过程都完成时)。

这有什么问题吗?有更好的方法吗?

它必须工作的环境是带有Python 2.4的CentOS,但我正在带有Python 2.5的Cygwin上进行测试,因此它可能在我的机器上失败,但在Linux机器上可以工作(Linux机器非常慢,这错误很少见,所以我无法在那里得到它)。

The relevant part of the code looks like this:

pids = [] 
for size in SIZES:
    pids.append(os.spawnv(os.P_NOWAIT, RESIZECMD, [RESIZECMD, lotsOfOptions]))

# Wait for all spawned imagemagick processes to finish
while pids:
    (pid, status) = os.waitpid(0, 0)
    if pid:
        pids.remove(pid)

What this should be doing is spawning all of the processes off, then waiting for each process to finish before continuing. What it does is work for the most part but sometimes crash on the next section (when it expects all of these processes to be finished).

Is there something wrong with this? Is there a better way of doing it?

The environment it has to work on is CentOS with Python 2.4, but I'm testing on Cygwin with Python 2.5, so it could be that it fails on my machine but will work on the Linux one (the Linux machine is very slow and this error is rare, so I haven't been able to get it on there).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

李不 2024-09-11 10:23:59

启动子流程的推荐方法是使用 subprocess 模块。

pipe = Popen(["program", "arg1", "arg2"])
pipe.wait()

The recommended way to start subprocess is to use the subprocess module.

pipe = Popen(["program", "arg1", "arg2"])
pipe.wait()
夜声 2024-09-11 10:23:59

我建议您安装 python-subprocess32 —— Python 3 版本的强大向后移植subprocess 标准库模块,适用于 Python 2.4 到 2.7,也是迄今为止在 Python 2 中运行子进程的最佳方式。然后,在您将执行的循环中,

pids.append(subprocess.Popen([RESIZECMD, lot, of, options])

以下循环将是一个简单的

for pid in pids:
    pid.wait()

I would recommend you install python-subprocess32 -- a robust backport of Python 3's version of the subprocess standard library module, suitable for Python 2.4 to 2.7, and by far the best way to run subprocesses in Python 2. Then, in the loop you'll do

pids.append(subprocess.Popen([RESIZECMD, lot, of, options])

and the following loop will just be a simple

for pid in pids:
    pid.wait()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文