【问题标题】:Passing parameters to shell script from a python program从python程序将参数传递给shell脚本
【发布时间】:2015-02-18 06:02:33
【问题描述】:

我想从我的 python 脚本中调用一个 shell 脚本。我需要将 3 个参数/参数传递给 shell 脚本。我可以调用 shell 脚本(与 python 脚本在同一目录中),但是参数传递存在一些问题

from subprocess import call

// other code here.
line = "Hello"
// Here is how I call the shell command
call (["./myscript.sh", "/usr/share/file1.txt", ""/usr/share/file2.txt", line], shell=True)

In my shell script I have this
#!/bin/sh

echo "Parameters are $1 $2 $3"
...

Unfortunately parameters are not getting passed correctly.

I get this message:

Parameters are 

None of the parameter values are passed in the script

【问题讨论】:

  • 与推荐使用的shell=False 配合得很好——为什么你认为你需要shell=True 代替?!
  • 无论如何你都不想要shell=True 的列表参数。

标签: python shell subprocess


【解决方案1】:
call ("./myscript.sh /usr/share/file1.txt /usr/share/file2.txt "+line, shell=True)

当你使用shell=True时,你可以直接传递命令,就像直接传递shell一样。

【讨论】:

  • 是的,我试过这样做,除了最后一个参数外它工作正常。我在我的脚本中看到了这个: 参数是:/usr/share/file1.txt /usr/share/file2.txt 我想要的行:/usr/share/file1.txt /usr/share/file2.txt 你好
  • 是的,我这样做了:cmd = "./myscript.sh /usr/share/file1.txt /usr/share/file2.txt" + " " + line call([cmd],壳=真)。效果很好。
  • shell=True is unnecessary here。此外,如果line 包含诸如$`! 之类的shell 元字符,它可能会中断。
【解决方案2】:

删除shell=True(您可能需要使myscript.sh 可执行:$ chmod +x myscript.sh):

#!/usr/bin/env python
from subprocess import check_call

line = "Hello world!"
check_call(["./myscript.sh", "/usr/share/file1.txt", "/usr/share/file2.txt", 
            line])

Do not use a list argument and shell=True together.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2014-12-07
    • 2017-01-22
    • 2016-03-20
    相关资源
    最近更新 更多