I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments.
我原来是一个C程序员。我看过无数的技巧和“技巧”来解读许多不同的论点。
What are some of the ways Python programmers can do this?
Python程序员有什么方法可以做到这一点?
Related
- What’s the best way to grab/parse command line arguments passed to a Python script?
- 获取/解析传递给Python脚本的命令行参数的最佳方式是什么?
- Implementing a “[command] [action] [parameter]” style command-line interfaces?
- 实现“[命令][操作][参数]”样式命令行接口?
- How can I process command line arguments in Python?
- 如何在Python中处理命令行参数?
- How do I format positional argument help using Python’s optparse?
- 如何使用Python的optparse来格式化位置参数?
17 个解决方案
#1
275
The canonical solution in the standard library is argparse
(docs):
标准库中的典型解决方案是argparse (docs):
Here is an example:
这是一个例子:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
argparse
supports (among other things):
argparse支持(除其他外):
- Multiple options in any order.
- 任意顺序的多个选项。
- Short and long options.
- 短期和长期的选择。
- Default values.
- 默认值。
- Generation of a usage help message.
- 生成一个使用帮助信息。
#2
419
import sys
print("\n".join(sys.argv))
sys.argv
is a list that contains all the arguments passed to the script on the command line.
sys。argv是一个包含在命令行上传递给脚本的所有参数的列表。
Basically,
基本上,
import sys
print(sys.argv[1:])
#3
122
Just going around evangelizing for argparse which is better for these reasons.. essentially:
只是四处传播argparse .出于这些原因,那更好。从本质上讲:
(copied from the link)
(复制链接)
-
argparse module can handle positional and optional arguments, while optparse can handle only optional arguments
argparse模块可以处理位置和可选参数,而optparse只能处理可选参数
-
argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality
argparse对于您的命令行接口应该是什么样子并不武断——支持-file或/file之类的选项,这是必需的选项。Optparse拒绝支持这些特性,宁愿使用纯度而不是实用性
-
argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.
argparse提供了更多的信息使用消息,包括从您的参数中确定的命令行用法,并帮助用于位置和可选参数的消息。optparse模块要求您编写自己的使用字符串,并且没有办法显示对位置参数的帮助。
-
argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance
argparse支持使用可变数量的命令行args的操作,而optparse需要预先知道确切的参数数目(例如,1、2或3)。
-
argparse supports parsers that dispatch to sub-commands, while optparse requires setting
allow_interspersed_args
and doing the parser dispatch manuallyargparse支持将解析器分派到子命令的解析器,而optparse需要设置allow_interspersed_args并手动执行解析器分派
And my personal favorite:
我个人最喜欢的:
- argparse allows the type and action parameters to
add_argument()
to be specified with simple callables, while optparse requires hacking class attributes likeSTORE_ACTIONS
orCHECK_METHODS
to get proper argument checking - argparse允许使用简单的可调用来指定add_argument()的类型和操作参数,而optparse则需要对诸如STORE_ACTIONS或CHECK_METHODS之类的类属性进行黑客操作,以获得正确的参数检查
#4
61
There is also argparse
stdlib module (an "impovement" on stdlib's optparse
module). Example from the introduction to argparse:
还有argparse stdlib模块(stdlib的optparse模块上的“改进”)。从介绍到argparse:
# script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'integers', metavar='int', type=int, choices=range(10),
nargs='+', help='an integer in the range 0..9')
parser.add_argument(
'--sum', dest='accumulate', action='store_const', const=sum,
default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Usage:
用法:
$ script.py 1 2 3 4
4
$ script.py --sum 1 2 3 4
10
#5
45
One way to do it is using sys.argv
. This will print the script name as the first argument and all the other parameters that you pass to it.
一种方法是使用sys.argv。这将打印脚本名称作为第一个参数和传递给它的所有其他参数。
import sys
for arg in sys.argv:
print arg
#6
37
The docopt library is really slick. It builds an argument dict from the usage string for your app.
docopt库非常灵活。它从应用程序的使用字符串构建一个参数命令。
Eg from the docopt readme:
从docopt自述中:
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
#7
22
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
#8
21
If you need something fast and not very flexible
如果你需要一些快速而不灵活的东西
main.py:
main.py:
import sys
first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)
Then run python main.py James Smith
然后运行python主要。py詹姆斯史密斯
to produce the following output:
产生以下输出:
Hello James Smith
你好詹姆斯史密斯
#9
17
I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:
我使用optparse我自己,但是真的很像Simon Willison最近引入的optfunc库所采用的方向。它的工作原理是:
"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."
“内省一个函数定义(包括它的参数和它们的默认值),并使用它构造一个命令行参数解析器。”
So, for example, this function definition:
例如,这个函数定义
def geocode(s, api_key='', geocoder='google', list_geocoders=False):
is turned into this optparse help text:
转换为这个optparse帮助文本:
Options:
-h, --help show this help message and exit
-l, --list-geocoders
-a API_KEY, --api-key=API_KEY
-g GEOCODER, --geocoder=GEOCODER
#10
7
I like getopt from stdlib, eg:
我喜欢stdlib中的getopt。
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).
最近我一直在用类似的东西来包装这件事,以使事情不那么罗嗦。“- h”隐式)。
#11
#12
6
Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.
Pocoo的点击更直观,需要更少的样板文件,并且至少和argparse一样强大。
The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.
到目前为止,我遇到的唯一缺点是您无法对帮助页面进行大量定制,但这通常不是一个需求,docopt似乎是一个明确的选择。
#13
4
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando
您可能对我编写的一个小Python模块感兴趣,它使处理命令行参数变得更容易(开放源码,可*使用)——Commando
#14
4
I recommend looking at docopt as a simple alternative to these others.
我建议将docopt看作是一种简单的替代方法。
docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.
docopt是一个新的项目,它通过解析“帮助使用”消息来工作,而不是要求您自己实现所有内容。你只需要把你的使用信息放在POSIX格式。
#15
3
Yet another option is argh. It builds on argparse, and lets you write things like:
另一个选择是argh。它建立在argparse基础上,让你可以编写如下内容:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
它将自动生成帮助等,您可以使用decorator提供关于arg解析应该如何工作的额外指导。
#16
0
My solution is entrypoint2. Example:
我的解决方案是entrypoint2。例子:
from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True):
''' This function writes report.
:param file: write report to FILE
:param quiet: don't print status messages to stdout
'''
print file,quiet
help text:
帮助文本:
usage: report.py [-h] [-q] [--debug] file
This function writes report.
positional arguments:
file write report to FILE
optional arguments:
-h, --help show this help message and exit
-q, --quiet don't print status messages to stdout
--debug set logging level to DEBUG
#17
0
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html
#1
275
The canonical solution in the standard library is argparse
(docs):
标准库中的典型解决方案是argparse (docs):
Here is an example:
这是一个例子:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
argparse
supports (among other things):
argparse支持(除其他外):
- Multiple options in any order.
- 任意顺序的多个选项。
- Short and long options.
- 短期和长期的选择。
- Default values.
- 默认值。
- Generation of a usage help message.
- 生成一个使用帮助信息。
#2
419
import sys
print("\n".join(sys.argv))
sys.argv
is a list that contains all the arguments passed to the script on the command line.
sys。argv是一个包含在命令行上传递给脚本的所有参数的列表。
Basically,
基本上,
import sys
print(sys.argv[1:])
#3
122
Just going around evangelizing for argparse which is better for these reasons.. essentially:
只是四处传播argparse .出于这些原因,那更好。从本质上讲:
(copied from the link)
(复制链接)
-
argparse module can handle positional and optional arguments, while optparse can handle only optional arguments
argparse模块可以处理位置和可选参数,而optparse只能处理可选参数
-
argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality
argparse对于您的命令行接口应该是什么样子并不武断——支持-file或/file之类的选项,这是必需的选项。Optparse拒绝支持这些特性,宁愿使用纯度而不是实用性
-
argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.
argparse提供了更多的信息使用消息,包括从您的参数中确定的命令行用法,并帮助用于位置和可选参数的消息。optparse模块要求您编写自己的使用字符串,并且没有办法显示对位置参数的帮助。
-
argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance
argparse支持使用可变数量的命令行args的操作,而optparse需要预先知道确切的参数数目(例如,1、2或3)。
-
argparse supports parsers that dispatch to sub-commands, while optparse requires setting
allow_interspersed_args
and doing the parser dispatch manuallyargparse支持将解析器分派到子命令的解析器,而optparse需要设置allow_interspersed_args并手动执行解析器分派
And my personal favorite:
我个人最喜欢的:
- argparse allows the type and action parameters to
add_argument()
to be specified with simple callables, while optparse requires hacking class attributes likeSTORE_ACTIONS
orCHECK_METHODS
to get proper argument checking - argparse允许使用简单的可调用来指定add_argument()的类型和操作参数,而optparse则需要对诸如STORE_ACTIONS或CHECK_METHODS之类的类属性进行黑客操作,以获得正确的参数检查
#4
61
There is also argparse
stdlib module (an "impovement" on stdlib's optparse
module). Example from the introduction to argparse:
还有argparse stdlib模块(stdlib的optparse模块上的“改进”)。从介绍到argparse:
# script.py
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'integers', metavar='int', type=int, choices=range(10),
nargs='+', help='an integer in the range 0..9')
parser.add_argument(
'--sum', dest='accumulate', action='store_const', const=sum,
default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Usage:
用法:
$ script.py 1 2 3 4
4
$ script.py --sum 1 2 3 4
10
#5
45
One way to do it is using sys.argv
. This will print the script name as the first argument and all the other parameters that you pass to it.
一种方法是使用sys.argv。这将打印脚本名称作为第一个参数和传递给它的所有其他参数。
import sys
for arg in sys.argv:
print arg
#6
37
The docopt library is really slick. It builds an argument dict from the usage string for your app.
docopt库非常灵活。它从应用程序的使用字符串构建一个参数命令。
Eg from the docopt readme:
从docopt自述中:
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
naval_fate.py (-h | --help)
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
#7
22
#set default args as -h , if no args:
if len(sys.argv) == 1: sys.argv[1:] = ["-h"]
#8
21
If you need something fast and not very flexible
如果你需要一些快速而不灵活的东西
main.py:
main.py:
import sys
first_name = sys.argv[1]
last_name = sys.argv[2]
print("Hello " + first_name + " " + last_name)
Then run python main.py James Smith
然后运行python主要。py詹姆斯史密斯
to produce the following output:
产生以下输出:
Hello James Smith
你好詹姆斯史密斯
#9
17
I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:
我使用optparse我自己,但是真的很像Simon Willison最近引入的optfunc库所采用的方向。它的工作原理是:
"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."
“内省一个函数定义(包括它的参数和它们的默认值),并使用它构造一个命令行参数解析器。”
So, for example, this function definition:
例如,这个函数定义
def geocode(s, api_key='', geocoder='google', list_geocoders=False):
is turned into this optparse help text:
转换为这个optparse帮助文本:
Options:
-h, --help show this help message and exit
-l, --list-geocoders
-a API_KEY, --api-key=API_KEY
-g GEOCODER, --geocoder=GEOCODER
#10
7
I like getopt from stdlib, eg:
我喜欢stdlib中的getopt。
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).
最近我一直在用类似的东西来包装这件事,以使事情不那么罗嗦。“- h”隐式)。
#11
7
As you can see optparse "The optparse module is deprecated with and will not be developed further; development will continue with the argparse module."
正如您所看到的optparse:“optparse模块已被弃用,不会进一步开发;开发将继续与argparse模块。
#12
6
Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.
Pocoo的点击更直观,需要更少的样板文件,并且至少和argparse一样强大。
The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.
到目前为止,我遇到的唯一缺点是您无法对帮助页面进行大量定制,但这通常不是一个需求,docopt似乎是一个明确的选择。
#13
4
You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando
您可能对我编写的一个小Python模块感兴趣,它使处理命令行参数变得更容易(开放源码,可*使用)——Commando
#14
4
I recommend looking at docopt as a simple alternative to these others.
我建议将docopt看作是一种简单的替代方法。
docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.
docopt是一个新的项目,它通过解析“帮助使用”消息来工作,而不是要求您自己实现所有内容。你只需要把你的使用信息放在POSIX格式。
#15
3
Yet another option is argh. It builds on argparse, and lets you write things like:
另一个选择是argh。它建立在argparse基础上,让你可以编写如下内容:
import argh
# declaring:
def echo(text):
"Returns given word as is."
return text
def greet(name, greeting='Hello'):
"Greets the user with given name. The greeting is customizable."
return greeting + ', ' + name
# assembling:
parser = argh.ArghParser()
parser.add_commands([echo, greet])
# dispatching:
if __name__ == '__main__':
parser.dispatch()
It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.
它将自动生成帮助等,您可以使用decorator提供关于arg解析应该如何工作的额外指导。
#16
0
My solution is entrypoint2. Example:
我的解决方案是entrypoint2。例子:
from entrypoint2 import entrypoint
@entrypoint
def add(file, quiet=True):
''' This function writes report.
:param file: write report to FILE
:param quiet: don't print status messages to stdout
'''
print file,quiet
help text:
帮助文本:
usage: report.py [-h] [-q] [--debug] file
This function writes report.
positional arguments:
file write report to FILE
optional arguments:
-h, --help show this help message and exit
-q, --quiet don't print status messages to stdout
--debug set logging level to DEBUG
#17
0
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called prog.py
$ python prog.py -h
Ref-link: https://docs.python.org/3.3/library/argparse.html