Python:使用参数(变量)执行shell脚本,但是在shell脚本中未读取参数 [英] Python: executing shell script with arguments(variable), but argument is not read in shell script

查看:526
本文介绍了Python:使用参数(变量)执行shell脚本,但是在shell脚本中未读取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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和var2是我用作shell脚本输入的一些字符串.我是否缺少某些东西,或者还有另一种方法吗?

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?

已引用:如何使用子流程popen Python

推荐答案

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

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)

shell只会将您在Popen的第一个参数中提供的参数传递给进程,因为它会对参数本身进行解释. 在这里看到类似的问题.实际发生的情况是您的shell脚本没有参数,因此$ 1和$ 2为空.

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

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.

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

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)

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

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

这篇关于Python:使用参数(变量)执行shell脚本,但是在shell脚本中未读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆