在python中尝试使用子进程时出现分段错误(内核转储)

在python中尝试使用子进程时出现分段错误(内核转储),python,python-3.x,subprocess,Python,Python 3.x,Subprocess,我试图用不同的参数多次并行运行一个程序。我在网上搜索,发现python中的子流程是一种很好的方法。我的代码如下: import subprocess import os models_path="~/" procs = [] num_of_procs_running=0 i = 0 for model_name in os.listdir(models_path): if num_of_procs_running > num_of_procs: for p in

我试图用不同的参数多次并行运行一个程序。我在网上搜索,发现python中的子流程是一种很好的方法。我的代码如下:

import subprocess
import os

models_path="~/"
procs = []
num_of_procs_running=0
i = 0
for model_name in os.listdir(models_path):
    if num_of_procs_running > num_of_procs:
        for p in procs:
            p.wait()
        procs = []
        num_of_procs_running = 0
    elif model_name.endswith(".onnx"):
        name, ending = model_name.split(".")
        runner = './SOME_PROGRAM '+str(i)+'> output.txt'
        i+=1
        procs.append(subprocess.Popen(runner,shell=True))
        num_of_procs_running += 1
        print("Total processes:",num_of_procs_running)
        print("\n")
for p in procs:
    p.wait()
如果我试图运行56个以上的子进程,我就会被转储。我的机器有56个CPU,每个CPU有12个内核。如何运行56个以上的子进程,或者如何使用线程? 谢谢

因为@danielpryden已经不调用shell了:

import subprocess

# bad (mocking your code)
p = subprocess.Popen("echo 1 > output.txt", shell=True)
p.wait()

# better
fp = open("output.txt", "w")
p = subprocess.Popen(["echo", "1"], stdout=fp)

p.wait() # or do something else
fp.close() # remember to close file
当达到最大线程数时,它会等待所有线程都完成,效率很低。你似乎想要实现的正是:

分段错误不是由Python应用程序引起的,而是由您试图执行的任何程序引起的。如果是C++,请看一下;您需要更改程序代码,而不是python脚本


调试的第一步需要找到一种方法,在直接运行MY_程序可执行文件时可靠地触发segfault。然后启动一个调试器,比如gdb,看看它为什么会崩溃。您的Python代码不是这里的问题-问题不知怎么地存在于我的_程序中。顺便说一句:不要使用shell=True,尤其是当您像这样手动组装参数时。只需直接传递参数列表。是否有不使用名称和结尾的原因?@DavidCullen是的。它正在我的原始代码中使用。这篇文章没有必要。。这是发送给程序的参数之一。@GuyOhayon:通常应避免在一个字符串中传递参数。为什么要启动一个完整的单独的shell进程来将字符串解析为字符串列表呢?如果您不小心错误地组装了字符串,shell可能会执行您意想不到的任意命令,而如果您传递了字符串列表,则不会发生这种情况。但是,请回答您的另一个问题:在这两种情况下,您能否复制完全相同的命令行?您是否可以尝试以其他方式复制环境匹配环境变量、重定向或关闭stdin/stdout等?注释。
from multiprocessing.pool import Pool

# mocking your code
modules = ["mod1.onnx", "mod2.onnx"]

def run(module):
  print("running", module)

# use the maximum number of threads by default
with Pool() as pool:
  pool.map(run, modules)