Python命令行参数argv和argparse该如何使用

作者:葛木瓜 时间:2022-04-05 01:38:52 

概述

运行python脚本时通过命令行方式传入运行参数通常有以下两种自建方式:

  • sys.argv - 简洁

  • argparse - 丰富,可自定义

下面详细说一下具体时使用

argv


# test_argv.py

import sys

args = sys.argv
print(f'args = {args}')

>>> output
➜ git:(master) python3 test_argv.py    
args = ['test_argv.py']
➜ git:(master) ✗ python3 test_argv.py 1 2 3
args = ['test_argv.py', '1', '2', '3']
➜ git:(master) ✗ python3 test_argv.py 1 2 3 'hello world !'
args = ['test_argv.py', '1', '2', '3', 'hello world !']

从上面可以看出,通过argv方法获取的结果:

  • 返回为list

  • 第一个参数为脚本本身

  • 如参数中间带空格,用引号即可

argparse

argparse模块的功能较为丰富,其核心是通过add_argument方法自定义入参的:标志、格式、类型和范围等特性,常用如下:

  • *name_or_flag - 定义入参名或flag,如'-n', '--number'

  • type - 指定入参类型

  • choices - 指定入参范围

  • default - 指定入参默认值

  • required - 指定该餐素是否不要,布尔类型

  • help - 参数概述

更多请参考: argparse

实例

test_argv.py


import argparse

# 初始化一个parser对象
parser = argparse.ArgumentParser(description='test module of argparse')

# 指定-n/--number的参数
# 类型为int
# help为简短地说明
parser.add_argument(
 '-n', '--number', type=int,
 help='args of number'
)

# 指定-o/--output参数
# 并限制类型为:['txt', 'csv', 'doc']
parser.add_argument(
 '-o', '--output', type=str,
 choices=['txt', 'csv', 'doc'],
 help='output method'
)

# 指定-d/--default参数
# 并限制类型为:['txt', 'csv', 'doc']
parser.add_argument(
 '-d', '--default', type=int,
 choices=[_ for _ in range(1, 10)],
 default=5,
 help='default'
)

# 指定位置参数foo
parser.add_argument('foo')

args = parser.parse_args()
print(f'args = {args}')

# 获取指定参数
print(
 f'number = {args.number}, type = {type(args.number)}\n'
 f'output = {args.output}, type = {type(args.output)}\n'
 f'default = {args.default}, type = {type(args.default)}\n'
 f'foo = {args.foo}, type = {type(args.foo)}'
)

output


# -h - 打印help
➜ git:(master) ✗ python3 test_argv.py -h
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
         [-d {1,2,3,4,5,6,7,8,9}]
         foo

test module of argparse

positional arguments:
foo

optional arguments:
-h, --help      show this help message and exit
-n NUMBER, --number NUMBER
           args of number
-o {txt,csv,doc}, --output {txt,csv,doc}
           output method
-d {1,2,3,4,5,6,7,8,9}, --default {1,2,3,4,5,6,7,8,9}
           default
# 不带参数运行,结果为None
➜ git:(master) ✗ python3 test_argv.py  
args = Namespace(number=None, output=None)
number = None
output = None

# 带参数运行
➜ git:(master) ✗ python3 test_argv.py -n 33 --output txt
args = Namespace(number=33, output='txt')
number = 33, type = <class 'int'>
output = txt, type = <class 'str'>

# 参数格式错误
➜ git:(master) ✗ python3 test_argv.py -n str    
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -n/--number: invalid int value: 'str'
➜ git:(master) ✗ python3 test_argv.py -o excel    
usage: test_argv.py [-h] [-n NUMBER] [-o {txt,csv,doc}]
test_argv.py: error: argument -o/--output: invalid choice: 'excel' (choose from 'txt', 'csv', 'doc')

# 默认参数
➜ git:(master) ✗ python3 test_argv.py  
args = Namespace(default=5, number=None, output=None)
number = None, type = <class 'NoneType'>
output = None, type = <class 'NoneType'>
output = 5, type = <class 'int'>

来源:https://www.cnblogs.com/freedomlidi/p/12680005.html

标签:python,命令行参数,argv,argparse
0
投稿

猜你喜欢

  • 如何基于Python制作有道翻译小工具

    2023-10-01 21:00:58
  • javascript 时间脚本收集

    2013-07-17 19:52:50
  • phpstudy apache开启ssi使用详解

    2023-05-25 08:04:44
  • Python及PyCharm下载与安装教程

    2022-10-04 08:19:54
  • Python使用列表和字典实现简单的考试系统详解

    2023-11-07 11:14:53
  • 用XMLHTTP很好的一个例子

    2008-04-25 10:25:00
  • Python flask框架如何显示图像到web页面

    2022-05-20 00:11:05
  • Oracle 插入超4000字节的CLOB字段的处理方法

    2009-07-12 18:52:00
  • 使用 python pyautogui实现鼠标键盘控制功能

    2023-11-17 07:01:41
  • python快速编写单行注释多行注释的方法

    2022-06-04 07:06:54
  • 如何用Anaconda搭建虚拟环境并创建Django项目

    2022-02-25 02:30:21
  • Web标准基础教程:CSS简写指南

    2010-04-02 12:47:00
  • Python WebSocket长连接心跳与短连接的示例

    2022-08-20 04:05:15
  • Python设计模式之观察者模式简单示例

    2023-07-12 04:36:06
  • sqlserver 2000中创建用户的图文方法

    2012-03-26 18:26:39
  • Python3使用requests登录人人影视网站的方法

    2021-10-04 15:42:19
  • PHP addAttribute()函数讲解

    2023-06-06 09:03:45
  • sqlserver 数据库压缩与数据库日志(ldf)压缩方法分享

    2012-01-05 18:57:19
  • Python类属性与实例属性用法分析

    2022-10-12 03:14:58
  • apache+mysql+php+ssl服务器之完全安装攻略

    2023-11-16 07:34:16
  • asp之家 网络编程 m.aspxhome.com