当前位置: 首页 > 新闻动态 > 软件编程

python获取命令行参数实例方法讲解

作者:用户投稿 浏览: 发布日期:2026-01-11
[导读]:在本篇文章里小编给大家整理的是一篇关于python获取命令行参数实例方法讲解内容,有兴趣的朋友们可以学习下。

Python 在命令行解析方面给出了类似的几个选择:自己解析, 自给自足(batteries-included)的方式,以及大量的第三方方式

自己解析

你可以从 sys 模块中获取程序的参数。

import sys
 
if __name__ == '__main__':
   for value in sys.argv:
       print(value)

自给自足

在 Python 标准库中已经有几个参数解析模块的实现: getopt 、 optparse ,以及最近的 argparse 。argparse 允许程序员为用户提供一致的、有帮助的用户体验,但就像它的 GNU 前辈一样,它需要程序员做大量的工作和“ 模板代码 ”才能使它“奏效”。

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 框架使用 装饰器 的方式来构建命令行解析。

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 规范,让代码更容易阅读和维护。

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()

 

免责声明:转载请注明出处:http://www.sczxchw.cn/news/567292.html

扫一扫高效沟通

多一份参考总有益处

免费领取网站策划SEO优化策划方案

请填写下方表单,我们会尽快与您联系
感谢您的咨询,我们会尽快给您回复!