Python 命令行解析器argparse及传参数详解
源码实例一
from argparse import ArgumentParser
parser = ArgumentParser(description='Beeswarm')
group = parser.add_argument_group()
group.add_argument('-se', '--server', action='store_true', help='Starts beeswarm in server mode.')
parser.add_argument('--config', dest='configurl', default='', help='Configuration URL to the server service.')
parser.add_argument('--waitingdrone', action='store_true', default=False, help='Waiting drone mode - expert mode!')
parser.add_argument('--local_socket', dest='local_socket', default=None)
parser.add_argument('--workdir', dest='workdir', default=os.getcwd())
parser.add_argument('--max_sessions', dest='max_sessions', type=int, default=None,
help='Maximum number of sessions to store.')
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Logs debug messages.')
parser.add_argument('--customize', action='store_true', default=False,
help='Asks for specific network and certificate information on the first run.')
parser.add_argument('--clearsessions', action='store_true', default=False,
help='Deletes all sessions on startup.')
parser.add_argument('--resetpw', action='store_true', default=False,
help='Deletes all sessions on startup.')
parser.add_argument('--no_webui', action='store_true', default=False,
help='Do not start the web ui.')
parser.add_argument('-l', '--logfile', dest='logfile', default='beeswarm.log', help='Beeswarm log file..')
args = parser.parse_args()
if is_url(args.configurl):
# meh, MiTM problem here... Acceptable? Workaround?
# maybe print fingerprint on the web ui and let user verify manually?
config_extracted = extract_config_from_api(args.configurl, config_file)
if not config_extracted:
logger.error('Error while extracting configuration from {0}, please make sure that the correct url was '
'provided.'.format(args.configurl))
sys.exit(1)
源码实例二
from optparse import OptionParser
usage = '''
%prog -c config [-t TAGS | -C category] url
%prog -c config [-t TAGS | -C category] -s subdif -f webfile
%prog -c config [-t TAGS | -C category] -u url
'''
_optParser = OptionParser(usage)
_optParser.add_option("-c", "--config", dest="config",
action="append", type="string", help="config file")
_optParser.add_option("-t", "--tags", dest="tags",
action="append", type="string", help="tags config file")
_optParser.add_option("-C", "--category", dest="category",
action="append", type="string", help="category config file")
_optParser.add_option("-s", "--subdir", dest="subdir",
action="store", type="string", help="子目录文件") # sensitive_dir.txt
_optParser.add_option("-f", "--webfile", dest="webfile",
action="store", type="string", help="Web配置文件") # weak_flist.txt
_optParser.add_option("-u", "--url", dest="url",
action="append", type="string", help="被测试的url")
_optParser.add_option("-D", "--depth", dest="depth",
action="store", type="string", help="文件夹测试深度")
_optParser.add_option("-d", "--debug", dest="debug", default=0,
action="count", help="调试模式, 打印调试信息")
_optParser.add_option("-z", "--fuzz", dest="fuzz",
action="store_true", help="do dir && file fuzz, use default dirlist && filelist")
_optParser.add_option("-T", "--thread", dest="thread", default=1,
action="store", type="int", help="blasting thread count")
(options, args) = _optParser.parse_args()
print(options.thread, type(options.thread))
dirfuzz_depth = 1 if not options.depth else int(options.depth)
add_argument:读入命令行参数,该调用有多个参数
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)
>>> parser.add_argument('-f', '--foo') #选项参数
>>> parser.add_argument('bar') #位置参数
nargs: 当选项后接受多个或者0个参数时需要这个来指定
比如-u选项接受2个参数
>>> parser.add_argument('-u',nargs=2)
>>> parser.parse_args('-u a b'.split())
Namespace(u=['a', 'b'])
当选项接受1个或者不需要参数时指定nargs=’?',当没有参数时,会从default中取值。对于选项参数有一个额外的情况,就是出现选项而后面没有跟具体参数,那么会从const中取值
>>> parser.add_argument('-u',nargs='?')
>>> parser.parse_args(''.split())
Namespace(u=None)
>>> parser.parse_args('-u a'.split())
Namespace(u='a')
>>> parser.add_argument('-u',nargs='?',default='d')
>>> parser.add_argument('A',nargs='?',default='e')
>>> parser.parse_args(''.split())
Namespace(A='e', u='d')
>>> parser.parse_args('-u'.split())
Namespace(A='e', u=None)
>>> parser.add_argument('-u',nargs='?',default='d',const='s')
>>> parser.add_argument('A',nargs='?',default='T',const='P')
>>> parser.parse_args(''.split())
Namespace(A='T', u='d')
>>> parser.parse_args('-u'.split())
Namespace(A='T', u='s')
>>> parser.parse_args('A'.split())
Namespace(A='A', u='d')
而对于后面需要跟多个参数的情况(–foo a1 a2 a3…),则需要设置nargs=’*’
>>> parser.add_argument('-u',nargs='*')
>>> parser.parse_args('-u a b c d e'.split())
Namespace(u=['a', 'b', 'c', 'd', 'e'])
nargs=’+'也和nargs=’*'一样,但是有一个区别当’+'时少于1个参数(没有参数)位置参数会报错误
>>> parser.add_argument('u',nargs='+')
>>> parser.parse_args(''.split())
usage: [-h] u [u ...]
: error: too few arguments
而‘*’会使用默认值
>>> parser.add_argument('u',nargs='*',default='e')
>>> parser.parse_args(''.split())
Namespace(u='e')
default: 当参数需要默认值时,由这个参数指定,默认为None,当default=argparse.SUPPRESS时,不使用任何值
>>> parser.add_argument('u',nargs='*',default=argparse.SUPPRESS)
>>> parser.parse_args(''.split())
Namespace()
type: 使用这个参数,转换输入参数的具体类型,这个参数可以关联到某个自定义的处理函数,这种函数通常用来检查值的范围,以及合法性
>>> parser.parse_args('-u',type=int)
>>> parser.add_argument('f',type=file)
>>> parser.parse_args('-u 2 aa'.split())
Namespace(f='aa', mode 'r' at 0x8b4ee38>, u=2)
choices: 这个参数用来检查输入参数的范围
>>> parser.add_argument('-u',type=int,choices=[1,3,5])
>>> parser.parse_args('-u 3'.split())
Namespace(u=3)
>>> parser.parse_args('-u 4'.split())
usage: [-h] [-u {1,3,5}]
: error: argument -u: invalid choice: 4 (choose from 1, 3, 5)
required: 当某个选项指定需要在命令中出现的时候用这个参数
>>> parser.add_argument('-u',required=True)
>>> parser.parse_args(''.split())
usage: [-h] -u U
: error: argument -u is required
help: 使用这个参数描述选项作用
>>> parser.add_argument('-u',required=True,default='wowo',help='%(prog)s for test sth(default: %(default)s)')
>>> parser.print_help() usage: [-h] -u U
optional arguments:
-h, --help show this help message and exit
-u U for test sth(default: wowo)
dest: 这个参数相当于把位置或者选项关联到一个特定的名字
>>> parser.add_argument('--str',nargs='*')
>>> parser.parse_args('--str a b c'.split())
Namespace(str=['a', 'b', 'c'])
>>> parser.add_argument('--str',nargs='*',dest='myname')
>>> parser.parse_args('--str a b c'.split())
Namespace(myname=['a', 'b', 'c'])
metavar: 这个参数用于help 信息输出中
>>> parser.add_argument('--str',nargs='*',metavar='AAA')
>>> parser.print_help()
usage: [-h] [--str [AAA [AAA ...]]]
optional arguments:
-h, --help show this help message and exit
--str [AAA [AAA ...]]
>>> parser.add_argument('str',nargs='*',metavar='AAA')
>>> parser.print_help()
usage: [-h] [AAA [AAA ...]]
positional arguments:
AAA
optional arguments:
-h, --help show this help message and exit
action:store_true
a.py文件的代码如下:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--t', help=' ', action='store_true', default=False)
config = parser.parse_args()
print(config.t)
直接运行python a.py,输出结果False
运行python a.py --t,输出结果True
也就是说,action='store_true',只要运行时该变量有传参就将该变量设为True。
相关文章
- python控制网络继电器
- python add_argument() 的使用方法
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- Python - Windows系统下安装使用virtualenv
- Python做简单的字符串匹配详解
- [转]Python 命令行参数和getopt模块详解
- Python: 爬虫入门-python爬虫入门教程(非常详细)
- 【Python基础】python爬虫之异步网络爬虫ǃ
- Python编程:利用python编程实现对基于时间序列的数据(dataframe格式)按照指定时间范围进行单方向关联,不存在的日期补充为默认的NaN
- Python语言学习:在python中,如何获取变量的本身字符串名字而非其值/内容及其应用(在代码中如何查找同值的所有变量名)
- Python编程语言学习:python编程语言中重要函数讲解之map函数等简介、使用方法之详细攻略
- Python语言学习之打印输出那些事:python输出图表和各种吊炸天的字符串或图画、版权声明(如README.md)等之详细攻略
- Python IDE之Pydev: 基于Eclipse搭建python的编译环境(Eclipse+pydev)简介、安装、使用技巧方法集合之详细攻略
- Python语言学习之数值、小数、空格那些事:python和数值、小数、空格的使用方法之详细攻略
- Python小游戏(滑雪)
- 来看几段代码,测测你是 Python 菜鸟还是老鸟
- 〖Python语法进阶篇⑯〗- 综合实战 - 抽奖系统之基础功能开发 - base奖品相关功能实现
- 力扣——417. 太平洋大西洋水流问题(Java、python、C代码实现)
- Python疫情数据采集, 并做可视化展示
- python将视频分段处理
- 对于python命令行,你应该这么做才专业
- Python开发GUI工具介绍,实战:将图片转化为素描画!
- Python中lambda的使用,与它的三个好基友介绍!
- 编程进阶:这些 Python 常用技巧真棒
- Python获取命令行参数的正确方法,案例详解
- C++调用C++项目中的Python脚本中的函数和类。,在,工程,python
- Python编程:python-attrs模块的简单使用
- Python 两个星号(**)的 参数
- Python标准库:内置函数open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=T
- python自动化测试学习-Python测试框架之unittest和pytest
- Python 命令行模块使用技巧
- 〖Python自动化办公篇㉑〗- python实现邮件自动化 - 定时发送邮件
- Python少儿编程入门篇(2)算术运算和赋值运算