python - 计算python中子进程/子进程的数量

标签 python bash macos

我没有软件背景,因此请原谅任何不正确的术语。

我想在 python 脚本中创建一个循环来监视创建的子进程的数量。下面是 python 代码的示例:

for x in list:
   os.system('program --input %s &' % (x))
   while int(subprocess.check_output("echo $(pgrep -c -P$$)", shell=True)) > n-1:
        time.sleep(0.25)

这里的目标是同时运行多个作业(有 10,000 个<)而不使系统过载。作业在后台运行,当正在运行的作业数量低于一定数量 (n-1) 时,下一个作业开始。

上面的代码在 ubuntu 中运行 .py 脚本时有效,但由于缺少 pgrep 的 -c 选项而无法在 macOS 中运行。

使用以下内容:

subprocess.check_output("pgrep -P$$ | wc -l", shell=True)

...在 Mac 终端中可以工作,但无法使用 os.system() 从 python 中返回正确的值。通过打开的 python 控制台运行代码或将其作为脚本执行时会有区别吗?

是否有更好(也许更Pythonic)或更智能的方法来编写代码,以允许此循环在macOS上运行而无需安装不同版本的pgrep?也许通过使用 psutil 模块或通过某种 popen 函数在它自己的子线程中运行程序来使用,使它们更容易监视?

非常感谢!


编辑:
修改后的代码:

import subprocess 
import psutil
import time

def childCount():
    current_process = psutil.Process()
    children = current_process.children()
    return(len(children))

for x in range(1,11):
    subprocess.Popen(['sleep 2'], shell=True)
    print('running %s' % (str(x)))
    while childCount() > 4:
        time.sleep(0.25)

但是,现在的问题是脚本在第五次迭代时挂起。当子进程(在本例中为 sleep)完成运行时,subprocess.Popen 打开的新进程可能不会终止或关闭?

非常感谢!

最佳答案

您所拥有的是来自父进程的一堆僵尸子进程(即子进程调用),它们在终止之前不等待退出状态。

import subprocess 
import psutil
import time

def childCount():
    current_process = psutil.Process()
    children = current_process.children()
    return(len(children))

for x in range(1,11):
    p = subprocess.Popen(['sleep 2'], shell=True) # save the Popen instance
    print('running %s' % (str(x)))
    while childCount() > 4:
        time.sleep(0.25)
        p.communicate() # this will get the exit code

通过使用 Popen.communicate 获取退出状态,您将释放您的僵尸 child 。

关于python - 计算python中子进程/子进程的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918725/

相关文章:

php - MYSQL PID/SOCK 错误 - 我无法让我的 Mac El Capitan 与完整的 Web 服务器配合使用

windows - Electron:是否可以检索文件上次访问的日期和时间

python - 更新 txt 文件以检查 python 将数据保存到其中

regex - 在 linux 目录中查找与模式匹配的文件数

linux sed,如何删除剩下的字?

python - 如何从 python 脚本中打破 bash for 循环?

c - 您希望应用程序接受传入的网络连接吗?

python - 在 python/numpy 中随机放置给定数字的矩阵

python - 如何在Python中测试线程

python - 将 "string"作为原始二进制文件写入 Python 文件