Python argparse

怎樣讓本身寫的腳本看上去更加的專業,固然是有 --help 或者 -h 這個功能。html

Python自帶的argparse 模塊可以很容易的幫咱們實現這個功能。python

直接上代碼:git

import argparse

VERSION = (0, 2)
__version__ = '.'.join(map(str, VERSION[0:2]))
__description__ = 'HTTP Proxy Server in Python'
__author__ = 'Abhinav Singh'
__author_email__ = 'mailsforabhinav@gmail.com'
__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()

 

執行程序加上 --help, 輸出以下:github

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

 

更多關於argparse: https://docs.python.org/3/howto/argparse.htmlthis

相關文章
相關標籤/搜索