Other way is to simply do this
cwd = os.getcwd()
os.chdir('c:\some\directory')
subprocess.Popen('tool.exe')
os.chdir(cwd)
This solution works if you want to rely on relative paths, for example, if your tool's location is c:\some\directory\tool.exe
. cwd
keyword argument for Popen
will not let you do this. Some scripts/tools may rely on you being in the given directory while invoking them. To make this code less noisy, aka detach the logic related to changing directories from the "business logic", you can use a decorator.
def invoke_at(path: str):
def parameterized(func):
def wrapper(*args, **kwargs):
cwd = os.getcwd()
os.chdir(path)
try:
ret = func(*args, **kwargs)
finally:
os.chdir(cwd)
return ret
return wrapper
return parameterized
Such decorator can be then used in a way:
@invoke_at(r'c:\some\directory')
def start_the_tool():
subprocess.Popen('tool.exe')