将参数传递到结构助教

2024-04-16 20:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

从命令行调用“fab”时,如何向fabric任务传递参数?例如:

def task(something=''):
    print "You said %s" % something
$ fab task "hello"
You said hello

Done.

是否可以在不使用fabric.operations.prompt提示的情况下执行此操作?


Tags: 命令行youhellotask参数def情况prompt
3条回答

结构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 docs中阅读更多关于它的信息。

在结构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

结构参数是通过非常基本的字符串解析来理解的,因此在发送它们时必须稍微小心一点。

下面是几种不同的方法向以下测试函数传递参数的示例:

@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'})

我在这里使用双引号将shell从等式中去掉,但是单引号对于某些平台可能更好。还要注意fabric考虑分隔符的字符的转义。

文档中的更多详细信息: http://docs.fabfile.org/en/1.14/usage/fab.html#per-task-arguments

相关问题 更多 >