gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:20:40 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com