Based on the comments, I realized that pathlib
does not help change directories and, whenever possible, directory changes should be avoided.
Since I needed to call bash scripts outside of Python from the correct directory, I decided to use the context manager for a cleaner way of changing directories like this answer :
import os import contextlib from pathlib import Path @contextlib.contextmanager def working_directory(path): """Changes working directory and returns to previous on exit.""" prev_cwd = Path.cwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
A good alternative is to use the cwd
parameter of the subprocess.Popen
class, as in this one.
If you use Python <3.6 and path
, this is actually pathlib.Path
, you need str(path)
in the chdir
statements.
Lukas source share