python学习之argparse模块

一、简介:

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.

python学习之argparse模块的更多相关文章

  1. python学习之argparse模块的使用

    以下内容主要来自:http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/argparse.html argparse ...

  2. Python学习 Part4:模块

    Python学习 Part4:模块 1. 模块是将定义保存在一个文件中的方法,然后在脚本中或解释器的交互实例中使用.模块中的定义可以被导入到其他模块或者main模块. 模块就是一个包含Python定义 ...

  3. Python学习day19-常用模块之re模块

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  4. Python学习day18-常用模块之NumPy

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

  5. python学习之random模块

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  6. Python学习之argparse

    http://www.2cto.com/kf/201412/363654.html https://docs.python.org/3.4/howto/argparse.html# 一.简介: arg ...

  7. Python学习笔记之模块与包

    一.模块 1.模块的概念 模块这一概念很大程度上是为了解决代码的可重用性而出现的,其实这一概念并没有多复杂,简单来说不过是一个后缀为 .py 的 Python 文件而已 例如,我在某个工作中经常需要打 ...

  8. Python学习笔记-常用模块

    1.python模块 如果你退出 Python 解释器并重新进入,你做的任何定义(变量和方法)都会丢失.因此,如果你想要编写一些更大的程序,为准备解释器输入使用一个文本编辑器会更好,并以那个文件替代作 ...

  9. Python学习笔记1—模块

    模块的使用 引用模块的两种形式 形式一: import module_name 形式二: from module1 import module11   (module11是module的子模块) 例: ...

随机推荐

  1. BZOJ 1124: [POI2008]枪战Maf(构造 + 贪心)

    题意 有 \(n\) 个人,每个人手里有一把手枪.一开始所有人都选定一个人瞄准(有可能瞄准自己).然后他们按某个顺序开枪,且任意时刻只有一个人开枪. 因此,对于不同的开枪顺序,最后死的人也不同. 问最 ...

  2. emwin之窗口关闭按钮用法

    @2018-07-27 [小记] 使用函数 FRAMEWIN_AddCloseButton() 实现关闭当前窗口的功能时,调用其窗口的父窗口必须处于打开状态,否则将导致假死(当前窗口死了,系统还在工作 ...

  3. 【转】stm32CubeMx上移植自己的printf()和scanf()函数

    要想printf()和scanf() 函数工作,我们需要把printf()和scanf() 重新定向到串口中.重定向是指用户可以自己重写C 的库函数,当连接器检查到用户编写了与C 库函数相同名字的函数 ...

  4. c语言输入字符注意

    1.c=getchar(); //getchar can't accept Space Tab 2.    scanf("%c",&c);    printf(" ...

  5. 程序编译运行和exe运行之文件位置的区别

    如图: 文件输入输出 1.程序编译运行 输入文件和输出文件与.c同位置 2.exe运行 输入文件和输出文件与.exe同位置

  6. hiho一下 第144周(机会渺茫)解题报告及拓展

    题目1 : 机会渺茫 时间限制:5000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi最近在追求一名学数学的女生小Z.小Z其实是想拒绝他的,但是找不到好的说辞,于是提出了这样的要求: ...

  7. zoj3707(Calculate Prime S)解题报告

    1.计算(a/b)%c,其中b能整除a 设a=b*r=(bc)*s+b*t 则(b*t)为a除以bc的余数 r=c*s+t 而 (a/b)%c=r%c=t (a%bc)/b=(b*t)/b=t 所以对 ...

  8. 13 款高逼格且实用的 Linux 运维必备工具

    转载于民工哥技术之路 1. 查看进程占用带宽情况 - Nethogs Nethogs 是一个终端下的网络流量监控工具可以直观的显示每个进程占用的带宽. 下载:http://sourceforge.ne ...

  9. pyglet and opengl -- 纹理映射以及动画

    #-*- coding:gbk -*- #from pyglet.gl import * from OpenGL.GL import * import pyglet from pyglet impor ...

  10. Java_myBatis_全局配置文件

    mybatis主要需要配置的项: 1.properties  配置文件的“环境变量”键值对 2.typeAliases  输入输出数据的类型 3.mappers  映射配置文件 下面看看实例: < ...