Last active
April 10, 2017 08:26
-
-
Save MOOOWOOO/652b30e438e6124d4b35e2871ca50d0b to your computer and use it in GitHub Desktop.
new project use argument parser init
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
import sys | |
from argparse import ArgumentParser | |
def main(*args): | |
pass | |
def init_arg_list(argument_paser): | |
argument_paser.add_argument('-a', | |
'--aparam', | |
help='param a', | |
action='store') | |
argument_paser.add_argument('-b', | |
'--bparam', | |
help='param a', | |
action='store_true') | |
# 参数action有: | |
# store:默认action模式,存储值到指定变量。 | |
# store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。 | |
# store_true / store_false:布尔开关。可以2个参数对应一个变量。 | |
# append:存储值到列表,该参数可以重复使用。 | |
# append_const:存储值到列表,存储值在参数的const部分指定。 | |
def check_args(argument_paser): | |
if len(sys.argv) == 1: | |
argument_paser.print_help() | |
sys.exit(1) | |
if __name__ == "__main__": | |
ap = ArgumentParser() | |
init_arg_list(ap) | |
check_args(ap) | |
args, remaining = ap.parse_known_args(sys.argv) | |
main(args) | |
# python3 ./ArgumentParserInit.py -a 123 | |
# ('args', Namespace(aparam='123', bparam=False)) | |
# ('remaining', ['./ArgumentParserInit.py']) | |
# ('args.aparam', '123') | |
# ('args.bparam', False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment