pip install invoke
。c
或ctx
或context
。invoke --list
来查看所有任务,运行invoke xxx
来执行名为 xxx 的任务。命令行中的“invoke”可以简写成“inv”。# 文件名:tasks.py
from invoke import task
@task
def hello(c):
print("Hello world!")
@task
def greet(c, name):
c.run(f"echo {name}加油!")
from invoke import task
,@task 装饰器可以不带参数,也可以带参数(参见下一节),被它装饰了的函数就是一个任务。inv --list
或者inv -l
,可以看到所有任务的列表(按字母表顺序排序):>>> inv -l
Available tasks:
greet
hello
>>> inv hello
Hello world!
>>> inv greet 武汉
武汉加油!
>>> inv greet --name="武汉"
武汉加油!
@task(help={'name': 'A param for test'})
def greet(c, name):
"""
A test for shell command.
Second line.
"""
c.run(f"echo {name}加油!")
>>> inv -l
Available tasks:
greet A test for shell command.
>>> inv --help greet
Usage: inv[oke] [--core-opts] greet [--options] [other tasks here ...]
Docstring:
A test for shell command.
Second line.
Options:
-n STRING, --name=STRING A param for test
@task
def clean(c):
c.run("echo clean")
@task
def message(c):
c.run("echo message")
@task(pre=[clean], post=[message])
def build(c):
c.run("echo build")
>>> inv clean
clean
>>> inv message
message
>>> inv build
clean
build
message
@task(clean, message)
def test(c):
c.run("echo test")
>>> inv test
clean
message
test
# 文件名:tasks.py
from invoke import Collection, task
import task1
@task
def deploy(c):
c.run("echo deploy")
namespace = Collection(task1, deploy)
>>> inv -l
Available tasks:
deploy
task1.greet
task1.hello
>>> inv deploy
deploy
>>> inv task1.hello
Hello world!
>>> inv task1.greet 武汉
武汉加油!
stdout
和stderr
,并支持在stdin
中输入必要的信息。responses = {r"Are you ready? \[y/n\] ": "y\n"}
ctx.run("excitable-program", responses=responses)
argparse
、Flask 作者开源的click
与谷歌开源的fire
等等,而 invoke 也可以作为命令行工具库使用。pip install tester
安装,而此工具提供两个执行命令:tester unit
和tester intergration
。# tasks.py
from invoke import task
@task
def unit(c):
print("Running unit tests!")
@task
def integration(c):
print("Running integration tests!")
# main.py
from invoke import Collection, Program
from tester import tasks
program = Program(namespace=Collection.from_module(tasks), version='0.1.0')
# setup.py
setup(
name='tester',
version='0.1.0',
packages=['tester'],
install_requires=['invoke'],
entry_points={
'console_scripts': ['tester = tester.main:program.run']
}
)
$ tester --version
Tester 0.1.0
$ tester --help
Usage: tester [--core-opts] <subcommand> [--subcommand-opts] ...
Core options:
... core options here, minus task-related ones ...
Subcommands:
unit
integration
$ tester --list
No idea what '--list' is!
$ tester unit
Running unit tests!