python 子进程 popen returns None

python subprocess popen returns None

我有这样的 python 片段:

self.task = subprocess.Popen("bash ./FOLDER/script.sh", cwd=some_dir, shell=True)
self.task.wait()

引发异常,抱怨 'NoneType' 对象没有方法 wait()。我想这意味着 Popen 调用 returns None ?这可能是什么原因。文档没有提到这种可能性

我正在使用 python 2.7.13

好吧,显然 self.task 给出了 NoneType 响应,这意味着 subprocess.Popen() 命令可能有问题。

我注意到的第一件事是语法不正确,因为您没有将命令行括在方括号中 [] 并且您没有拆分参数。

此外,Python 文档状态(关于您使用的 cwd 选项):

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

所以首先要检查的是您的 script.sh 是否位于 some_dir/FOLDER/script.sh

如果情况确实如此,请检查您是否使用正确的语法插入了 cwd 参数,例如作为字符串.. 意思是 cwd="/path/to/some/dir"

然后,由于 Python 文档明确指出:

Using shell=True can be a security hazard

我会删除那个论点。这可能意味着您必须使用 bash 的完整路径。要找出正确的路径,请打开终端并执行 which bash。或者,可以肯定的是,type bash.

那么,试试这个:

import subprocess

self.task = subprocess.Popen(["/path/to/your/bash", "./FOLDER/script.sh"], cwd="/path/to/some_dir", stdout=subprocess.PIPE, stderr=subprocess.PIPE) # This makes sure you will also catch any standard errors, so it allows for a bit more control. 
output, errors = self.task.communicate() # This already encapsulates .wait()
print(output.decode()) # if you'd like to check the output. 

阅读代码中的注释以获得进一步的解释..