argparse 能够根据程序中的定义从 sys.argv 中解析出这些参数,并自动生成帮助和使用信息。
ArgumentParse 解析器
使用 argparse 解析命令行参数时,首先需要创建一个解析器:
import argparseparser = argparse.ArgumentParser()
- description 比较常用的参数,程序的描述信息
使用 add_argument 方法为应用程序添加参数选项
def add_argument(self,*name_or_flags: Text, # 参数的名字action: Union[Text, Type[Action]] = ..., # 遇到参数时的动作nargs: Union[int, Text] = ..., # 参数的个数,可以是具体的数字,也可以是 + 或者 *,* 0 个或多个,+ 1个或多个const: Any = ..., # 需要的常量值default: Any = ..., # 不指定参数时的默认值type: Union[Callable[[Text], _T], Callable[[str], _T], FileType] = ..., # 参数的类型choices: Iterable[_T] = ..., # 参数允许的值required: bool = ..., # 可选参数是否可以忽略help: Optional[Text] = ..., # 参数的帮助信息metavar: Optional[Union[Text, Tuple[Text, ...]]] = ..., # 在 useage 说明中的参数名称dest: Optional[Text] = ..., # 解析后的参数名称version: Text = ...,**kwargs: Any,)
- parse_args 方法进行解析参数,该方法返回一个 Namespace 对象。获取对象以后,参数值通过属性的方式进行访问。 ```python 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’, default=False, dest=’boolean_switch’, 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()
```bash❯ python test_argparse.pyNamespace(server='localhost', boolean_switch=False)host = localhostboolean_switch = False❯ python test_argparse.py --host=127.0.0.1 -tNamespace(server='127.0.0.1', boolean_switch=True)host = 127.0.0.1boolean_switch = True
argparse 会根据我们的选项定义自动生成帮助信息
❯ python test_argparse.py --helpusage: test_argparse.py [-h] [--host SERVER] [-t]This is descriptionoptional arguments:-h, --help show this help message and exit--host SERVER connect to host-t Set a switch to true
模仿 MySQL 客户端的命令行参数
import argparsedef _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 conneting 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, version=parser.version)print(conn_args)if __name__ == '__main__':main()
❯ python mock_mysql_client.py --helpusage: mock_mysql_client.py [-h] --host HOST -u USER -p PASSWORD [-P PORT] [-v]A Python_MySQL clientoptional arguments:-h, --help show this help message and exit--host HOST connect to host-u USER, --user USER user for login-p PASSWORD, --password PASSWORDpassword to use when conneting 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
