Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用参数(变量)执行shell脚本,但在shell脚本中不读取参数_Python_Shell_Subprocess_Popen - Fatal编程技术网

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

Python:使用参数(变量)执行shell脚本,但在shell脚本中不读取参数,python,shell,subprocess,popen,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和var

我正在尝试从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脚本的输入。我是否遗漏了什么,或者是否有其他方法可以做到这一点


参考:

您实际上正在发送参数。。。如果您的shell脚本编写了一个文件而不是打印,您将看到它。您需要进行通信以查看脚本的打印输出

from subprocess import Popen,PIPE

Process=Popen(['./childdir/execute.sh',str(var1),str(var2)],shell=True,stdin=PIPE,stderr=PIPE)
print Process.communicate() #now you should see your output

问题在于
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脚本内部的输出并以某种方式对其进行操作时,才应该这样做

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

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

请注意,
check\u output
check\u call
对于
shell=
参数的规则与
Popen

相同,如果您想以简单的方式从python脚本向shell脚本发送参数。。您可以使用python os模块:

import os  
os.system(' /path/shellscriptfile.sh {} {}' .format(str(var1), str(var2)) 
如果你有更多的理由。。增加花括号并添加参数。。
在shell脚本文件中。。这将读取参数,你可以相应地执行命令。

此外,如果他们只想看到输出,他们可以使用
子进程调用(['./childdir/execute.sh',str(var1),str(var2)],shell=True)
如果他们想看到输出。@Joran:我可以看到shell脚本输出,shell=True,我可以看到$0('./childdir/execute.sh')例如,正在执行的脚本,但不是参数var1、var2..可能会在shell脚本的顶部添加一个shebang。。。它可能没有在bash中运行,但是我保证您正在发送参数(可能参数不是您认为的参数)@SethMMorton:我尝试了这两个选项,但得到了错误(./execute.sh:premission denied)。虽然我给了execute prev.(chmod+x execute.sh)@Joran我也尝试过shebang…为了调试,我创建了两个小脚本来检查这一点,但是当我打印process.communicate()时,它会打印(无。[])@user2837135如果它解决了您的问题,您应该接受它(单击复选标记)在这种情况下不应该考虑“投票”>“代码> shell=true <代码>,但是如果您使用它,则应该避免<代码> VAR1,<代码> VAR2使用:<代码>输出= CHECKOULL输出(“./PaldiR/Exuuth.SH”+”“.No.Cube。
请注意,输出类型为
字节
,可能需要在使用前转换为
str
,例如:
output.decode(“utf-8”)