两次执行之间的Python多进程休眠 [英] python multiprocessing sleep between executions

查看:10
本文介绍了两次执行之间的Python多进程休眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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"命令之间进行睡眠,因为每个作业的输出取决于计算机时钟。因此,如果我运行20个作业,它们都以相同的系统时钟开始,因此它们都将具有相同的输出。

你知道如何让我的脚本在‘sis’命令之间休眠吗?

阿贝丁

推荐答案

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

在我看来,无论如何,您都希望在发出sis命令之前等待5秒钟,所以您没有理由需要在工作进程中执行睡眠命令。尝试重构为类似以下内容:

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

这篇关于两次执行之间的Python多进程休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆