Python: 子进程 "call" 函数找不到路径

Python: Subprocess "call" function can't find path

我有一个 python 程序需要在服务器上 运行 一个 bash 命令。当我在我的本地目录中 运行 一个 bash 命令时该程序工作,如下所示:

import subprocess from subprocess import call call(['bash', 'Script_Test.sh'])

但是,在通过 SSH 连接到服务器并 运行 在下面的类似代码行中使用服务器上指向 bash 脚本的路径后,我得到了错误 "No such file or directory"

call['bash', path]

出于多种原因,这没有意义。我三次检查路径是否正确。我继续使用 Putty,连接到那里的服务器,运行 一个具有相同路径的 bash 命令并且它有效,所以它不可能是路径。我还 运行 进行了一些测试,以确保我通过 SSH 进入了正确的服务器,我确实做到了。我认为我 运行ning bash 的服务器存在安全问题,所以我改用 cat。不行,还是找不到路径

我对 python 子流程不是很熟悉,所以任何指向我在 "call" 中遗漏的任何内容的指针都会非常有帮助。

确保您的脚本已准备好执行

  1. 给你的脚本一个 shebang 行

首先,您使用的是important that you include a shebang line in your script on Unix-like systems. I recommend, for your script's portability#!/usr/bin/env bash

关于文件扩展名的注意事项:

我建议您 remove the .sh extension from your script. If you are using the Bourne Again Shell (bash) to execute your script, then using the .sh extension is misleading. Simply put, the Bourne Shell (sh) is different than the Bourne Again Shell (bash) - 所以不要使用暗示您使用的 shell 与实际不同的文件扩展名!

It's not the end of the world if you don't do change your file extension - 如果您有正确的 bash shebang 行,您的脚本仍将作为 bash 脚本执行。不过,最好还是使用无文件扩展名Script_Test——强烈推荐)或.bash文件扩展名[=78] =](Script_Test.bash)。

  1. 为您的脚本提供适当的文件权限

出于您的目的,也许重要的是授予当前用户读取和执行脚本的权限。在这种情况下,使用 chmod u+x Script_Test.sh。这里重要的是正确的用户 (u+) / 组 (g+) 具有执行脚本的权限。

  1. 确保您的 script's path is in the $PATH environment variable

在 Python 脚本中执行您的 bash 脚本

完成这些步骤后,您的 Python 脚本应该会像您在问题中调用的那样工作:

import subprocess
from subprocess import call

your_call = call("Test_Script.sh")

如果您不想将脚本移动到 $PATH 环境变量中,只需确保引用脚本的完整路径(在您的情况下为当前目录 ./ ):

import subprocess
from subprocess import call

your_call = call("./Test_Script.sh")

最后,如果您的脚本没有 shebang 行,您将需要在 call 函数中指定一个附加参数:

import subprocess
from subprocess import call

your_call = call("./Test_Script.sh", shell=True)

但是,我不推荐最后一种方法。请参阅 Python 2.7.12 documentation for the subprocess package...

Warning: Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.

如果您仍有问题,请检查@zenpoy's explanation to a similar Whosebug question

编码愉快!