首页 > 解决方案 > 使用 Python 打开 .sh 文件时出现问题:未找到

问题描述

我必须用 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。为什么?

标签: pythonshell

解决方案


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

推荐阅读