时间:2020-11-02来源:www.pcxitongcheng.com作者:电脑系统城
Python 在命令行解析方面给出了类似的几个选择:自己解析, 自给自足(batteries-included)的方式,以及大量的第三方方式。
自己解析
你可以从 sys 模块中获取程序的参数。
?| 1 2 3 4 5 |
import sys if __name__ == '__main__': for value in sys.argv: print(value) |
自给自足
在 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) |
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获取命令行参数实例方法讲解的文章就介绍到这了
2023-03-17
python flask项目打包成docker镜像发布的过程2023-03-17
python调试模块ipdb详解2023-03-17
python使用openai生成图像的超详细教程python cron定时任务触发接口自动化巡检 apscheduler报错:Run time of job …… next run at: ……)” was missed by misfire_grace_time参数 找到任务超时的根本原因...
2023-03-15