怎样让自己写的脚本看上去更加的专业,当然是有 --help 或者 -h 这个功能。
Python自带的argparse 模块能够很容易的帮我们实现这个功能。
直接上代码:
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, 输出如下:
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.html