简体   繁体   English

如何将参数从bash脚本传递给使用python的函数?

[英]How to pass arguments from a bash script to a function that uses python?

#!/bin/bash

#=================
function func1 {
#=================

echo "I have chickens"

func2 100

}
#================
function func2 {
#================

number=$1

python << END

print "I have", number, "chickens"

END
}

func1

In bash I want to pass func2 an argument. 在bash中,我想向func2传递一个参数。 In func2 I want to print the argument using python. 在func2中,我想使用python打印参数。

Desired output: 所需的输出:

I have chickens 我有鸡

I have 100 chickens 我有一百只鸡

Regular bash string variable substitution works: 常规bash字符串变量替换有效:

$ export n=3
$ python << END
> print "I have ${n} chickens"
> END

Output: 输出:

I have 3 chickens

Because of this, you have to be very careful if you wish to continue your (rather unusual) approach. 因此,如果您希望继续使用(相当不寻常的)方法,则必须非常小心。 A much more common way would be to have the Bash and Python programs in separate files and run the Python script from the Bash script with some command line arguments. 一种更常见的方法是将Bash和Python程序放在单独的文件中,并使用一些命令行参数从Bash脚本运行Python脚本。 You can then access them from Python as sys.argv , or, if you want to do anything more sophisticated, argparse . 然后,您可以以sys.argv从Python访问它们,或者,如果您想做更复杂的事情,可以使用argparse

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

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