Skip to main content
 首页 » 编程设计

执行之间的python多处理 sleep

2024年10月25日13xiaohuochai

我有一个 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) 

虽然我在“sis”命令之间有 sleep 5,但当我运行我的脚本时,所有作业都会立即启动。我需要在“sis”命令之间 sleep ,因为每个作业的输出取决于计算机时钟。所以如果我运行 20 个作业,它们都以相同的系统时钟开始,因此它们都有相同的输出。

知道如何让我的脚本在“sis”命令之间休眠吗?

阿贝丁

请您参考如下方法:

看看 docs for pool.map() .当您创建一个项目列表,然后使用 map 将它们提交到池中时,所有作业都会一起提交到池中。由于您有 20 个工作进程,因此您的 20 个作业将同时(有效地)全部启动。这包括您的 sis 命令和 sleep 命令。甚至不能保证它们将以相同的顺序执行和完成,只是您将以相同的顺序收到结果。 apply_async()函数可能更适合您,因为您可以控制何时将作业提交到池中。

在我看来,无论如何您都希望 Python 脚本在发出 sis 命令之前等待 5 秒,因此您没有理由需要在工作进程中执行 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] 

另一个注意事项:由于应用了语法突出显示,很容易看出您在 sis 字符串中缺少一个结束引号,并且可能还有一个“+”。与其手动构建字符串,不如考虑使用 string.format() :

sis = 'nohup ~/mycodes/code > {}/out{}.dat'.format(j, i) 

如果反斜杠用于分隔路径层次结构,则应使用 os.path.join() :

import os 
sis = os.path.join('nohup ~/mycodes/code > {}'.format(j), 'out{}.dat'.format(i)) 

生成的第一个字符串(无论哪种情况)将是:

nohup ~/mycodes/code > 1/out0.dat