python-2.7 - python 子进程 popen 返回 None

标签 python-2.7 subprocess popen nonetype

我有一个像这样的Python代码片段:

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

引发异常,提示“NoneType”对象没有 wait() 方法。我猜这意味着 Popen 调用返回 None ?这可能是什么原因。文档没有提到这种可能性

我使用的是 python 2.7.13

最佳答案

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

我注意到的第一件事是语法不正确,因为您没有将命令行括在方括号 [] 中。而且你没有 split 争论。

此外,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. 

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

关于python-2.7 - python 子进程 popen 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43078974/

相关文章:

python - 如何在python中对文件中的内容进行排序

python - 检测音频信号中的数字削波

python - 如何避免 "WindowsError: [Error 5] Access is denied"

java - Maven 命令 mvn 从终端运行没有错误,但从 python 没有错误

c - 在多线程程序中为 system() 向下传递信息

python - Python 2 中的格式化字符串文字

python子进程popen将主目录设置为cwd

python - 当我在 Bash 中有一系列命令时,如何重定向标准输入/标准输出?

c - 使用 fclose 到 popen 的管道是一个严重的错误?

Python unicode popen 或 Popen 错误读取 unicode