【问题标题】:Python: Subprocess "call" function can't find pathPython:子进程“调用”函数找不到路径
【发布时间】:2016-11-08 22:16:45
【问题描述】:

我有一个需要在服务器上运行 bash 命令的 python 程序。当我像这样在本地目录中运行 bash 命令时,该程序可以工作:

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

但是,在通过 SSH 连接到服务器并运行下面类似的代码行并在服务器上使用 bash 脚本的路径后,我收到错误“没有这样的文件或目录”

call['bash', path]

由于多种原因,这没有意义。我三次检查路径是否正确。我继续使用 Putty,连接到那里的服务器,并使用相同的路径运行 bash 命令并且它有效,所以它不能是路径。我还进行了许多测试,以确保我通过 SSH 连接到正确的服务器,并且确实如此。我认为在我运行 bash 时服务器上存在安全问题,所以我尝试使用 cat 代替。不行,还是找不到路径。

我对 python 子进程不是很熟悉,所以任何指向我在这里缺少的“调用”的指针都会非常有帮助。

【问题讨论】:

  • 将行 import os.path; print (os.path.isfile(path)) 添加到您的 python 代码中。如果您的程序返回 False,则表示文件:path 不存在。因此,您需要将 bash 脚本文件重新定位到其正确位置。此外,使用which bashwhich python 测试您的服务器上是否安装了bash 和python。
  • 您可能会从运行 Script_Test.sh 的子进程中收到错误“没有这样的文件或目录”。这可能与您的子进程的路径可能与您的 script_test.sh 所在的位置不同有关。您可以使用 pwd 从内部打印来检查子进程的路径。

标签: python bash shell ssh subprocess


【解决方案1】:

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

  1. 给你的脚本一个 shebang 行

首先,在类 Unix 系统上的脚本中是 important that you include a shebang line。我建议您使用for your script's portability,使用#!/usr/bin/env bash

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

我会推荐你​​remove the .sh extension from your script。如果您使用 Bourne Again Shell (bash) 执行脚本,那么使用 .sh 扩展名会产生误导。简而言之,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文件扩展名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...

警告:使用shell=True 可能存在安全隐患。有关详细信息,请参阅Frequently Used Arguments 下的警告。

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

编码愉快!

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 2021-04-08
    • 2011-10-09
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2019-04-13
    • 2019-05-22
    相关资源
    最近更新 更多