
python获取命令行参数实现方法:自己解析, 自给自足(batteries-included)的方式,以及大量的第三方方式。
1.自己解析
你可以从 sys 模块中获取程序的参数。
1 2 3 4 5 | import sys
if __name__ == '__main__' :
for value in sys.argv:
print(value)
|
2.自给自足
在 Python 标准库中已经有几个参数解析模块的实现: getopt 、 optparse ,以及最近的 argparse 。argparse 允许程序员为用户提供一致的、有帮助的用户体验,但就像它的 GNU 前辈一样,它需要程序员做大量的工作和“ 模板代码 ”才能使它“奏效”。
1 2 3 4 5 6 7 8 9 10 | from argparse import ArgumentParser
if __name__ == "__main__" :
argparser = ArgumentParser(description= 'My Cool Program' )
argparser.add_argument( "--foo" , "-f" , help= "A user supplied foo" )
argparser.add_argument( "--bar" , "-b" , help= "A user supplied bar" )
results = argparser.parse_args()
print(results.foo, results.bar)
|
3.CLI 的现代方法
Click 框架使用 装饰器 的方式来构建命令行解析。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import click
@click.command()
@click.option( "-f" , "--foo" , default = "foo" , help= "User supplied foo." )
@click.option( "-b" , "--bar" , default = "bar" , help= "User supplied bar." )
def echo(foo, bar):
"" "My Cool Program
It does stuff. Here is the documentation for it.
" ""
print(foo, bar)
if __name__ == "__main__" :
echo()
|
在 Click 接口中添加参数就像在堆栈中添加另一个装饰符并将新的参数添加到函数定义中一样简单。
知识拓展:
Typer 建立在 Click 之上,是一个更新的 CLI 框架,它结合了 Click 的功能和现代 Python 类型提示 。使用 Click 的缺点之一是必须在函数中添加一堆装饰符。CLI 参数必须在两个地方指定:装饰符和函数参数列表。Typer 免去你造轮子 去写 CLI 规范,让代码更容易阅读和维护。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import typer
cli = typer.Typer()
@cli.command()
def echo(foo: str = "foo" , bar: str = "bar" ):
"" "My Cool Program
It does stuff. Here is the documentation for it.
" ""
print(foo, bar)
if __name__ == "__main__" :
cli()
|
大家可以根据自己的用例,选择上面方法使用,如需了解更多python实用知识,点击进入PyThon学习网教学中心。
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)