Python 命令行与参数解析方法有很多工具,本文使用python 自带的argparse 来说明python 如何进行命令行解析。
什么是命令行与参数解析?
通俗来说,命令行与参数解析就是当你输入cmd 打开dos 交互界面时候,启动程序要进行的参数给定。比如在dos 界面输入:
python openPythonFile.py "a" -b "number"
其中的"a", -b 等就是命令行与参数解析要做的事。
~~这在windows 系统下用处不是特别大,因为windows 下各种编译器,你根本不需要在dos 界面下去执行python 脚本。但是在linux 系统下,你几乎要总是考虑命令行解析。~~
和操作系统无关,就是设计程序在运行时必须给定某些额外参数才能运行,也就是如果设置了命令行参数解析,那么各种编译器按F5 是无法直接运行程序的。用途,就是不能随便就能运行脚本,可以达到一定程度上的安全功能。
Python 命令行与参数解析使用步骤
创建解析
添加参数
解析参数
下面通过一个例子进行简单创建:
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=, conflict_handler='error', add_help=True)
# 例如
parser = argparse.ArgumentParser(description='Process some integers.')
prog(不建议更改)
程序名称(默认sys.argv[0],默认为函数文件名),设置prog 则改变这一默认(仍使用上面那个实例):
# 变更参数
parser = argparse.ArgumentParser(prog='sum or max',descripti