Python 命令行解析器argparse及传参数详解
源碼實例一
from argparse import ArgumentParserparser = 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 OptionParserusage = '''%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個參數
?
當選項接受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 命令行解析器argparse及传参数详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: twisted系列教程十四— pre-f
- 下一篇: nc个人实战使用总结