将参数传递给Fabric任务

Don*_*van 122 python fabric

从命令行调用"fab"时,如何将参数传递给结构任务?例如:

def task(something=''):
    print "You said %s" % something
Run Code Online (Sandbox Code Playgroud)
$ fab task "hello"
You said hello

Done.
Run Code Online (Sandbox Code Playgroud)

是否可以在没有提示的情况下执行此操作fabric.operations.prompt

Jak*_*cil 205

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
Run Code Online (Sandbox Code Playgroud)

您可以在Fabric文档中阅读有关它的更多信息.

  • 报价不是必要的; 所有参数都是字符串:"由于此过程涉及字符串解析,因此所有值都将以Python字符串形式结束,因此请相应地进行规划.(我们希望在未来的Fabric版本中对此进行改进,前提是可以找到直观的语法.)" (9认同)
  • 由于该过程涉及字符串解析,因此fabric命令中的`bar = True`将传递为`bar ='True',这不是布尔值 (5认同)
  • 看来,"你好世界"的引用似乎是必要的吗? (4认同)
  • @PEZ如果这是真的,那么在该示例中可能需要引号,因为终端或结构的命令行解析器会看到空间并认为这是该任务的所有内容的结束,并且"world"是一项新任务. (2认同)

mrt*_*rts 12

在 Fabric 2 中,只需将参数添加到任务函数即可。例如,将version参数传递给 task deploy

@task
def deploy(context, version):
    ...
Run Code Online (Sandbox Code Playgroud)

运行如下:

fab -H host deploy --version v1.2.3
Run Code Online (Sandbox Code Playgroud)

Fabric 甚至会自动记录选项:

$ fab --help deploy
Usage: fab [--core-opts] deploy [--options] [other tasks here ...]

Docstring:
  none

Options:
  -v STRING, --version=STRING
Run Code Online (Sandbox Code Playgroud)


Bog*_*tsa 6

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

以下是将参数传递给以下测试函数的几种不同方式的示例:

@task
def test(*args, **kwargs):
    print("args:", args)
    print("named args:", kwargs)
Run Code Online (Sandbox Code Playgroud)
$ 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'})
Run Code Online (Sandbox Code Playgroud)

我在这里使用双引号将外壳排除在等式之外,但对于某些平台,单引号可能更好。还请注意Fabric视为定界符的字符的转义符。

docs中有更多详细信息:http : //docs.fabfile.org/zh/1.14/usage/fab.html#per-task-arguments