使用环境变量访问ArgumentParser变量

时间:2014-02-03 14:00:37

标签: python environment-variables argparse

如何访问

的prog变量
parser = argparse.ArgumentParser(prog='ipush',
        description='Utility to push the last commit and email the color diff')
    parser.add_argument('-V', '--version', action='version',
        version='%(prog)s 1.0,$s'PYTHON_VERSION)

如何从环境中argparse.ArgumentParser以及PYTHON_VERSION访问prog变量?

1 个答案:

答案 0 :(得分:0)

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='ipush',
...         description='Utility to push the last commit and email the color diff')
>>>
>>> parser.prog
'ipush'
>>>

for python version:

>>> import sys
>>> sys.version
'2.7.2 (default, Oct 11 2012, 20:14:37) \n[GCC 4.2.1 Compatible Apple Clang 4.0     (tags/Apple/clang-418.0.60)]'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
>>>

如果你想print_usage:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='ipush',description='Utility to push the last commit and email the color diff')
>>> p = parser.parse_args()
>>> argument = vars(p)

这里检查是否定义了所需的参数:

>>> parser.print_usage()

这是一个小片段:

#!/usr/bin/python

import argparse

def run(p):

    """ Execute base on the arguments """
    if p.get('create', False) is True:
        # do something
        return True

    elif p.get('find', False) is True:
        # do something
        return True
    else:
        return False

def main():

    parser = argparse.ArgumentParser(prog='ipush',
                   description='Utility to push the last commit and email the color diff')
    parser.add_argument('--find', action="store_true",
                       help="find the user details")
    parser.add_argument('--create', action='store_true',
                       help="creating the database")

    p = parser.parse_args()

    argument = vars(p)

    if run(argument) is False:
        parser.print_usage()

if __name__ == '__main__':
    main()

输出:

 test_script/tmp$ python p.py
 usage: ipush [-h] [--find] [--create]
 test_script/tmp$ python p.py -h
 usage: ipush [-h] [--find] [--create]

 Utility to push the last commit and email the color diff

 optional arguments:
   -h, --help  show this help message and exit
   --find      find the user details
   --create    creating the database
 test_script/tmp$ python p.py --find
 test_script/tmp$