通俗来说,命令行与参数解析就是当你输入cmd 打开dos 交互界面时候,启动程序要进行的参数给定。比如在dos 界面输入:
python openPythonFile.py "a" -b "number"
其中的"a", -b 等就是命令行与参数解析要做的事。
~~这在windows 系统下用处不是特别大,因为windows 下各种编译器,你根本不需要在dos 界面下去执行python 脚本。但是在linux 系统下,你几乎要总是考虑命令行解析。~~
和操作系统无关,就是设计程序在运行时必须给定某些额外参数才能运行,也就是如果设置了命令行参数解析,那么各种编译器按F5 是无法直接运行程序的。用途,就是不能随便就能运行脚本,可以达到一定程度上的安全功能。
下面通过一个例子进行简单创建:
-
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')
-
# 解析参数步骤
-
args = parser.parse_args()
-
print(args.accumulate(args.integers))
在dos 界面执行:
python 命令行与参数解析.py -h
运行结果:
-
usage:
命令行与参数解析.py [-h] [--sum] N [N ...]
-
Process
some integers.
-
positional
arguments:
-
N
an integer for the accumulator
-
optional
arguments:
-
-h,
--help show this help message and exit
-
--sum
sum the integers
-
ArgumentParser(prog=
'', usage=None, description=
'Process some integers.', version=None, formatter_class=<
class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
-
# 例如
-
parser = argparse.ArgumentParser(description=
'Process some integers.')
-
# 变更参数
-
parser = argparse.ArgumentParser(prog=
'sum or max',description=
'Process some integers.')
-
-
#运行结果
-
#原始
-
usage: 命令行与参数解析.py [-h] [--sum] N [N
...]
-
#变更后
-
usage: sum or max [-h] [--sum] N [N
...]
python xxx.py -h
之后将出现。看例子:
-
# 变更参数
-
parser =
argparse.ArgumentParser(usage='python 命令行与参数解析.py arguments',description='Process some integers.')
-
-
#运行结果
-
#原始
-
usage:
命令行与参数解析.py [-h] [--sum] N [N ...]
-
#变更后
-
usage:
python 命令行与参数解析.py arguments
-
# 变更参数
-
epilog=
'And What can I help U?'
-
# 运行结果
-
optional arguments:
-
-h, --
help show this
help message and
exit
-
--sum sum the intergers
-
And What can I
help U?
-
>>>
with open('args.txt', 'w') as fp:
-
...
fp.write('-f\nbar')
-
>>>
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
-
>>>
parser.add_argument('-f')
-
>>>
parser.parse_args(['-f', 'tmp', '@args.txt'])
-
Namespace(f='bar')
例子中parser.parse_args(['-f', 'foo', '@args.txt'])解析时会从文件args.txt 读取,相当于 ['-f', 'foo', '-f', 'bar']
-
>>> parser = argparse.ArgumentParser(prog=
'PROG')
-
>>> parser.add_argument(
'-f',
'--foo', help=
'old foo help')
-
>>> parser.add_argument(
'--foo', help=
'new foo help')
-
Traceback (most recent call last):
-
..
-
ArgumentError: argument --
foo: conflicting option string(s): --foo
-
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][,
help][, metavar][, dest])
-
-
# 例如
-
parser.add_argument(
'intergers',metavar=
'N',
type=
int,nargs=
'+',
help=
'an interger for the accumulator')
-
parser.add_argument(
'--sum',dest=
'accumulate',
action=
'store_const',const=
sum,
default=
max,
help=
'sum the intergers (default:find the max)')
知识点:
+ 每一个参数都要单独设置,就像上面例子,需要两个参数就用两个add_argument 。
+ 从上面的实例中也可以看到,参数分为两种:positional arguments 和optional arguments 。
+ positional arguments 参数按照参数设置的先后顺序对应读取,实际中不用设置参数名,必须有序设计。
+ optional arguments 参数在使用时必须使用参数名,然后是参数具体数值,设置可以是无序的。
+ 程序根据prefix_chars(默认"-")自动识别positional arguments 还是optional arguments。
+ prefix_chars 分为缩写(比如"-h")和对应的全程(比如"--help"),可以同时设置
参数设定详细解释:
+ name or flag
optional arguments以'-'为前缀的参数,其他的为positional arguments。上面例子已经有体现如何设定。
parser.add_argument('-t',action='store_const',const=7)
parser.add_argument('-t',action='store_truet')
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'--str', dest=
'types', action=
'append_const', const=str)
-
>>> parser.add_argument(
'--int', dest=
'types', action=
'append_const', const=int)
-
>>> parser.parse_args(
'--str --int --str --int'.split())
-
Namespace(l=None, types=[
'str'>, 'int'>, 'str'>, 'int'>])
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'--counte',
'-c', action=
'count')
-
>>> parser.parse_args(
'-cccc'.split())
-
Namespace(counte=
4)
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'--version', action=
'version', version=
'version 2.0')
-
>>> parser.parse_args([
'--version'])
-
version
2.0
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'x', type=int, choices=range(
1,
4))
-
>>> parser.parse_args([
'3'])
-
Namespace(x=
3)
-
>>> parser.parse_args([
'4'])
-
usage: [-h] {
1,
2,
3}
-
:
error: argument
x: invalid
choice:
4 (choose from
1,
2,
3)
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'--foo', dest=
'f_name')
-
>>> parser.parse_args(
'--foo XXX'.split())
-
Namespace(f_name=
'XXX')
-
>>> parser = argparse.ArgumentParser()
-
>>> parser.add_argument(
'x')
-
>>> a = parser.parse_args([
'1'])
-
>>> a
-
Namespace(x=
'1')
-
>>> type(a)
-
<
class 'argparse.Namespace'>
-
>>> a.x
-
'1'
filename = argv_argparse.py
-
import sys
-
import argparse
-
-
def cmd():
-
args = argparse.ArgumentParser(description =
'Personal Information ',epilog =
'Information end ')
-
#必写属性,第一位
-
args.add_argument(
"name",
type = str,
help =
"Your name")
-
#必写属性,第二位
-
args.add_argument(
"birth",
type = str,
help =
"birthday")
-
#可选属性,默认为None
-
args.add_argument(
"-r",
'--race',
type = str, dest =
"race",
help = u
"民族")
-
#可选属性,默认为0,范围必须在0~150
-
args.add_argument(
"-a",
"--age",
type = int, dest =
"age",
help =
"Your age", default = 0, choices=range(150))
-
#可选属性,默认为male
-
args.add_argument(
'-s',
"--sex",
type = str, dest =
"sex",
help =
'Your sex', default =
'male', choices=[
'male',
'female'])
-
#可选属性,默认为None,-p后可接多个参数
-
args.add_argument(
"-p",
"--parent",
type = str, dest =
'parent',
help =
"Your parent", default =
"None", nargs =
'*')
-
#可选属性,默认为None,-o后可接多个参数
-
args.add_argument(
"-o",
"--other",
type = str, dest =
'other',
help =
"other Information",required = False,nargs =
'*')
-
-
args = args.parse_args()
#返回一个命名空间,如果想要使用变量,可用args.attr
-
print
"argparse.args=",args,
type(args)
-
print
'name = %s'%args.name
-
d = args.__dict__
-
for key,value
in d.iteritems():
-
print
'%s = %s'%(key,value)
-
-
if __name__==
"__main__":
-
cmd()
dos输入命令示例:
-
python argv_argparse.py -h
-
python argv_argparse.py xiaoming
1991.
11.
11
-
python argv_argparse.py xiaoming
1991.
11.
11 -p xiaohong xiaohei -a
25 -r han -s female -o