Python 带有子进程标志的多处理无法 运行

Python Multiprocessing with Subprocess Flags fail to run

当尝试 运行 以下代码时,我得到

OSError: [Errno 2] No such file or directory

奇怪的问题是,当我尝试 运行 LS 而没有任何其他标志(例如 -a)时,子进程 运行 没有错误。我也尝试添加 shell=True 和标志 -a,但仍然没有成功。

from multiprocessing import *
import subprocess


class ThreadManager:
    def __init__(self, tools):
        self.tools = tools
        self.pool_size = cpu_count()
        self.p1 = Pool(processes=self.pool_size, maxtasksperchild=2, )

    def initiate(self):
        for self.tool in self.tools:
            print self.tool
            self.p1 = Pool(4)
            self.p1 = Process(target=subprocess.call, args=(self.tool,))
            print self.p1

            self.p1.start()

th = ThreadManager("ls -a".split("/"))
th.initiate()

你的问题在这里:

"ls -a".split("/")

这将它变成一个列表 ["ls -a"],它强制 subprocess.call() 找到一个名为 "ls -a" 的二进制文件,它不存在。 subprocess.call() 有两种调用方式:

subprocess.call("ls -a", shell=True)   # argument parsing is done by shell
subprocess.call(["ls", "-a"])          # argument parsing not needed
subprocess.call("ls -a".split())       # argument parsing is done via .split()
subprocess.call(shlex.split("ls -a"))  # a more reliable approach to parse 
                                       # command line arguments in Python

请注意 subprocess.call() 的第一个参数是 位置参数 并作为 args 元组传递,而 shell=True关键字参数 并且应该作为字典参数传递 kwargs:

Process(target=subprocess.call, args=("ls -a",), kwargs=dict(shell=True))
Process(target=subprocess.call, args=(["ls", "-a"],))