博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python学习之argparse模块
阅读量:7113 次
发布时间:2019-06-28

本文共 4744 字,大约阅读时间需要 15 分钟。

本文参考

http://www.2cto.com/kf/201412/363654.html

http://blog.itpub.net/26250550/viewspace-1281968/

并综合整理

 

一、简介:

argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。argparse模块的作用是用于解析命令行参数,例如python parseTest.py input.txt output.txt --user=name --port=8080。

二、使用步骤:

1:import argparse

2:parser = argparse.ArgumentParser()

3:parser.add_argument()

4:parser.parse_args()

解释:首先导入该模块;然后创建一个解析对象;然后向该对象中添加你要关注的命令行参数和选项,每一个add_argument方法对应一个你要关注的参数或选项;最后调用parse_args()方法进行解析;解析成功之后即可使用,下面简单说明一下步骤2和3。

 

三、方法ArgumentParser(prog=None, usage=None,description=None, epilog=None, parents=[],formatter_class=argparse.HelpFormatter, prefix_chars='-',fromfile_prefix_chars=None, argument_default=None,conflict_handler='error', add_help=True)

这些参数都有默认值,当调用parser.print_help()或者运行程序时由于参数不正确(此时python解释器其实也是调用了pring_help()方法)时,会打印这些描述信息,一般只需要传递description参数,如上。

四、方法add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

其中:

name or flags:命令行参数名或者选项,如上面的address或者-p,--port.其中命令行参数如果没给定,且没有设置defualt,则出错。但是如果是选项的话,则设置为None

nargs:命令行参数的个数,一般使用通配符表示,其中,'?'表示只用一个,'*'表示0到多个,'+'表示至少一个

default:默认值

type:参数的类型,默认是字符串string类型,还有float、int等类型

help:和ArgumentParser方法中的参数作用相似,出现的场合也一致

 

最常用的地方就是这些,其他的可以参考官方文档。下面给出一个例子,基本包括了常见的情形:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import
argparse
 
def parse_args():
    
description = usage: %prog [options] poetry-file
 
This is the Slow Poetry Server, blocking edition.
Run it like
this
:
 
  
python slowpoetry.py <path-to-poetry-file>
 
If you are in the base directory of the twisted-intro
package
,
you could run it like
this
:
 
  
python blocking-server/slowpoetry.py poetry/ecstasy.txt
 
to serve up John Donne's Ecstasy, which I know you want to
do
.
 
 
    
parser = argparse.ArgumentParser(description = description)
     
    
help = The addresses to connect.
    
parser.add_argument(
'addresses'
,nargs =
'*'
,help = help)
 
    
help = The filename to operate on.Default is poetry/ecstasy.txt
    
parser.add_argument(
'filename'
,help=help)
 
    
help = The port to listen on. Default to a random available port.
    
parser.add_argument(
'-p'
,--port', type=
int
, help=help)
 
    
help = The
interface
to listen on. Default is localhost.
    
parser.add_argument(
'--iface'
, help=help,
default
=
'localhost'
)
 
    
help = The number of seconds between sending bytes.
    
parser.add_argument(
'--delay'
, type=
float
, help=help,
default
=.
7
)
 
    
help = The number of bytes to send at a time.
    
parser.add_argument(
'--bytes'
, type=
int
, help=help,
default
=
10
)
 
    
args = parser.parse_args();
    
return
args
 
if
__name__ ==
'__main__'
:
    
args = parse_args()
     
    
for
address in args.addresses:
        
print
'The address is : %s .'
% address
     
    
print
'The filename is : %s .'
% args.filename
    
print
'The port is : %d.'
% args.port
    
print
'The interface is : %s.'
% args.iface
    
print
'The number of seconds between sending bytes : %f'
% args.delay
    
print
'The number of bytes to send at a time : %d.'
% args.bytes</path-to-poetry-file>

运行该脚本:python test.py --port 10000 --delay 1.2 127.0.0.1 172.16.55.67 poetry/ecstasy.txt

 

输出为:

The address is : 127.0.0.1 .

The address is : 172.16.55.67 .
The filename is : poetry/ecstasy.txt .
The port is : 10000.
The interface is : localhost.
The number of seconds between sending bytes : 1.200000
The number of bytes to send at a time : 10.

 

==============================================================================

import argparse

parse = argparse.ArgumentParser()
parse.add_argument("a", help="params means")
parse.add_argument("-C", "--gc", default="count")
parse.add_argument("--ga", help="params means ga",dest='simple_value',choices=['A', 'B', 'C', 0])
parse.add_argument("--gb", help="params means gb",action="store_const",const='value-to-store')
args = parse.parse_args()
print args.simple_value,args.gb,args.gc
### add_argument 说明
不带'--'的参数
    调用脚本时必须输入值
    参数输入的顺序与程序中定义的顺序一致
'-'的参数
    可不输入    add_argument("-a")
    类似有'--'的shortname,但程序中的变量名为定义的参数名
'--'参数
    参数别名: 只能是1个字符,区分大小写
        add_argument("-shortname","--name", help="params means"),但代码中不能使用shortname
    dest: 参数在程序中对应的变量名称 add_argument("a",dest='code_name')
    default: 参数默认值
    help: 参数作用解释  add_argument("a", help="params means")
    type : 默认string  add_argument("c", type=int)
    action:

    store:默认action模式,存储值到指定变量。
    store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。
    store_true / store_false:布尔开关。 store_true.默认为False,输入则为true。 store_flase 相反
    append:存储值到列表,该参数可以重复使用。
    append_const:存储值到列表,存储值在参数的const部分指定。
    count: 统计参数简写输入的个数  add_argument("-c", "--gc", action="count")
    version 输出版本信息然后退出。

    const:配合action="store_const|append_const"使用,默认值

    choices:输入值的范围 add_argument("--gb", choices=['A', 'B', 'C', 0])
    required : 默认False, 若为 True, 表示必须输入该参数

转载于:https://www.cnblogs.com/hadis-yuki/p/5444333.html

你可能感兴趣的文章
(转) OpenCV学习笔记大集锦 与 图像视觉博客资源2之MIT斯坦福CMU
查看>>
Controller 接口控制器详解
查看>>
【转】【MySQL】mysql 通过bin-log恢复数据方法详解
查看>>
linux上安装启动elasticsearch-5.5.1完整步骤
查看>>
请求失败或服务未及时响应。有关详细信息,请参见事件日志或其他适用的错误日志...
查看>>
Silverlight 4 MVVM开发方式(一)小黑端
查看>>
公告:CSDN博客频道新功能正式上线!
查看>>
Web服务的体系架构
查看>>
linux下apache的使用
查看>>
UML对象图(转载)
查看>>
Computer skills one can learn within one day
查看>>
关于删除MySQL Logs的一点记录
查看>>
[cb]Unity 项目架构
查看>>
spin_lock & mutex_lock的区别?
查看>>
居安思危,奋发图强,别整那些没用的
查看>>
数据库的备份与还原
查看>>
C语言清空输入缓冲区的N种方法对比【转】
查看>>
zabbix安装配置及监控脚本编写案例【转】
查看>>
linux USB HOST之EHCI和OHCI【转】
查看>>
使用 systemd timer 备份数据库
查看>>