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屋!