2016-03-16 120 views
0

我写的shell脚本采用参数,传递shell脚本变量的Python脚本参数

while getopts ":i:o:m" opt; do 
    case $opt in 
    i) a="$OPTARG" 
    ;; 
    o) b="$OPTARG" 
    ;; 
    m) c="$OPTARG" 
    ;; 
    \?) echo "Invalid option -$OPTARG" >&3 
    ;; 
    esac 
done 

然后我加入

python filename.py a b c 

变量而不是值,变量名被发送到Python程序。

请帮忙解决这个问题。

+0

使用' “$ A” 的''而不是A' –

+0

我瘦你刚才忘了加上'$'?使用:'python filename.py“$ a”“$ b”“$ c”'...在shell脚本中,您需要在变量之前使用'$'。我也为安全添加了引号,否则如果值有空格,事情就会中断;-) – Carpetsmoker

+1

并确保了解shell脚本 –

回答

1

如果你想获得变量的外壳使用$变量名的值。 参见下面的例子

[email protected]:/tmp# cat t.sh 
#!/bin/sh 
a="test" 
b="test2" 
c="test3" 
python test.py $a $b $c 

[email protected]:/tmp# cat test.py 
#!/usr/bin/python 
import sys 
print sys.argv[1:] 


[email protected]:/tmp# ./t.sh 
['test', 'test2', 'test3'] 
-2

您可以按名称访问环境变量,但需要导出它们。

巴蜀

myvariable="something" 
export myvariable 

在蟒蛇

import os 
print os.environ["myvariable"]