【问题标题】:Python program can't find Shellscript FilePython程序找不到Shellscript文件
【发布时间】:2021-09-12 15:24:45
【问题描述】:

嘿,我正在尝试使用以下行使用 python 运行 shell 脚本:

import subprocess

shellscript = subprocess.Popen(["displaySoftware.sh"], stdin=subprocess.PIPE)

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()

但是当我运行程序时,它说它找不到 .sh 文件。

【问题讨论】:

  • 你能发布完整的回溯吗?
  • 尝试给它.sh文件的完整路径。也许您运行脚本的“当前路径”与脚本所在的路径不同。
  • @Teer2008,如果您的displaySoftware.sh 具有可执行权限并以有效的shebang 开头,您只需将["displaySoftware.sh"] 更改为["./displaySoftware.sh"],添加前导./,这就是您所需要的要做——没有shell=True,没有sh。而且它以这种方式更好工作,因为它尊重你的脚本的shebang来选择要使用的解释器。
  • @Teer2008, ...请注意,最好不要硬编码 ./ 来引用模块的 __file__ 属性来查找包含 Python 源代码的目录——这样如果您的脚本从与源目录不同的目录运行,您的脚本仍然可以工作(这是您接受的答案仍然存在的错误)。

标签: python linux shell


【解决方案1】:

您的命令缺少“sh”,您必须传递“shell=True”并且必须对“yes\n”进行编码。

您的示例代码应如下所示:

import subprocess

shellscript = subprocess.Popen(["sh displaySoftware.sh"], shell=True, stdin=subprocess.PIPE )

shellscript.stdin.write('yes\n'.encode("utf-8"))
shellscript.stdin.close()
returncode = shellscript.wait()

这种方法可能会更好:

import subprocess

shellscript = subprocess.Popen(["displaySoftware.sh"], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
returncode = shellscript.communicate(input='yes\n'.encode())[0]
print(returncode)

在我的机器上运行此脚本时,与 python 脚本位于同一目录中的“displaySoftware.sh”脚本已成功执行。

【讨论】:

  • 非常低效。当你这样做时,你告诉 Python 在它只需要一个时启动 两个 shell。
  • 也就是说:shell=True['sh', '-c'] 添加到给定的命令列表中,因此您正在运行sh -c 'sh displaySoftware.sh'。你永远不会在命令行上这样做,对吗?
  • 此外,sh displaySoftware.sh 本身就是不好的做法,因为它忽略了 displaySoftware.sh 选择使用的 shell 并强制使用 sh 执行它,即使它是为 bash 编写的,或 ksh,或 zsh,等等。
  • 我更新了我的答案。第二个选项是否解决了您指出 Charles Duffy 的问题?
猜你喜欢
  • 2017-02-28
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多