use*_*925 5 python python-multiprocessing
我有一个 python 脚本,它应该并行运行多个作业。我将最大进程设置为 20,但我需要脚本在发送作业之间休眠 5 秒。这是我的示例代码:
#!/usr/bin/env python
import multiprocessing
import subprocess
def prcss(cmd):
sbc = subprocess.call
com = sbc(cmd, shell='True')
return (com)
if __name__=='__main__':
s = 'sleep 5'
cmd= []
for j in range(1,21):
for i in range(10):
sis = "nohup ~/mycodes/code > str(j)"+"/"+"out"+str(i)+".dat"
cmd.append(sis)
cmd.append(s)
pool=multiprocessing.Pool(processes=20)
pool.map(prcss,cmd)
Run Code Online (Sandbox Code Playgroud)
尽管我在“sis”命令之间有睡眠 5 个时间,但当我运行脚本时,所有作业都会立即启动。我需要在“sis”命令之间休息一下,因为每个作业的输出取决于计算机时钟。因此,如果我运行 20 个作业,它们都以相同的系统时钟启动,因此它们都将具有相同的输出。
知道如何让我的脚本在“sis”命令之间休眠吗?
阿贝丁
查看pool.map() 的文档。当您创建项目列表,然后使用映射将它们提交到池中时,所有作业都会一起提交到池中。由于您有 20 个工作进程,因此您的 20 个作业将(有效)同时启动。这包括您的sis命令和睡眠命令。甚至不能保证它们将以相同的顺序执行和完成,只是您会以相同的顺序收到结果。apply_async ()函数可能更适合您,因为您可以控制作业何时提交到池中。
在我看来,无论如何,您都希望 Python 脚本在发出命令之前等待 5 秒sis,因此您没有理由需要在工作进程中执行 sleep 命令。尝试重构为这样的内容:
import multiprocessing
import subprocess
import time
def prcss(cmd):
# renaming the subprocess call is silly - remove the rename
com = subprocess.call(cmd, shell='True')
return (com)
if __name__=='__main__':
pool = multiprocessing.Pool(processes=20)
results_objects = []
for j in range(1,21):
for i in range(10):
sis = 'nohup ~/mycodes/code >'+str(j)+'/'+'out'+str(i)+'.dat'
# make an asynchronous that will execute our target function with the
# sis command
results_objects.append(pool.apply_async(prcss, args=(sis,))
# don't forget the extra comma in the args - Process must receive a tuple
# now we pause for five sections before submitting the next job
time.sleep(5)
# close the pool and wait for everything to finish
pool.close()
pool.join()
# retrieve all of the results
result = [result.get() for result in results_objects]
Run Code Online (Sandbox Code Playgroud)
另请注意:由于应用了语法突出显示,因此很容易发现字符串中缺少结束引号sis,并且可能还缺少“+”。考虑使用string.format(),而不是手动构建字符串:
sis = 'nohup ~/mycodes/code > {}/out{}.dat'.format(j, i)
Run Code Online (Sandbox Code Playgroud)
如果反斜杠用于分隔路径层次结构,则应该使用os.path.join():
import os
sis = os.path.join('nohup ~/mycodes/code > {}'.format(j), 'out{}.dat'.format(i))
Run Code Online (Sandbox Code Playgroud)
生成的第一个字符串(无论哪种情况)将是:
nohup ~/mycodes/code > 1/out0.dat
| 归档时间: |
|
| 查看次数: |
18690 次 |
| 最近记录: |