背景
为了便于记录每次执行代码时参数的设置,在shell脚本中调用python代码,并向其传递参数。
问题导入
shell代码
复制代码
1
2
3
4
5#!/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.csdn.net/weixin_38278993/article/details/100052961
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14import 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
模块
python中argparse使用介绍参考https://blog.csdn.net/Blankit1/article/details/122510221?spm=1001.2014.3001.5501
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13import 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,它们的值从命令行中获取。
方式三 sys
模块
参考http://t.zoukankan.com/sixbeauty-p-4285565.html
最后
以上就是寂寞大船最近收集整理的关于shell向python传递参数的全部内容,更多相关shell向python传递参数内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复