问题:想要一个简单的argparse示例:1个参数,3个结果
该文档为argparse Python模块,而优秀的我敢肯定,是太多了我的小初学者的大脑现在掌握。我不需要在命令行上进行数学运算,也不需要在屏幕上设置格式行或更改选项字符。我要做的只是“如果arg是A,如果以上都不显示帮助并退出,则B这样做。”
The documentation for the argparse python module, while excellent I’m sure, is too much for my tiny beginner brain to grasp right now. I don’t need to do math on the command line or meddle with formatting lines on the screen or change option characters. All I want to do is “If arg is A, do this, if B do that, if none of the above show help and quit”.
回答 0
我对原始问题的理解是双重的。首先,就最简单的argparse示例而言,令我惊讶的是我在这里没有看到它。当然,简而言之,这几乎没有任何功能,而且开销很大,但这可能会让您入门。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()
if args.a == 'magic.name':
print 'You nailed it!'
但是,现在需要此位置参数。如果在调用该程序时将其遗漏,则会出现有关缺少参数的错误。这将我引到原始问题的第二部分。马特·威尔基(Matt Wilkie)似乎想要一个不带命名标签(–option标签)的可选参数。我的建议是修改上面的代码,如下所示:
...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
print 'You nailed it!'
else:
print args.a
可能会有一个更优雅的解决方案,但这是可行的并且是极简主义的。
My understanding of the original question is two-fold. First, in terms of the simplest possible argparse example, I’m surprised that I haven’t seen it here. Of course, to be dead-simple, it’s also all overhead with little power, but it might get you started.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()
if args.a == 'magic.name':
print 'You nailed it!'
But this positional argument is now required. If you leave it out when invoking this program, you’ll get an error about missing arguments. This leads me to the second part of the original question. Matt Wilkie seems to want a single optional argument without a named label (the –option labels). My suggestion would be to modify the code above as follows:
...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
print 'You nailed it!'
else:
print args.a
There may well be a more elegant solution, but this works and is minimalist.
回答 1
这是我的处理方式argparse
(带有多个args):
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args
将是包含参数的字典:
if args['foo'] == 'Hello':
# code here
if args['bar'] == 'World':
# code here
在您的情况下,只需添加一个参数即可。
Here’s the way I do it with argparse
(with multiple args):
parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())
args
will be a dictionary containing the arguments:
if args['foo'] == 'Hello':
# code here
if args['bar'] == 'World':
# code here
In your case simply add only one argument.
回答 2
该argparse
文档相当不错,但省略了一些可能并不明显的有用细节。(@Diego Navarro已经提到了其中一些内容,但是我将尝试对他的回答进行一些扩展。)基本用法如下:
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--my-foo', default='foobar')
parser.add_argument('-b', '--bar-value', default=3.14)
args = parser.parse_args()
您从中获得的对象parse_args()
是“命名空间”对象:该对象的成员变量以命令行参数命名。该Namespace
对象是您访问参数和与之关联的值的方式:
args = parser.parse_args()
print args.my_foo
print args.bar_value
(请注意,argparse
在命名变量时,请在参数名称中用下划线替换“-”。)
在许多情况下,您可能希望仅将参数用作没有值的标志。您可以像这样在argparse中添加它们:
parser.add_argument('--foo', action='store_true')
parser.add_argument('--no-foo', action='store_false')
上面的代码将分别创建名称为’foo’的True变量和’no_foo’的False变量:
if (args.foo):
print "foo is true"
if (args.no_foo is False):
print "nofoo is false"
还请注意,添加参数时可以使用“ required”选项:
parser.add_argument('-o', '--output', required=True)
这样,如果您在命令行中忽略此参数,argparse
则会告诉您它丢失了,并停止执行脚本。
最后,请注意,可以使用vars
函数创建参数的dict结构,如果这样会使您的生活更轻松。
args = parser.parse_args()
argsdict = vars(args)
print argsdict['my_foo']
print argsdict['bar_value']
如您所见,vars
返回一个dict,其参数名称为键,其值为er值。
您可以执行许多其他选择和操作,但这应该涵盖最基本,最常见的使用情况。
The argparse
documentation is reasonably good but leaves out a few useful details which might not be obvious. (@Diego Navarro already mentioned some of this but I’ll try to expand on his answer slightly.) Basic usage is as follows:
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--my-foo', default='foobar')
parser.add_argument('-b', '--bar-value', default=3.14)
args = parser.parse_args()
The object you get back from parse_args()
is a ‘Namespace’ object: An object whose member variables are named after your command-line arguments. The Namespace
object is how you access your arguments and the values associated with them:
args = parser.parse_args()
print args.my_foo
print args.bar_value
(Note that argparse
replaces ‘-‘ in your argument names with underscores when naming the variables.)
In many situations you may wish to use arguments simply as flags which take no value. You can add those in argparse like this:
parser.add_argument('--foo', action='store_true')
parser.add_argument('--no-foo', action='store_false')
The above will create variables named ‘foo’ with value True, and ‘no_foo’ with value False, respectively:
if (args.foo):
print "foo is true"
if (args.no_foo is False):
print "nofoo is false"
Note also that you can use the “required” option when adding an argument:
parser.add_argument('-o', '--output', required=True)
That way if you omit this argument at the command line argparse
will tell you it’s missing and stop execution of your script.
Finally, note that it’s possible to create a dict structure of your arguments using the vars
function, if that makes life easier for you.
args = parser.parse_args()
argsdict = vars(args)
print argsdict['my_foo']
print argsdict['bar_value']
As you can see, vars
returns a dict with your argument names as keys and their values as, er, values.
There are lots of other options and things you can do, but this should cover the most essential, common usage scenarios.
回答 3
Matt正在询问argparse中的位置参数,我同意在这方面缺少Python文档。在约20个奇数页中,没有一个完整的示例显示解析和使用位置参数。
这里的其他答案均未显示位置参数的完整示例,因此,这是一个完整的示例:
# tested with python 2.7.1
import argparse
parser = argparse.ArgumentParser(description="An argparse example")
parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')
args = parser.parse_args()
if args.action == "install":
print("You asked for installation")
else:
print("You asked for something other than installation")
# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)
# But this works:
print(getattr(args, 'foo-bar'))
让我失望的是argparse会将命名参数“ –foo-bar”转换为“ foo_bar”,但是名为“ foo-bar”的位置参数保持为“ foo-bar”,这使得如何处理在您的程序中使用它。
请注意,在我的示例结尾处的两行-这两行都无法获取foo-bar位置参数的值。第一个显然是错误的(这是一个算术表达式args.foo减去bar),但是第二个也不起作用:
AttributeError: 'Namespace' object has no attribute 'foo_bar'
如果要使用该foo-bar
属性,则必须使用getattr
,如我的示例的最后一行所示。疯狂的是,如果您试图dest=foo_bar
将属性名称更改为更易于访问的名称,则会收到一个非常奇怪的错误消息:
ValueError: dest supplied twice for positional argument
上面的示例运行方式如下:
$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments
$ python test.py -h
usage: test.py [-h] action foo-bar
An argparse example
positional arguments:
action The action to take (e.g. install, remove, etc.)
foo-bar Hyphens are cumbersome in positional arguments
optional arguments:
-h, --help show this help message and exit
$ python test.py install foo
You asked for installation
foo
Matt is asking about positional parameters in argparse, and I agree that the Python documentation is lacking on this aspect. There’s not a single, complete example in the ~20 odd pages that shows both parsing and using positional parameters.
None of the other answers here show a complete example of positional parameters, either, so here’s a complete example:
# tested with python 2.7.1
import argparse
parser = argparse.ArgumentParser(description="An argparse example")
parser.add_argument('action', help='The action to take (e.g. install, remove, etc.)')
parser.add_argument('foo-bar', help='Hyphens are cumbersome in positional arguments')
args = parser.parse_args()
if args.action == "install":
print("You asked for installation")
else:
print("You asked for something other than installation")
# The following do not work:
# print(args.foo-bar)
# print(args.foo_bar)
# But this works:
print(getattr(args, 'foo-bar'))
The thing that threw me off is that argparse will convert the named argument “–foo-bar” into “foo_bar”, but a positional parameter named “foo-bar” stays as “foo-bar”, making it less obvious how to use it in your program.
Notice the two lines near the end of my example — neither of those will work to get the value of the foo-bar positional param. The first one is obviously wrong (it’s an arithmetic expression args.foo minus bar), but the second one doesn’t work either:
AttributeError: 'Namespace' object has no attribute 'foo_bar'
If you want to use the foo-bar
attribute, you must use getattr
, as seen in the last line of my example. What’s crazy is that if you tried to use dest=foo_bar
to change the property name to something that’s easier to access, you’d get a really bizarre error message:
ValueError: dest supplied twice for positional argument
Here’s how the example above runs:
$ python test.py
usage: test.py [-h] action foo-bar
test.py: error: too few arguments
$ python test.py -h
usage: test.py [-h] action foo-bar
An argparse example
positional arguments:
action The action to take (e.g. install, remove, etc.)
foo-bar Hyphens are cumbersome in positional arguments
optional arguments:
-h, --help show this help message and exit
$ python test.py install foo
You asked for installation
foo
回答 4
另一个摘要的介绍,受本文启发。
import argparse
# define functions, classes, etc.
# executes when your script is called from the command-line
if __name__ == "__main__":
parser = argparse.ArgumentParser()
#
# define each option with: parser.add_argument
#
args = parser.parse_args() # automatically looks at sys.argv
#
# access results with: args.argumentName
#
参数是由以下组合定义的:
parser.add_argument( 'name', options... ) # positional argument
parser.add_argument( '-x', options... ) # single-char flag
parser.add_argument( '-x', '--long-name', options... ) # flag with long name
常见选项有:
- help:该参数的描述
--help
。
- 默认:如果省略arg的默认值。
- 输入:如果您期望a
float
或int
(否则为str
)。
- dest:为标志命名(例如
'-x', '--long-name', dest='longName'
)。
注意:默认情况下--long-name
使用args.long_name
- 动作:对某些参数的特殊处理
store_true, store_false
:用于布尔参数
'--foo', action='store_true' => args.foo == True
store_const
:与选项一起使用const
'--foo', action='store_const', const=42 => args.foo == 42
count
:用于重复的选项,例如./myscript.py -vv
'-v', action='count' => args.v == 2
append
:用于重复的选项,例如./myscript.py --foo 1 --foo 2
'--foo', action='append' => args.foo == ['1', '2']
- required:如果需要标志,或者不需要位置参数。
- nargs:用于捕获N args的标志
./myscript.py --foo a b => args.foo = ['a', 'b']
- 选择:限制可能的输入(指定为字符串列表,如果为,则指定为int
type=int
)。
Yet another summary introduction, inspired by this post.
import argparse
# define functions, classes, etc.
# executes when your script is called from the command-line
if __name__ == "__main__":
parser = argparse.ArgumentParser()
#
# define each option with: parser.add_argument
#
args = parser.parse_args() # automatically looks at sys.argv
#
# access results with: args.argumentName
#
Arguments are defined with combinations of the following:
parser.add_argument( 'name', options... ) # positional argument
parser.add_argument( '-x', options... ) # single-char flag
parser.add_argument( '-x', '--long-name', options... ) # flag with long name
Common options are:
- help: description for this arg when
--help
is used.
- default: default value if the arg is omitted.
- type: if you expect a
float
or int
(otherwise is str
).
- dest: give a different name to a flag (e.g.
'-x', '--long-name', dest='longName'
).
Note: by default --long-name
is accessed with args.long_name
- action: for special handling of certain arguments
store_true, store_false
: for boolean args
'--foo', action='store_true' => args.foo == True
store_const
: to be used with option const
'--foo', action='store_const', const=42 => args.foo == 42
count
: for repeated options, as in ./myscript.py -vv
'-v', action='count' => args.v == 2
append
: for repeated options, as in ./myscript.py --foo 1 --foo 2
'--foo', action='append' => args.foo == ['1', '2']
- required: if a flag is required, or a positional argument is not.
- nargs: for a flag to capture N args
./myscript.py --foo a b => args.foo = ['a', 'b']
- choices: to restrict possible inputs (specify as list of strings, or ints if
type=int
).
回答 5
注意Argparse教程在Python的HOWTO文档。它从最基本的示例开始,例如以下示例:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
并发展到基本程度较低的水平。
有一个带有预定义选项的示例,例如:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)
Note the Argparse Tutorial in Python HOWTOs. It starts from most basic examples, like this one:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)
and progresses to less basic ones.
There is an example with predefined choice for an option, like what is asked:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer)
回答 6
这主要是由于@DMH而使我在学习项目中想到的…
演示代码:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--flag', action='store_true', default=False) # can 'store_false' for no-xxx flags
parser.add_argument('-r', '--reqd', required=True)
parser.add_argument('-o', '--opt', default='fallback')
parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
parsed = parser.parse_args()
# NOTE: args with '-' have it replaced with '_'
print('Result:', vars(parsed))
print('parsed.reqd:', parsed.reqd)
if __name__ == "__main__":
main()
这可能已经发展并且可以在线获得:command-line.py
用于锻炼此代码的脚本:command-line-demo.sh
Here’s what I came up with in my learning project thanks mainly to @DMH…
Demo code:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--flag', action='store_true', default=False) # can 'store_false' for no-xxx flags
parser.add_argument('-r', '--reqd', required=True)
parser.add_argument('-o', '--opt', default='fallback')
parser.add_argument('arg', nargs='*') # use '+' for 1 or more args (instead of 0 or more)
parsed = parser.parse_args()
# NOTE: args with '-' have it replaced with '_'
print('Result:', vars(parsed))
print('parsed.reqd:', parsed.reqd)
if __name__ == "__main__":
main()
This may have evolved and is available online: command-line.py
Script to give this code a workout: command-line-demo.sh
回答 7
您也可以使用plac(argparse
)。
作为奖励,它会生成简洁的帮助说明-参见下文。
示例脚本:
#!/usr/bin/env python3
def main(
arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
):
"""General help for application"""
if arg == 'A':
print("Argument has value A")
elif arg == 'B':
print("Argument has value B")
if __name__ == '__main__':
import plac
plac.call(main)
输出示例:
没有提供参数- example.py
:
usage: example.py [-h] {A,B}
example.py: error: the following arguments are required: arg
提供了意外的参数- example.py C
:
usage: example.py [-h] {A,B}
example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')
提供的正确参数- example.py A
:
Argument has value A
完整的帮助菜单(自动生成)- example.py -h
:
usage: example.py [-h] {A,B}
General help for application
positional arguments:
{A,B} Argument with two possible values
optional arguments:
-h, --help show this help message and exit
简短说明:
参数名称通常等于参数名称(arg
)。
arg
参数之后的元组注释具有以下含义:
- 说明(
Argument with two possible values
)
- 参数类型-“标志”,“选项”或“位置”(
positional
)之一
- 缩写(
None
)
- 参数值的类型-例如 浮点数,字符串(
None
)
- 限制选择集(
['A', 'B']
)
说明文件:
要了解有关使用plac的更多信息,请查看其出色的文档:
Plac:轻松解析命令行
You could also use plac (a wrapper around argparse
).
As a bonus it generates neat help instructions – see below.
Example script:
#!/usr/bin/env python3
def main(
arg: ('Argument with two possible values', 'positional', None, None, ['A', 'B'])
):
"""General help for application"""
if arg == 'A':
print("Argument has value A")
elif arg == 'B':
print("Argument has value B")
if __name__ == '__main__':
import plac
plac.call(main)
Example output:
No arguments supplied – example.py
:
usage: example.py [-h] {A,B}
example.py: error: the following arguments are required: arg
Unexpected argument supplied – example.py C
:
usage: example.py [-h] {A,B}
example.py: error: argument arg: invalid choice: 'C' (choose from 'A', 'B')
Correct argument supplied – example.py A
:
Argument has value A
Full help menu (generated automatically) – example.py -h
:
usage: example.py [-h] {A,B}
General help for application
positional arguments:
{A,B} Argument with two possible values
optional arguments:
-h, --help show this help message and exit
Short explanation:
The name of the argument usually equals the parameter name (arg
).
The tuple annotation after arg
parameter has the following meaning:
- Description (
Argument with two possible values
)
- Type of argument – one of ‘flag’, ‘option’ or ‘positional’ (
positional
)
- Abbreviation (
None
)
- Type of argument value – eg. float, string (
None
)
- Restricted set of choices (
['A', 'B']
)
Documentation:
To learn more about using plac check out its great documentation:
Plac: Parsing the Command Line the Easy Way
回答 8
除了其他人所说的:
我通常喜欢使用’dest’参数指定变量名,然后使用’globals()。update()’将这些变量放入全局命名空间中。
用法:
$ python script.py -i "Hello, World!"
码:
...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"
To add to what others have stated:
I usually like to use the ‘dest’ parameter to specify a variable name and then use ‘globals().update()’ to put those variables in the global namespace.
Usage:
$ python script.py -i "Hello, World!"
Code:
...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"
回答 9
使用argparse并修改’-h’/’–help’开关以显示自己的个人代码帮助说明的一种非常简单的方法是将默认帮助设置为False,您还可以根据需要添加尽可能多的其他.add_arguments :
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
运行:python test.py -h
输出:
usage: test.py [-h]
optional arguments:
-h, --help To run this script please provide two arguments
A really simple way to use argparse and amend the ‘-h’/ ‘–help’ switches to display your own personal code help instructions is to set the default help to False, you can also add as many additional .add_arguments as you like:
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
Run: python test.py -h
Output:
usage: test.py [-h]
optional arguments:
-h, --help To run this script please provide two arguments
回答 10
最简单的答案!
PS写argparse文件的人是愚蠢的
python代码:
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set
运行代码
python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1
The simplest answer!
P.S. the one who wrote the document of argparse is foolish
python code:
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('--o_dct_fname',type=str)
parser.add_argument('--tp',type=str)
parser.add_argument('--new_res_set',type=int)
args = parser.parse_args()
o_dct_fname = args.o_dct_fname
tp = args.tp
new_res_set = args.new_res_set
running code
python produce_result.py --o_dct_fname o_dct --tp father_child --new_res_set 1