【问题标题】:Passing variable to shell from python从python将变量传递给shell
【发布时间】:2018-01-18 14:57:48
【问题描述】:

我想将变量从 python 传递到 shell 脚本。我的代码如下所示。

Object_Id=12
Class_Name='My_Class'
Folder_Path='/My_Folder'

output=subprocess.check_output(['./execute.sh, 'Object_Id', 'Class_Name', "shell=True"])
print(output)

execute.sh 脚本只是简单的 echo 语句

echo $1
echo $2

输出是

 Object_Id 
 Class_Name

脚本将 args 作为文字字符串获取,但我想获取变量的值。

【问题讨论】:

  • 您能说明传递变量和获取参数之间的区别吗?如果你想传递变量 bash export 可能是你的电话。您可以随时编写如下代码:OBJECT_ID=$1; CLASS_NAME=$2

标签: python python-3.x shell subprocess


【解决方案1】:

您的check_output 调用需要将命令及其参数作为list 或str 与check_output API 本身的参数分开。你不应该传递变量的 names (你的命令根本不知道 Object_Id 的含义,并且即使它理解也无法返回到 Python 进程来识别),而是变量本身(并且您的报价不匹配,需要修复)。真的,你根本不需要shell=True,所以你可以这样做:

output = subprocess.check_output(['./execute.sh', str(Object_Id), Class_Name])

如果 shell=True 出于某种原因很重要,您可以通过传递代表 shell 命令的字符串来做到这一点:

import shlex
output = subprocess.check_output('./execute.sh {} {}'.format(shlex.quote(Object_Id), shlex.quote(Class_Name)),
                                 shell=True)

请注意,shell=True 是 check_output 的单独参数,不是命令本身的一部分(第一个位置参数)。

【讨论】:

  • 我是 python 新手,但第一个给我 exec 格式错误 ....我之前只尝试过这个...第二个告诉我 shlex 模块中缺少引号,我是使用 2.7 python
  • @SubrataFouzdar:当您使用 Python 2.7 时,为什么要标记问题 python-3.x?!?无论如何,您是否确保将Object_Id 包装在str() 中(非shell 变体必须通过str 的list)?对于第二个版本,如果您确定Object_Id 和Class_Name 包含其中没有空格或shell 元字符的字符串,您可以省略shlex.quote。或者只是切换到 Python 3;学习旧版本的语言是不必要地妨碍自己。仅在维护遗留代码时使用 Python 2。
  • output = subprocess.check_output('./execute.sh {} {}'.format((Object_Id), (Class_Name)),shell=True) --使用this,关于python的标记3.0 我的道歉
【解决方案2】:

它看起来像是将 args 作为字符串而不是变量,因为你用 '' 将它括起来,删除它们应该修复它

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 2013-03-28
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2015-01-08
    • 2017-03-06
    相关资源
    最近更新 更多