使用os.system等待子级

2024-06-07 07:04:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用很多os.system调用在for循环中创建后台进程。如何等待所有后台进程结束?

os.wait告诉我没有子进程。

ps:我正在使用Solaris

这是我的代码:

#!/usr/bin/python
import subprocess
import os

pids = []
NB_PROC=30

for i in xrange(NB_PROC):
        p = subprocess.Popen("(time wget http://site.com/test.php 2>&1 | grep real )&", shell=True)
        pids.insert(0,p)
        p = subprocess.Popen("(time wget http://site.com/test.php 2>&1 | grep real )&", shell=True)
        pids.insert(0,p)

for i in xrange(NB_PROC*2):
        pids[i].wait()
os.system("rm test.php*")

Tags: intestimportfor进程osprocsystem
2条回答

解决方案确实在子流程模块中

#!/usr/bin/python
import subprocess
import os

pids = []
NB_PROC=4
cmd="(time wget http://site.com/test.php 2>&1 | grep elapsed | cut -d ' ' -f 3)"

for i in xrange(NB_PROC):
    p = subprocess.Popen(cmd,stdin=None,stdout=None, shell=True)
    pids.insert(0,p)
    print "request %d processed" % (i+1)


for i in xrange(NB_PROC):
    pids[i].wait()
os.system("rm test.php*")

在这个过程中切换到debian,但由于某些原因,有时脚本挂起,而有时它运行得很好

通常,os.system()在子进程完成时返回。因此,实际上os.wait()没有什么可做的。它相当于subprocess.call()

使用subprocess.Popen()创建后台进程,然后Popen对象的wait()poll()方法等待它们退出。

默认情况下,Popen不生成shell,而是直接执行程序。这样可以节省资源并防止可能的shell注入攻击。

根据os.system()的文档:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function

如果要并行执行多个作业,请考虑使用multiprocessing,特别是Pool对象。它在几个过程中处理了许多农业工作的细节。

编辑:计时程序的执行

import time
import subprocess

t1 = time.clock()
t2 = time.clock()
overhead = t2-t1

t1 = time.clock()
subprocess.call(['wget', 'http://site.com/test.php'])
t2 = time.clock()
print 'elapsed time: {:.3f} seconds.'.format(t2-t1-overhead)

相关问题 更多 >