将参数传递给fabric任务
我该如何在命令行中调用“fab”时,给一个fabric任务传递参数呢?比如说:
def task(something=''):
print "You said %s" % something
$ fab task "hello"
You said hello
Done.
有没有办法在不使用fabric.operations.prompt
提示的情况下做到这一点?
5 个回答
7
Fabric 1.x 的参数处理方式很简单,主要是通过基本的字符串解析来理解,所以在发送参数时需要稍微小心一些。
下面是几种不同的方式来传递参数给以下的测试函数:
@task
def test(*args, **kwargs):
print("args:", args)
print("named args:", kwargs)
$ fab "test:hello world"
('args:', ('hello world',))
('named args:', {})
$ fab "test:hello,world"
('args:', ('hello', 'world'))
('named args:', {})
$ fab "test:message=hello world"
('args:', ())
('named args:', {'message': 'hello world'})
$ fab "test:message=message \= hello\, world"
('args:', ())
('named args:', {'message': 'message = hello, world'})
我在这里使用双引号是为了避免与命令行的干扰,但在某些平台上,单引号可能会更好。此外,还要注意对于 Fabric 来说,某些字符是分隔符,需要进行转义处理。
更多详细信息可以查看文档: http://docs.fabfile.org/en/1.14/usage/fab.html#per-task-arguments
14
在Fabric 2中,只需要在你的任务函数中添加参数。例如,要把version
这个参数传给任务deploy
:
@task
def deploy(context, version):
...
可以这样运行:
fab -H host deploy --version v1.2.3
Fabric甚至会自动记录这些选项:
$ fab --help deploy
Usage: fab [--core-opts] deploy [--options] [other tasks here ...]
Docstring:
none
Options:
-v STRING, --version=STRING
218
Fabric 2 任务参数的文档:
http://docs.pyinvoke.org/en/latest/concepts/invoking-tasks.html#task-command-line-arguments
Fabric 1.X 版本使用以下语法来传递参数给任务:
fab task:'hello world'
fab task:something='hello'
fab task:foo=99,bar=True
fab task:foo,bar
你可以在 Fabric 文档 中了解更多信息。