背景
为了便于记录每次执行代码时参数的设置,在shell脚本中调用python代码,并向其传递参数。
问题导入
shell代码
#!/bin/bash
name="xxx"
count=10
python -u click_demo.py --name ${name} --count=${count}
上面的shell脚本中,向python脚本click_demo.py
传递了两个参数,name
和count
。
python脚本中怎么接收这两个参数呢?
方式一 通过click传递
click模块基本使用方法参考https://blog.youkuaiyun.com/weixin_38278993/article/details/100052961
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
方式二 argparse
模块
import argparse
parser = argparse.ArgumentParser() ## 新建参数解释器对象
parser.add_argument('--count',type=int) ## 添加参数,注明参数类型
parser.add_argument('--name') ## 添加参数
args = parser.parse_args()### 参数赋值,也可以通过终端赋值
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
print('Hello %s!' % name)
if __name__ == '__main__':
hello(args.count,args.name) ## 带参数
注意上述两种方式中,hello函数调用是不同的,使用click
模块时,hello不带参数,而使用argparse
需要参数。
click
版本的 hello 函数有两个参数:count 和 name,它们的值从命令行中获取。