【问题标题】:Python: executing shell script with arguments(variable), but argument is not read in shell scriptPython:使用参数(变量)执行shell脚本,但在shell脚本中未读取参数
【发布时间】:2013-10-19 23:36:29
【问题描述】:

我正在尝试从 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

【问题讨论】:

    标签: python shell subprocess popen


    【解决方案1】:

    如果你想以简单的方式从 python 脚本向 shellscript 发送参数.. 你可以使用 python os 模块:

    import os  
    os.system(' /path/shellscriptfile.sh {} {}' .format(str(var1), str(var2)) 
    

    如果您有更多参数.. 增加花括号并添加参数.. 在 shellscript 文件中。这将读取参数,您可以相应地执行命令

    【讨论】:

      【解决方案2】:

      问题在于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,因此通常不需要向 Popen 提供 stdin=stderr= 参数(除非您使用输出重定向运行脚本,例如 >)。只有在需要读取 python 脚本中的输出并以某种方式对其进行操作时,才应该这样做。

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

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

      注意check_outputcheck_callshell= 参数的规则与Popen 相同。

      【讨论】:

      • @user2837135 如果它解决了你的问题,你应该接受它(点击复选标记),也许也考虑投票。
      • shell=True 应该在这种情况下使用,但如果你使用它,那么你应该使用shlex.quote() 转义var1var2output = check_output("./childdir/execute.sh " + " ".join(pipes.quote(str(v)) for v in [var1, var2]), shell=True)
      • 请注意,输出的类型是bytes,在使用之前可能需要转换为str,例如:output.decode("utf-8")
      【解决方案3】:

      您实际上是在发送参数......如果您的 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
      

      【讨论】:

      • 另外,如果他们只想查看输出,他们可以使用subprocess.call(['./childdir/execute.sh',str(var1),str(var2)],shell=True)
      • @Joran :我能够看到 shell=True 的 shell 脚本输出,我能够看到 $0('./childdir/execute.sh') 即正在执行的脚本,但是不是参数 var1, var2..
      • 可能在 shell 脚本的顶部添加一个 shebang ......它可能没有在 bash 中运行,但是我保证你正在发送参数(可能参数不是你认为的那样)
      • @SethMMorton :我尝试了这两个选项,但我得到了错误(./execute.sh:premission denied)。虽然我已经给出了execute prev.(chmod +x execute.sh)
      • @Joran 我也尝试使用 shebang...进行调试,我创建了 2 个小脚本来检查这一点,但是当我打印 process.communicate() 时,它会打印 (None.[])
      猜你喜欢
      • 2013-10-21
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多