如何在Python中读取/处理命令行参数?

The official way of reading or processing the command line arguments is by using the argparse from ArgumentParser module.

读取或处理命令行参数的官方方法是使用ArgumentParser模块中的argparse 。

The argparse module enables is implementing the user-friendly command-line interfaces. The program defines the arguments it requires, and argparse will ascertain how to parse those out of the sys.argv? The argparse also generates the help and usage messages and issues errors when the users give the program invalid arguments.

argparse模块启用了实现用户友好的命令行界面。 该程序定义了所需的参数,而argparse将确定如何从sys.argv中解析这些参数? 当用户为程序提供无效参数时, argparse还会生成帮助和用法消息并发出错误。

Example:

例:

import argparse

parser = argparse.ArgumentParser(description='Process the numbers')
parser.add_argument('integers',metavar='N', type=int, nargs='+', help='an integer for addition')
parser.add_argument('--sum',dest='addition', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.addition(args.integers))

Assuming, we have saved the above method in a file as 'argparse_example.py', it can be run at the command line and provide helpful messages.

假设,我们已将上述方法保存为文件“ argparse_example.py”,可以在命令行中运行并提供有用的消息。

Case 1: running the method without passing the arguments

情况1:在不传递参数的情况下运行方法

    python argparse_example.py 
    usage: argparse_example.py [-h] [--sum] N [N ...]
    argparse_example.py: error: the following arguments are required: N

Case 2: Running the method passing the -h as argument

情况2:运行通过-h作为参数的方法

    python argparse_example.py -h
    usage: argparse_example.py [-h] [--sum] N [N ...]

    Process the numbers

    positional arguments:
      N           an integer for addition

    optional arguments:
      -h, --help  show this help message and exit
      --sum       sum the integers (default: find the max)

Case 3: Running the method passing the numbers (returns max of list of numbers)

情况3:运行传递数字的方法(返回数字列表的最大值)

    python argparse_example.py 1 2 3 4
    4

Case 4: Running the method passing the –sum argument as an argument, along with list of numbers

情况4:运行传递–sum参数作为参数以及数字列表的方法

    python argparse_example.py 1 2 3 4 --sum
    10


翻译自: https://www.includehelp.com/python/how-to-read-process-command-line-arguments-in-python.aspx

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值