python - invoke.context.Context 因缺少位置参数而出现奇怪的错误

标签 python python-3.x invoke fabric contextmanager

我正在尝试在上下文管理器中更改我的 python 程序中的目录。使用 invoke.context.Context 似乎是正确的方法,从 Fabric 文档中获取并且使用常规 with os.chdir 将不起作用。

但是,当我尝试做诸如

之类的事情时
from invoke import Context

with Context.cd("/etc"):
    subprocess.run(["ls"])

我收到一条错误信息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-40b28af3213a> in <module>
----> 1 with Context.cd("/etc"):
      2     subprocess.run(["ls"])
      3

~/miniconda3/envs/python3/lib/python3.7/contextlib.py in helper(*args, **kwds)
    237     @wraps(func)
    238     def helper(*args, **kwds):
--> 239         return _GeneratorContextManager(func, args, kwds)
    240     return helper
    241

~/miniconda3/envs/python3/lib/python3.7/contextlib.py in __init__(self, func, args, kwds)
     80
     81     def __init__(self, func, args, kwds):
---> 82         self.gen = func(*args, **kwds)
     83         self.func, self.args, self.kwds = func, args, kwds
     84         # Issue 19330: ensure context manager instances have good docstrings

TypeError: cd() missing 1 required positional argument: 'path'

文档使这看起来是正确的(http://docs.pyinvoke.org/en/latest/api/context.html#invoke.context.Context),但我有点迷路。

任何建议都是有帮助的。

最佳答案

查看文档,您似乎应该创建自己的 Context 实例,而不是直接使用 Context 类。

他们还在 Context 实例上使用 run() 方法而不是 subprocess.run()

试试这个:

from invoke import Context

c = Context()
with c.cd("/etc"):
    c.run("ls")

关于python - invoke.context.Context 因缺少位置参数而出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56049097/

相关文章:

python - 在另一个函数中导​​入一个函数

python - mysql 和 sqlalchemy with_lockmode ('update' ) 它是如何工作的?

尝试将 AsyncCallback 添加到 BeginInvoke() 时 C# 参数计数不匹配

python - 如何通过将最后一列分配为元组的第二个值来读取csv文件?

groovy - 如何在 Groovy 中动态调用方法?

python - 如何在一行中读取由空格分隔的两个输入?

python - 如何从工作线程导入 Python 异步模块?

python - 如何使用 ScrolledText 小部件为文本添加多色?

python-3.x - 拟合顺序模型后缺少 val_acc