argparse 中的命名参数 [英] named argument in argparse
问题描述
我想按名称(类似于 kwargs)将参数发送到脚本.我试过这样的事情,但它没有做我想要的:(假设它是用 script.py 编写的)
I want to send arguments to script by their name (something like kwargs). I tried something like this but it's not doing what I want: (let's say it's written in script.py)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
然后在命令行中写入:script.py name = david
and then writing in commant line: script.py name = david
另一件事,假设我在 argparse 中几乎没有命名参数,如果我不按照它们声明的顺序发送它们,它还能正常工作吗?
another thing, let's say I have few named argument in argparse If I will send them not in the order they are declared will it still work well?
推荐答案
上述问题包含一些误解,或者我有一个很大的误解.
The question as stated contains a bit of a misunderstanding, or I have a big one.
*keyword 和 **keyword 用于将参数/内容传递给 python 代码中的类/函数/方法.
*keyword and **keyword are for passing parameters/stuff to classes/functions/methods INSIDE the python code.
argparse 用于从外部/命令行将参数/选项传递到 python 程序中.所以你不会得到它的 1 对 1 复制.然而 argparse 是相当可配置的,并且取决于你想如何去做,你可以接近.
argparse is used to pass arguments/options into the python program from outside/the commandline. So you're not going to get a 1 for 1 replication of it. However argparse is pretty configurable, and depending on how you want to do it you can come close.
如果你只想传递一个名字,那么:
If you only want to pass one name, then:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
print args
会让你:
$ ./pytest.py dave
Namespace(name='dave')
如果您想设置名称以便您也可以发送其他内容:
If you want to set name so you can send other stuff as well:
parser.add_argument("-name")
会让你:
./pytest.py -name dave
Namespace(name='dave')
但请注意:
./pytest.py -name dave -name steve
Namespace(name='steve')
然而:
parser.add_argument("--name")
将让/要求:
./pytest.py --name dave
Namespace(name='dave')
./pytest.py --name=dave
Namespace(name='dave')
如果你:
parser.add_argument("--name", nargs="+")
./pytest.py --name dave steve murphy
Namespace(name=['dave', 'steve', 'murphy'])
但是:
./pytest.py --name=dave --name=steve --name=murphy
Namespace(name= ['murphy'])
(注意最后一个是一个只有墨菲的列表.)
(note that that last one is a list with only murphy in it.)
所以你可以做的是:
parser.add_argument("--name")
parser.add_argument("--email")
parser.add_argument("--hair-color")
./pytest.py --name fred --hair-color murphy --email example@example.com
Namespace(email='example@example.com', hair_color='murphy', name='fred')
这篇关于argparse 中的命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!