python 以其多功能性和易用性而闻名,尤其是在构建命令行界面 (cli) 应用程序时。无论您是想自动执行日常任务、构建开发人员工具还是创建灵活的脚本,python 丰富的生态系统都提供了各种库来高效处理 cli。
在这篇博文中,我们将深入探讨如何使用 python 中的 cli,涵盖以下内容:
在这篇文章结束时,您将能够创建强大且用户友好的命令行应用程序。
cli 广泛用于系统管理、数据处理和软件开发,因为它们提供:
python 提供了多个库来构建 cli 工具:
sys.argv 是访问命令行参数的基本方法。它将命令行参数存储为列表,其中第一个元素始终是脚本名称。
import sys # command-line arguments print(f"script name: {sys.argv[0]}") print(f"arguments: {sys.argv[1:]}")
运行脚本:
$ python script.py arg1 arg2 arg3 script name: script.py arguments: ['arg1', 'arg2', 'arg3']
argparse 模块是用于创建 cli 的 python 标准库。它提供比 sys.argv 更多的控制,并自动生成帮助消息和错误处理。
import argparse parser = argparse.argumentparser(description="a simple cli tool") parser.add_argument("name", help="your name") parser.add_argument("--greet", help="custom greeting", default="hello") args = parser.parse_args() print(f"{args.greet}, {args.name}!")
运行脚本:
$ python script.py alice hello, alice! $ python script.py alice --greet hi hi, alice!
类型检查和选择示例:
parser.add_argument("age", type=int, help="your age") parser.add_argument("--format", choices=["json", "xml"], help="output format")
运行脚本:
$ python script.py alice 30 --format json
click 是一个用于创建命令行界面的更高级的库。它提供了一种基于装饰器的方法来定义命令、子命令和选项。
import click @click.command() @click.option('--name', prompt='your name', help='the person to greet.') @click.option('--greet', default="hello", help='greeting to use.') def greet(name, greet): """simple program that greets name with a greet.""" click.echo(f'{greet}, {name}!') if __name__ == '__main__': greet()
运行脚本:
$ python greet.py --name alice --greet hi hi, alice!
您可以使用多个子命令创建更复杂的 cli 工具。
import click @click.group() def cli(): pass @cli.command() def start(): click.echo("starting the application...") @cli.command() def stop(): click.echo("stopping the application...") if __name__ == '__main__': cli()
运行脚本:
$ python app.py start starting the application... $ python app.py stop stopping the application...
无论您使用哪个库,错误处理对于提供流畅的用户体验都至关重要。
如果缺少必需的参数,argparse 将抛出错误并显示使用说明:
$ python script.py usage: script.py [-h] name script.py: error: the following arguments are required: name
在单击中,您可以使用装饰器引发自定义异常并优雅地处理错误。
@click.command() @click.option('--count', type=int, help='number of repetitions') def repeat(count): if count is none or count < 1: raise click.badparameter("count must be a positive integer.") click.echo('repeating...' * count)
要扩展 cli 功能,您可以将 argparse 或 click 与其他库(如操作系统、子进程,甚至自定义库)结合起来。
import os import argparse parser = argparse.argumentparser(description="file operations cli") parser.add_argument("filename", help="name of the file to check") parser.add_argument("--create", action="store_true", help="create the file if it does not exist") args = parser.parse_args() if os.path.exists(args.filename): print(f"{args.filename} already exists.") else: if args.create: with open(args.filename, 'w') as f: f.write("new file created.") print(f"{args.filename} created.") else: print(f"{args.filename} does not exist.")
运行脚本:
$ python filecli.py example.txt --create example.txt created.
要分发 cli 工具,您可以使用 setuptools 对其进行打包,并使其在任何系统上均可全局访问。
from setuptools import setup setup( name='greet-cli', version='0.1', py_modules=['greet'], install_requires=[ 'click', ], entry_points=''' [console_scripts] greet=greet:greet ''', )
$ pip install --editable .
现在,greet 命令在全球可用:
$ greet --name alice hello, alice!
要公开分发您的工具,请创建一个 pypi 帐户并按照以下步骤上传您的包:
python setup.py sdist bdist_wheel
twine upload dist/*
python 提供了一个用于构建命令行界面 (cli) 应用程序的优秀工具包。无论您使用内置的 argparse 模块还是功能更丰富的 click,您都可以创建功能强大、用户友好的工具,这些工具可以自动化工作流程、处理数据并提高生产力。
现在您已经了解了在 python 中使用 cli 的基础知识和高级功能,是时候将其付诸实践了。构建您自己的工具,分享它,甚至在全球范围内分发它!
如有问题或建议,请随时联系: