将shell脚本变量作为参数传递给Python脚本

时间:2016-03-16 14:17:32

标签: python shell unix

编写带有参数的shell脚本,

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程序。

请帮助解决这个问题。

2 个答案:

答案 0 :(得分:2)

如果要在shell中获取变量的值,请使用$ variable_name。 见下面的例子

root@s:/tmp# cat t.sh
#!/bin/sh
a="test"
b="test2"
c="test3"
python test.py $a $b $c

root@s:/tmp# cat test.py
#!/usr/bin/python
import sys
print  sys.argv[1:]


root@s:/tmp# ./t.sh
['test', 'test2', 'test3']

答案 1 :(得分:-3)

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

on bash

myvariable="something"
export myvariable

on python

import os
print os.environ["myvariable"]
相关问题