Возможно, это не самое удачное решение, потому что оно фактически создает каталоги на вашем диске:
import contextlib
import os
from pathlib import Path
@contextlib.contextmanager
def working_directory_relative_to_script_location(path):
"""Changes working directory, and returns to previous on exit.
It's needed for PRAW for example,
because it looks for praw.ini in Path.cwd(),
but I have that file in the settings directory."""
prev_cwd = Path.cwd()
script_dir = Path(os.path.realpath(__file__)).parent
os.chdir(script_dir / path)
try:
yield
finally:
os.chdir(prev_cwd)
def test_decorator():
tmp = 'tmp_dir'
initial_path = Path.cwd()
os.mkdir(tmp)
tmp_path = os.path.join(initial_path, tmp)
@working_directory_relative_to_script_location(tmp_path)
def with_decorator():
return Path.cwd()
try:
assert with_decorator() == tmp_path
assert Path.cwd() == initial_path
except AssertionError as e:
raise e
finally:
os.rmdir(tmp)
test_decorator()
Здесь я создал функцию, которая возвращает текущий рабочий каталог, и украсил его вашим менеджером контекста.От менеджера контекста можно ожидать, что он изменяет каталог на tmp
во время вызова функции (это проверяется первым оператором assert
) и что впоследствии он возвращается в исходный каталог (это проверяетсявторое assert
утверждение).