如何在Python中读取/处理命令行参数?
读取或处理命令行参数的官方方法是使用ArgumentParser模块中的argparse。
argparse模块启用了实现用户友好的命令行界面。该程序定义了所需的参数,而argparse将确定如何从sys.argv中解析这些参数?当用户为程序提供无效参数时,argparse还会生成帮助和用法消息并发出错误。
示例
import argparse
parser = argparse.ArgumentParser(description='Process the numbers')
parser.add_argument('integers',metavar='N', type=int, nargs='+', help='an integer for addition')
parser.add_argument('--sum',dest='addition', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.addition(args.integers))假设,我们已将上述方法保存为文件“argparse_example.py”,可以在命令行中运行并提供有用的消息。
情况1:在不传递参数的情况下运行方法
python argparse_example.py
usage: argparse_example.py [-h] [--sum] N [N ...]
argparse_example.py: error: the following arguments are required: N情况2:运行通过-h作为参数的方法
python argparse_example.py -h
usage: argparse_example.py [-h] [--sum] N [N ...]
Process the numbers
positional arguments:
N an integer for addition
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)情况3:运行传递数字的方法(返回数字列表的最大值)
python argparse_example.py 1 2 3 4
4情况4:运行传递–sum参数作为参数以及数字列表的方法
python argparse_example.py 1 2 3 4 --sum
10热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练