12.20. argparse解析命令行参数

12.20.1. 代码举例1

#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2019/6/19 17:36
# filename: apgparse模块.py

import argparse


def _argparse():
    parser = argparse.ArgumentParser(description="This is description")
    parser.add_argument("--host", action="store",
                        dest="server", default="localhost", help="connect to host")
    parser.add_argument("-t", action="store_true",
                        dest="boolean_switch", default=False, help="Set a switch to true")
    return parser.parse_args()


def main():
    parser = _argparse()
    print(parser)
    print("host = ", parser.server)
    print("boolean_switch=", parser.boolean_switch)


if __name__ == '__main__':
    main()

输出信息

python apgparse模块.py
Namespace(boolean_switch=False, server='localhost')
host =  localhost
boolean_switch= False

python apgparse模块.py --host=127.0.0.1 -t
Namespace(boolean_switch=True, server='127.0.0.1')
host =  127.0.0.1
boolean_switch= True

通过help选项获取帮助信息

python apgparse模块.py --help
usage: apgparse模块.py [-h] [--host SERVER] [-t]

This is description

optional arguments:
  -h, --help     show this help message and exit
  --host SERVER  connect to host
  -t             Set a switch to true

12.20.2. 代码举例2

模仿Mysql客户端的命令行参数

import argparse


def _argparse():
    parser = argparse.ArgumentParser(description="A Python-MySQL client")
    parser.add_argument("--host", action="store",
                        dest="host", required=True, help="connect to host")

    parser.add_argument("-u", "--user", action="store",
                        dest="user", required=True, help="user for login")

    parser.add_argument("-p", "--password", action="store",
                        dest="password", required=True,
                        help="password to use when connecting to server")

    parser.add_argument("-P", "--port", action="store",
                        dest="port", default=3306, type=int,
                        help="port number to use for connection or 3306 for default")
    parser.add_argument("-v", "--version", action="version", version='%(prog)s 0.1')
    return parser.parse_args()

def main():
    parser = _argparse()
    conn_args = dict(host=parser.host, user=parser.user,
                     password=parser.password,port=parser.port)
    print(conn_args)

if __name__ == '__main__':
    main()

输出信息

python apgparse模块.py --help

usage: apgparse模块.py [-h] --host HOST -u USER -p PASSWORD [-P PORT] [-v]

A Python-MySQL client

optional arguments:
  -h, --help            show this help message and exit
  --host HOST           connect to host
  -u USER, --user USER  user for login
  -p PASSWORD, --password PASSWORD
                        password to use when connecting to server
  -P PORT, --port PORT  port number to use for connection or 3306 for default
  -v, --version         show program's version number and exit

示例代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @auther:   18793
# @Date:    2020/9/30 10:04
# @filename: argparse01.py
# @Email:    1879324764@qq.com
# @Software: PyCharm
import argparse


def get_argparse():
    parser = argparse.ArgumentParser(description='A email client in terminal')
    parser.add_argument('-s', action='store', dest='subject', required=True, help='specify a subject (must be in quotes if it has spaces)')
    parser.add_argument('-a', action='store', nargs='*', dest='attaches', required=False, help='attach file(s) to the message')
    parser.add_argument('-f', action='store', dest='conf', required=False, help='specify an alternate .emcli.cnf file')
    parser.add_argument('-r', action='store', nargs='*', dest='recipients', required=True, help='recipient who you are sending the email to')
    parser.add_argument('-v', action='version', version='%(prog)s 0.2')
    return parser.parse_args()



if __name__ == '__main__':
    parser = get_argparse()
    print(parser)
    print("s = ", parser.subject)
    print("r = ", parser.recipients)
    print("f = ", parser.conf)
D:\GitHub\python标准库\解析命令行参数>python argparse02.py -s hu -r huajianli -f "config.cfg"
Namespace(attaches=None, conf='config.cfg', recipients=['huajianli'], subject='hu')
s =  hu
r =  ['huajianli']
f =  config.cfg

12.20.3. argparse模块示例

Python实用模块(二十六)argparse https://xugaoxiang.com/2020/11/11/python-module-argparse/

12.20.4. Python命令行参数的3种传入方式

https://tendcode.com/article/python-shell/