简体   繁体   English

将变量从一个 shell 传递到另一个 shell 以执行 python 脚本

[英]Pass variables form one shell to another shell to execute a python script

I have a python script that takes an argument and return a multiplication.我有一个 python 脚本,它接受一个参数并返回一个乘法。 I have this shell script pythoncall.sh: python /user/mult.py var1我有这个 shell 脚本 pythoncall.sh: python /user/mult.py var1

I want to run this for different argument values in a loop: second.sh我想在循环中为不同的参数值运行它:second.sh

for i in 1 2 3
  do 
  var1=$i
  ./pythoncall.sh
done

but i don't get the result because i don't pass the variable i think.但我没有得到结果,因为我没有传递我认为的变量。 my error is IndexError: list index out of range.我的错误是 IndexError: list index out of range。

the python script:蟒蛇脚本:

import sys
def main(argv):

    num1=sys.argv[1]
    len1=int(num1)*3
    print(len1)

if __name__ == '__main__':
    main(sys.argv)

So, the direct answer is you need to export the variable for the second shell script to be able to see it:因此,直接的答案是您需要导出第二个 shell 脚本的变量才能看到它:

export var1=$i

but why do you need the variable and second shell script at all?但是为什么你需要变量和第二个 shell 脚本呢? Why not just call the python script directly:为什么不直接调用python脚本:

for i in 1 2 3
do
  python /user/mult.py $i
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM