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

2022-01-18 00:00:00 python shell subprocess popen

问题描述

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

main.py--------从子流程导入 Popen进程=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True)执行.sh----------echo $1//不打印任何东西echo $2//不打印任何东西

var1 和 var2 是我用作 shell 脚本输入的一些字符串.我错过了什么还是有其他方法可以做到这一点?

参考:如何使用子进程popen Python

解决方案

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

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

shell 只会将您在 Popen 的第一个参数中提供的参数传递给进程,就像它自己解释参数一样.查看此处回答的类似问题.实际发生了什么是你的 shell 脚本没有参数,所以 $1 和 $2 是空的.

Popen 将从 python 脚本继承 stdout 和 stderr,因此通常不需要向 Popen 提供 stdin=stderr= 参数(除非您运行脚本带有输出重定向,例如 >).只有在需要读取 python 脚本中的输出并以某种方式对其进行操作时,才应该这样做.

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

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])打印(输出)

请注意,check_outputcheck_call 对于 shell= 参数的规则与 Popen 相同.p>

I am trying to execute a shell script(not command) from python:

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 and var2 are some string that I am using as an input to shell script. Am I missing something or is there another way to do it?

Referred: How to use subprocess popen Python

解决方案

The problem is with shell=True. Either remove that argument, or pass all arguments as a string, as follows:

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

The shell will only pass the arguments you provide in the 1st argument of Popen to the process, as it does the interpretation of arguments itself. See a similar question answered here. What actually happens is your shell script gets no arguments, so $1 and $2 are empty.

Popen will inherit stdout and stderr from the python script, so usually there's no need to provide the stdin= and stderr= arguments to Popen (unless you run the script with output redirection, such as >). You should do this only if you need to read the output inside the python script, and manipulate it somehow.

If all you need is to get the output (and don't mind running synchronously), I'd recommend trying check_output, as it is easier to get output than Popen:

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

Notice that check_output and check_call have the same rules for the shell= argument as Popen.

相关文章