Python:使用参数(变量)执行 shell 脚本,但参数未在 shell 脚本中读取

标签 python shell subprocess popen

我正在尝试从 python 执行 shell 脚本(不是命令):

main.py
-------
from subprocess import Popen

Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True)

execute.sh
----------

echo $1 //does not print anything
echo $2 //does not print anything

var1 和 var2 是我用作 shell 脚本输入的一些字符串。我是否遗漏了什么或者是否有其他方法可以做到这一点?

引用:How to use subprocess popen Python

最佳答案

问题出在shell=True .要么删除该参数,要么将所有参数作为字符串传递,如下所示:

Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)

shell 只会传递您在 Popen 的第一个参数中提供的参数过程,就像它对论点本身的解释一样。 查看类似问题的回答here.实际发生的是您的 shell 脚本没有参数,因此 $1 和 $2 为空。

Popen 将从 python 脚本继承 stdout 和 stderr,所以通常不需要提供 stdin=stderr= Popen 的参数(除非您使用输出重定向运行脚本,例如 > )。仅当您需要读取 python 脚本中的输出并以某种方式对其进行操作时才应执行此操作。

如果您只需要获取输出(并且不介意同步运行),我建议您尝试 check_output ,因为它比 Popen 更容易获得输出:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)

注意 check_outputcheck_callshell= 有相同的规则参数为 Popen .

关于Python:使用参数(变量)执行 shell 脚本,但参数未在 shell 脚本中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19325761/

相关文章:

python - 是否可以在 sklearn.ensemble 中使用不同的分类器?

bash - 通过 bash 读取文件夹中的任何 .txt 文件

Python STDOUT 使用 openssl 子进程归档

linux - python 将 os.environ 传递给子 gnome 终端

python - 子进程模块、envoy、sarge 和 pexpect 之间的区别?

python - 动态创建的方法和装饰器,得到错误 'functools.partial' 对象没有属性 '__module__'

python - 告诉命令行运行 Python 3

c - 如何从 shell 执行库调用命令?

linux - Bash linux 强制多个实例等待运行 sqlplus 命令完成

python - Pandas 唯一值多列