• 技术文章 >Python技术 >Python基础教程

    详解python获取命令行参数实现方法

    2021-04-06 16:16:33原创2958

    python获取命令行参数实现方法:自己解析, 自给自足(batteries-included)的方式,以及大量的第三方方式

    1.自己解析

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

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

    2.自给自足

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

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

    大家可以根据自己的用例,选择上面方法使用,如需了解更多python实用知识,点击进入PyThon学习网教学中心

    (推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)

    专题推荐:python 命令行参数
    品易云
    上一篇:python实例:Python中如何删除numpy数组的元素 下一篇:python的列表extend函数是什么?怎么用?

    相关文章推荐

    • Python集成ActiveMQ怎么用?如何连接?• Python replace()函数:替换字符串中的某个字符• 基础学习:python遍历循环方法有哪些?怎么用?• 基础学习:python中map函数是什么?怎么用?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网