標籤:python getopt
getopt
函數原型:
getopt.getopt(args, shortopts, longopts=[])
參數解釋:
- args:args為需要解析的參數列表。一般使用sys.argv[1:],這樣可以過濾掉第一個參數(ps:第一個參數是指令碼的名稱,它不應該作為參數進行解析)
- shortopts:簡寫參數列表
- longopts:長參數列表
傳回值:
- opts:分析出的(option, value)列表對。
- args:不屬于格式資訊的剩餘命令列參數列表。
源碼分析
在Android產生OTA的build系統中,common.py檔案中的ParseOptions函數就是用來解析輸入參數的,我們來通過該函數的實現來分析一下getopt的使用。
函數源碼如下:
def ParseOptions(argv, docstring, extra_opts="", extra_long_opts=(), extra_option_handler=None): try: opts, args = getopt.getopt( argv, "hvp:s:x" + extra_opts, ["help", "verbose", "path=", "signapk_path=", "extra_signapk_args=", "java_path=", "public_key_suffix=", "private_key_suffix=", "device_specific=", "extra="] + list(extra_long_opts)) except getopt.GetoptError, err: Usage(docstring) print "**", str(err), "**" sys.exit(2) path_specified = False for o, a in opts: if o in ("-h", "--help"): Usage(docstring) sys.exit() elif o in ("-v", "--verbose"): OPTIONS.verbose = True elif o in ("-p", "--path"): OPTIONS.search_path = a elif o in ("--signapk_path",): OPTIONS.signapk_path = a elif o in ("--extra_singapk_args",): OPTIONS.extra_signapk_args = shlex.split(a) elif o in ("--java_path",): OPTIONS.java_path = a else: if extra_option_handler is None or not extra_option_handler(o, a): assert False, "unknown option \"%s\"" % (o,) os.environ["PATH"] = (os.path.join(OPTIONS.search_path, "bin") + os.pathsep + os.environ["PATH"]) return args
其中,extra_option_handler可以理解為函數指標,它的功能也是解析opts的索引值對。
extra_option_handler源碼如下:
def option_handler(o, a): if o in ("-b", "--board_config"): pass # deprecated elif o in ("-k", "--package_key"): OPTIONS.package_key = a elif o in ("-i", "--incremental_from"): OPTIONS.incremental_source = a elif o in ("-w", "--wipe_user_data"): OPTIONS.wipe_user_data = True elif o in ("-n", "--no_prereq"): OPTIONS.omit_prereq = True elif o in ("-e", "--extra_script"): OPTIONS.extra_script = a elif o in ("-a", "--aslr_mode"): if a in ("on", "On", "true", "True", "yes", "Yes"): OPTIONS.aslr_mode = True else: OPTIONS.aslr_mode = False elif o in ("--worker_threads"): OPTIONS.worker_threads = int(a) else: return False return True
一般產生OAT全量包的參數argv如下:
argv = [‘-v‘, ‘-p‘, ‘out/host/linux-xxx‘, ‘-k‘, ‘build/target/product/security/testkey‘, ‘out/target/product/xxx/obj/PACKAGING/target_files_intermediates/xxx-target_files.zip‘, ‘out/target/product/xxx/xxx_20150723.1340-ota.zip‘]
首先,對參數進行分析,其中短參數包括:
-v,-p,-k,
經過解析後,產生的結果如下所示:
opts = [(‘-v‘, ‘‘), (‘-p‘, ‘out/host/linux-x86‘), (‘-k‘, ‘build/target/product/security/testkey‘)]args =[‘out/target/product/xxx/obj/PACKAGING/target_files_intermediates/xxx-target_files.zip‘, ‘out/target/product/xxx/xxx_20150723.1340-ota.zip‘]
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
python getopt使用