使用shell脚本执行python脚本-在sh中确定的变量

时间:2018-07-15 17:54:04

标签: python bash

我已经在shell脚本中确定了变量,现在我想实现这些变量以执行python脚本  (python脚本需要在shell脚本中确定变量)。

--------------------------- shell_script.sh ----------------- ---------

#变量a和b是执行my_pythonscript.py所必需的

a = hvariable_1

b = variable_2

python my_pythonscript.py a b


非常感谢您的帮助和建议

2 个答案:

答案 0 :(得分:1)

您可以将它们作为参数变量传递给脚本:

您的shell脚本:

#!/bin/bash

VARIABLE1='Hello'
VARIABLE2='World'

python example.py $VARIABLE1 $VARIABLE2

您的Python脚本:

import sys

if len(sys.argv) == 3:
    print(sys.argv[1] + ' ' + sys.argv[2] + '!')

通过shell脚本运行时会打印python脚本:

Hello World!

答案 1 :(得分:0)

shell_script.sh

A='your variable'
B='another variable'
python my_pythonscript.py "$A" "$B"

my_pythonscript.py

import sys
a = sys.argv[1]
b = sys.argv[2]

请注意: sys.argv[0]是脚本名称,在您的情况下为my_pythonscript.py

如果您打算使用python 3.6,请使用python3 my_pythonscript.py a b