Domanda

How do I access the prog variable of the

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)

how do I access prog variable from argparse.ArgumentParser as well as PYTHON_VERSION from environment as well?

È stato utile?

Soluzione

>>> 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)
>>>

If you want to 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)

Here check whether the required argument are defined not called :

>>> parser.print_usage()

Here is a small snippet:

#!/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()

Output:

 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$
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top