读取命名命令参数 [英] Reading named command arguments

查看:21
本文介绍了读取命名命令参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 argparse 读取不需要按特定顺序排列的命名命令行参数吗?我浏览了文档,但其中大部分内容都集中在根据参数显示内容提供(如--h).

Can I use argparse to read named command line arguments that do not need to be in a specific order? I browsed through the documentation but most of it focused on displaying content based on the arguments provided (such as --h).

现在,我的脚本读取有序的、未命名的参数:

Right now, my script reads ordered, unnamed arguments:

myscript.py foo-val bar-val

myscript.py foo-val bar-val

使用sys.argv:

foo = sys.argv[1]
bar = sys.argv[2]

但我想更改输入,以便通过命名参数使其与顺序无关:

But I would like to change the input so that it is order agnostic by naming arguments:

myscript.py --bar=bar-val --foo=foo-val

myscript.py --bar=bar-val --foo=foo-val

推荐答案

您可以使用 可选参数 像这样:

You can use the Optional Arguments like so:

import argparse, sys

parser=argparse.ArgumentParser()

parser.add_argument('--bar', help='Do the bar option')
parser.add_argument('--foo', help='Foo the program')

args=parser.parse_args()

print args
print sys

然后如果你用 ./prog --bar=bar-val --foo foo-val 调用它,它会打印:

Then if you call it with ./prog --bar=bar-val --foo foo-val it prints:

Namespace(bar='bar-val', foo='foo-val')
['Untitled 14.py', '--bar=bar-val', '--foo', 'foo-val']

或者,如果用户需要帮助 argparse 也构建:

Or, if the user wants help argparse builds that too:

 $ ./prog -h
usage: Untitled 14.py [-h] [--bar BAR] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --bar BAR   Do the bar option
  --foo FOO   Foo the program

这篇关于读取命名命令参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆