![](/img/trans.png)
[英]PyTest: Auto delete temporary directory created with tmpdir_factory
[英]How to get the temporary path using pytest tmpdir.as_cwd
在 python 測試函數中
def test_something(tmpdir):
with tmpdir.as_cwd() as p:
print('here', p)
print(os.getcwd())
我期待p
和os.getcwd()
會給出相同的結果。 但實際上, p
指向測試文件的目錄,而os.getcwd()
指向預期的臨時文件。
這是預期的行為嗎?
看看py.path.as_cwd
的文檔:
返回上下文管理器,它在托管的“with”上下文期間更改為當前目錄。 在
__enter__
它返回舊目錄。
因此,您觀察到的行為是正確的:
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())
請記住,您的示例中的p
不是您要更改的“新”當前目錄,而是您更改的“舊”目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.