【问题标题】:Problem with open a .sh file with Python:not found使用 Python 打开 .sh 文件时出现问题:未找到
【发布时间】:2021-06-16 13:04:14
【问题描述】:

我必须用 PyQt5 开发的 python GUI 打开一个 .sh 文件。于是我实现了命令:

def function_openSH(self):
    subprocess.call('chmod u+x ./script_open.sh', shell=True)
    subprocess.call('./script_open.sh', shell=True)

它给了我:./script_open.sh: 5: source: not found。为什么?

【问题讨论】:

  • @TforV script_open.sh 里面有什么?这就是错误发生的地方。可以在命令行手动运行文件吗?
  • ./ 表示“此目录”。您启动的子流程可能对这意味着什么有不同的想法。
  • @BoarGules 不,请参阅我对 S3DEV 的评论回复。
  • 亲爱的,脚本有效,但它给出了同样的错误:非常奇怪
  • @KonradRudolph 是的,我可以,但这不是问题

标签: python shell


【解决方案1】:

带有shell=True 的子进程专门使用/bin/sh。如果这不是 bash 的符号链接,那么您可能正在使用符合 POSIX 的 shell(例如 ),那么 source 命令不可用:

$ cat > foo.sh
echo hello world

$ bash -c 'source ./foo.sh'
hello world

$ /bin/sh -c 'source ./foo.sh'
/bin/sh: 1: source: not found

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Aug  7  2020 /bin/sh -> dash

$ python
Python 2.7.16 (default, Oct 10 2019, 22:02:15) 
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call('source ./foo.sh', shell=True)
/bin/sh: 1: source: not found
127

由于您明确使脚本可执行,请使用shell=False


或者,使用 POSIX sh . 命令代替 bash 特定的 source

>>> subprocess.call('. ./foo.sh', shell=True)
hello world
0

【讨论】:

  • Cor。另一天,我认为是我学习的 POSIX 的一部分的另一个命令实际上是一个 bashism。
  • @glennjackman:我很确定 OP 确实使用纯 POSIX shell:他只是用 shell 标记了他的问题,并且从未提及不同的 shell(例如作为 ksh,...) 任何地方。
  • @user1934428 极不可能。如果 OP 有意 使用纯 POSIX shell,他们就会知道添加 shebang 行。此外,他们显然确实使用不同的 shell,因为他们的脚本使用 bashisms。
【解决方案2】:

我的猜测是您没有指定使用哪个 shell,例如#!/bin/bash 或者您没有定义 .sh 文件的显式路径。

【讨论】:

  • 是的,没错,但我记得 .sh 在未指定使用哪个 shell 时存在问题,是否使用了 /bin/sh。这个问题在 Ubuntu 中产生了大量损坏的脚本。
  • 确实如此,Python 的 execvp 调用与 POSIX API 的不同(参见 stackoverflow.com/q/62893701/1968)。但这在这里不相关:OP 的代码 works 与没有 shebang 行的脚本一起使用,如果它所做的只是在现有文件上调用 source
猜你喜欢
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 2020-03-10
  • 2014-08-01
相关资源
最近更新 更多