Python invoke.context.context因缺少位置参数而出现奇数错误

Python invoke.context.context因缺少位置参数而出现奇数错误,python,python-3.x,invoke,fabric,contextmanager,Python,Python 3.x,Invoke,Fabric,Contextmanager,我试图在上下文管理器中更改python程序中的目录。使用invoke.context.context似乎是正确的方法,从Fabric文档中获得,并且在os.chdir中使用常规的 然而,当我尝试做一些事情,比如 from invoke import Context with Context.cd("/etc"): subprocess.run(["ls"]) 我收到一个错误,上面写着: -------------------------------------------------

我试图在上下文管理器中更改python程序中的目录。使用
invoke.context.context
似乎是正确的方法,从Fabric文档中获得,并且在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'
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
---->1和Context.cd(“/etc”):
2子流程运行([“ls”])
3.
助手中的~/miniconda3/envs/python3/lib/python3.7/contextlib.py(*args,**kwds)
237@wrapps(func)
238 def辅助设备(*参数,**kwds):
-->239返回_GeneratorContextManager(func、args、kwds)
240返回助手
241
~/miniconda3/envs/python3/lib/python3.7/contextlib.py在u_init__中(self、func、args、kwds)
80
81定义初始化(self、func、args、kwds):
--->82 self.gen=func(*args,**kwds)
83 self.func,self.args,self.kwds=func,args,kwds
84#问题19330:确保上下文管理器实例具有良好的文档字符串
TypeError:cd()缺少1个必需的位置参数:“路径”
文档使这看起来是正确的(),但我有点迷路了


任何建议都是有用的。

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

它们还对上下文实例使用
run()
方法,而不是
subprocess.run()

试试这个:

from invoke import Context

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

啊,是的,就是这样。不幸的是,您只能在其中使用
c.run
,并且不能调用子进程或操作系统模块。