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

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

自己解析

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

1

2

3

4

5

import sys

if __name__== '__main__':

for valuein sys.argv:

print(value)

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

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

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

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获取命令行参数实例方法讲解的文章就介绍到这了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值