擅长:python、mysql、java
<p>查看<a href="https://py.readthedocs.io/en/latest/path.html#py._path.local.LocalPath.as_cwd" rel="nofollow noreferrer">^{<cd1>}</a>的文档:</p>
<blockquote>
<p>return context manager which changes to current dir during the managed "with" context. On <code>__enter__</code> it returns the old dir.</p>
</blockquote>
<p>因此,您所观察到的行为是正确的:</p>
<pre><code>def test_something(tmpdir):
print('current directory where you are before changing it:', os.getcwd())
# the current directory will be changed now
with tmpdir.as_cwd() as old_dir:
print('old directory where you were before:', old_dir)
print('current directory where you are now:', os.getcwd())
print('you now returned to the old current dir', os.getcwd())
</code></pre>
<p>请记住,您的示例中的<code>p</code>不是您要更改到的“新”当前目录,而是您从中更改的“旧”目录。在</p>