Python argparse

How to make your own scripts look more professional, of course, there is the --help or -h function.

The argparse module that comes with Python can easily help us achieve this function.

Go directly to the code:

import argparse

VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION[0:2]))
__description__ = 'HTTP Proxy Server in Python'
__author__ = 'Abhinav Singh'
__author_email__ = '[email protected]'
__homepage__ = 'https://github.com/abhinavsingh/proxy.py'
__license__ = 'BSD'


def main():
    parser = argparse.ArgumentParser(
        description='proxy.py v%s' % __version__,
        epilog='Having difficulty using proxy.py? Report at: %s/issues/new' % __homepage__
    )

    parser.add_argument('--hostname', default='127.0.0.1', help='Default: 127.0.0.1')
    parser.add_argument('--port', default='8899', help='Default: 8899')
    parser.add_argument('--log-level', default='INFO', help='DEBUG, INFO, WARNING, ERROR, CRITICAL')
    args = parser.parse_args()

if __name__ == '__main__':
    main()

 

Executing the program with --help, the output is as follows:

usage: argparse_test.py [-h] [--hostname HOSTNAME] [--port PORT]
                        [--log-level LOG_LEVEL]

proxy.py v0.2

optional arguments:
  -h, --help            show this help message and exit
  --hostname HOSTNAME   Default: 127.0.0.1
  --port PORT           Default: 8899
  --log-level LOG_LEVEL
                        DEBUG, INFO, WARNING, ERROR, CRITICAL

Having difficulty using proxy.py? Report at:
https://github.com/abhinavsingh/proxy.py/issues/new

 

More about argparse: https://docs.python.org/3/howto/argparse.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324737018&siteId=291194637