将数据保存在Python的调用库(pyinvoke)中的上下文变量中

时间:2016-08-12 11:05:00

标签: python pyinvoke

使用Invoke library for Python,我想首先运行一个设置任务,在context variable中保存一些值,以便以下所有任务都可以读取和使用。

The documentation is quite short on that topic但是,它说明了

  

跑步者面临的常见问题是传输或存储   当前会话的“全局”值 - 从中​​加载的值   配置文件(或其他配置向量),CLI标志,   由“设置”任务设置的值

     

(我强调)

,所以实际上应该可以。

然而,当我写这篇文章时,

from invoke import task

@task
def set_context(context):
    context.foo = 'bar'

@task
def read_context(context):
    print(context.foo)

并通过invoke read_context set_context从命令行运行该文件,然后我得到

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/invoke/config.py", line 69, in __getattr__
    return self._get(key)
  File "/usr/local/lib/python3.4/dist-packages/invoke/config.py", line 113, in _get
    value = self.config[key]
  File "/usr/local/lib/python3.4/dist-packages/invoke/config.py", line 110, in __getitem__
    return self._get(key)
  File "/usr/local/lib/python3.4/dist-packages/invoke/config.py", line 113, in _get
    value = self.config[key]
KeyError: 'foo'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/invoke", line 11, in <module>
    sys.exit(program.run())
  File "/usr/local/lib/python3.4/dist-packages/invoke/program.py", line 270, in run
    self.execute()
  File "/usr/local/lib/python3.4/dist-packages/invoke/program.py", line 381, in execute
    executor.execute(*self.tasks)
  File "/usr/local/lib/python3.4/dist-packages/invoke/executor.py", line 113, in execute
    result = call.task(*args, **call.kwargs)
  File "/usr/local/lib/python3.4/dist-packages/invoke/tasks.py", line 111, in __call__
    result = self.body(*args, **kwargs)
  File "/home/jenkins/workspace/Deploy_Birmingham_URL_Service_on_Docker_host/deployment/tasks.py", line 14, in read_context
    print(context.foo)
  File "/usr/local/lib/python3.4/dist-packages/invoke/config.py", line 81, in __getattr__
    raise AttributeError(err)
AttributeError: No attribute or config key found for 'foo'

Valid keys: ['run', 'tasks']

Valid real attributes: ['from_data', 'run']

invoke在上下文变量中保存某些内容并在其他任务中重用它的正确方法是什么?我正在使用Python 3.5.2并调用0.13.0,如果这很重要的话。

未来用户请注意:0.15修复此问题(github bug link)

1 个答案:

答案 0 :(得分:1)

使用ctx.update

from invoke import task

@task
def set_context(context):
    context.update({'foo': 'bar'})

@task
def read_context(context):
    print(context.foo) # => 'bar'