python command line libraries
Invoke
https://docs.pyinvoke.org/en/stable/
The
invokeCLI toolDetails on the CLI interface to Invoke, available core flags, and tab completion options.
https://docs.pyinvoke.org/en/stable/getting-started.html#defining-and-running-task-functions
定义tasks.py
from invoke import task @task def build(c): print("Building!")
在同级目录下运行
$ invoke build Building!
argparse
https://docs.python.org/3/library/argparse.html
The
argparsemodule makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, andargparsewill figure out how to parse those out ofsys.argv. Theargparsemodule also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
定义prog文件
import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') args = parser.parse_args() print(args.accumulate(args.integers))
运行
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
options:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
Click
https://click.palletsprojects.com/en/8.0.x/
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box.
It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API.
Click in three points:
arbitrary nesting of commands
automatic help page generation
supports lazy loading of subcommands at runtime
定义文件
import click @click.command() @click.option('--count', default=1, help='Number of greetings.') @click.option('--name', prompt='Your name', help='The person to greet.') def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): click.echo(f"Hello {name}!") if __name__ == '__main__': hello()
运行
$ python hello.py --count=3 Your name: John Hello John! Hello John! Hello John!
Hug
https://www.hug.rest/
Embrace the APIs of the future
Drastically simplify API development over multiple interfaces. With hug, design and develop your API once, then expose it however your clients need to consume it. Be it locally, over HTTP, or through the command line - hug is the fastest and most modern way to create APIs on Python3.
支持cli的定义, 还支持本地和rest
"""An example of writing an API to scrape hacker news once, and then enabling usage everywhere""" import hug import requests @hug.local() @hug.cli() @hug.get() def top_post(section: hug.types.one_of(('news', 'newest', 'show'))='news'): """Returns the top post from the provided section""" content = requests.get('https://news.ycombinator.com/{0}'.format(section)).content text = content.decode('utf-8') return text.split('<tr class=\'athing\'>')[1].split("<a href")[1].split(">")[1].split("<")[0]
评价
https://realpython.com/comparing-python-command-line-parsing-libraries-argparse-docopt-click/#conclusion
Argparse 标准库, 代码风格, 没有特殊需求,使用这个。
Click声明模式, 简洁明了。
Invoke用于批量执行任务。
Argparse
Arparse is the standard library (included with Python) for creating command-line utilities. For that fact alone, it is arguably the most used of the tools examined here. Argparse is also very simple to use as lots of magic (implicit work that happens behind the scenes) is used to construct the interface. For example, both arguments and options are defined using the
add_argumentsmethod and argparse figures out which is which behind the scenes.Docopt
If you think writing documentation is great, docopt is for you! In addition docopt has implementations for many other languages - meaning you can learn one library and use it across many languages. The downside of docopt is that it is very structured in the way you have to define your command-line interface. (Some might say this is a good thing!)
Click
I’ve already said that I really like click and have been using it in production for over a year. I encourage you to read the very complete Why Click? documentation. In fact, that documentation is what inspired this blog post! The decorator style implementation of click is very simple to use and since you are decorating the function you want executed, it makes it very easy to read the code and figure out what is going to be executed. In addition, click supports advanced features like callbacks, command nesting, and more. Click is based on a fork of the now deprecated optparse library.
Invoke
Invoke surprised me in this comparison. I thought that a library designed for task execution might not be able to easily match full command-line libraries - but it did! That being said, I would not recommend using it for this type of work as you will certainly run into limitations for anything more complex than the example presented here.

浙公网安备 33010602011771号