Python 中生成并等待子进程
代码的相关部分如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
启动子流程的推荐方法是使用 subprocess 模块。
The recommended way to start subprocess is to use the subprocess module.
我建议您安装 python-subprocess32 —— Python 3 版本的强大向后移植
subprocess
标准库模块,适用于 Python 2.4 到 2.7,也是迄今为止在 Python 2 中运行子进程的最佳方式。然后,在您将执行的循环中,以下循环将是一个简单的
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 doand the following loop will just be a simple