我正在尝试在上下文管理器中更改我的 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/