Python脚本添加命令行参数

如果希望Python脚本执行的时候可以带上参数,如
python test.py --help
python test.py -a
python test.py --version
可以使用argparse模块的ArgumentParser类来实现。

示例:

import argparse

# 实例化一个argparse.ArgumentParser对象
parser = argparse.ArgumentParser(prog='myprogram', description='这些描述内容会在执行--help时显示.')

# 定义了一个无需指定值的参数-a
parser.add_argument('-a', action='store_true', help='option a')
# 定义了一个需要给一个整数作为值的参数b
# 使用-b 123 或者 -b=123 给值
parser.add_argument('-b', action='store', dest='value_of_b', type=int, help='option b')
# 让-V和--version都可以打印版本信息
parser.add_argument('-V', '--version', action='version', version='%(prog)s 1.0')

# 解析命令行参数
args = parser.parse_args()

if not any(vars(args).values()):
    # 如果没有接任何参数,打印帮助信息
	parser.print_help()
else:
    # 没有显式指定dest,默认将参数名设置为dest的值
    if args.a:
        print('option a is set')
    if args.value_of_b:
        print('the value of option b is: ', args.value_of_b)

脚本执行示例:

# python3 test.py --help
usage: myprogram [-h] [-a] [-b VALUE_OF_B] [-V]

这些描述内容会在执行--help时显示.

optional arguments:
  -h, --help     show this help message and exit
  -a             option a
  -b VALUE_OF_B  option b
  -V, --version  show program's version number and exit

# python3 test.py -b 123
the value of option b is:  123

argparse.ArgumentParser()可选参数:

  • prog:该程序的名称(默认情况下,将从 sys.argv[0] 中获取该名称,即脚本名)。
  • usage:程序用法的简短描述,如果不指定,则默认为从参数定义生成的描述。
  • description:程序的简要描述。
  • epilog:程序的结尾文本,通常用于提供更多信息。
  • parents:一组父级 ArgumentParser 对象,这些对象中定义的所有参数也将包含在该对象中。
  • formatter_class:用于自定义帮助信息格式的类。
  • prefix_chars:用于标识命令行选项的前缀字符,默认为 '-'。
  • fromfile_prefix_chars:用于指定读取参数值列表的文件的前缀字符,默认为 '@'。
  • argument_default:用于设置参数的默认值。
  • conflict_handler:用于处理参数定义之间的冲突的策略。
  • add_help:是否添加 -h/--help 选项来显示帮助信息。默认为 True。可以在想自定义-h参数时使用此参数,禁用默认的帮助信息选项,然后再手动定义一个参数用于显示帮助信息选项,让-h实现自定义的功能。

parser.add_argument()可选参数:

  • name or flags: 参数的名称或标志,例如 -f--file。可以使用逗号分隔的多个选项来表示同一个参数的多个名称或标志。
  • action: 定义参数被指定时的行为,可以使用以下值:
    • store: 将参数值保存到一个属性中。
    • store_const: 将指定的常量值保存到一个属性中。
    • store_true: 将 True 值保存到一个属性中。
    • store_false: 将 False 值保存到一个属性中。
    • append: 将参数值追加到一个列表中。
    • append_const: 将指定的常量值追加到一个列表中。
    • count: 统计指定参数出现的次数。
    • version: 打印程序的版本信息并退出。
    • help: 打印帮助信息并退出。
  • nargs: 参数接受的值的数量,可以使用以下值:
    • N: 接受固定数量的参数值。
    • ?: 接受一个可选的参数值。
    • *: 接受任意数量的参数值,将值保存到一个列表中。
    • +: 接受一个或多个参数值,将值保存到一个列表中。
  • const: 存储在参数中的常量值。
  • default: 参数的默认值。
  • type: 参数的类型,可以是内置类型(例如 int 或 float),也可以是自定义类型(例如解析一个字符串并返回一个自定义对象)。
    • str:将命令行参数解析为字符串类型(默认)。
    • int:将命令行参数解析为整数类型。
    • float:将命令行参数解析为浮点数类型。
    • complex:将命令行参数解析为复数类型。
    • list:将命令行参数解析为列表类型。例如 -l 1 2 3 可以解析成 [1, 2, 3]。
    • tuple:将命令行参数解析为元组类型。例如 -t 1 2 3 可以解析成 (1, 2, 3)。
    • file:将命令行参数解析为文件类型。例如 -f input.txt 将打开 input.txt 文件并返回文件对象。
    • 自定义函数:可以传递一个自定义函数来将命令行参数解析为指定的类型。函数应该接受一个参数(要解析的值),并返回解析后的结果。例如,type=lambda x: x.upper() 将所有字符串转换为大写字符串
  • choices: 参数可以接受的值的列表或元组。
  • required: 是否需要该参数。
  • help: 参数的帮助文本。
  • metavar: 在帮助文本中使用的参数值占位符。
  • dest: 存储参数值的属性名称。
  • const: 指定一个常量值,仅在 action='store_const' 时使用。
  • version: 程序版本信息,仅在 action='version' 时使用。

注意:两个不同参数的dest值不能一样,会有冲突!

写一个吃饱了没事做的脚步:

import argparse
import os

parser = argparse.ArgumentParser(prog='mysql_connect', description='这是一个吃饱了没事做的脚本')
parser.add_argument('-u', action='store', dest='user', type=str, required=True, help='mysql user')
parser.add_argument('-p', action='store', dest='password', type=str, required=True, help='mysql password')
parser.add_argument('-P', action='store', dest='port', type=str, default='3306', help='mysql port')
parser.add_argument('--host', action='store', dest='host', type=str, default='127.0.0.1', help='mysql host')
parser.add_argument('-V', '--version', action='version', version='%(prog)s 1.0')

args = parser.parse_args()

os.system(f"mysql -h{args.host} -P{args.port} -u{args.user} -p{args.password}")

该脚本用于连接mysql数据库,定义了五个参数,分别为用户名、密码、数据库端口、数据库host以及输出版本信息。其中用户名和密码为必须参数,host和端口提供了默认值。
执行效果:

# python3 db_connect.py --host=localhost -u=root -123456 -P3306
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

root@localhost [(none)]>
posted @ 2023-03-07 11:45  Charramma  阅读(323)  评论(0编辑  收藏  举报