In python how can I programmatically append to my system path? I'm aware of sys.path.append and just searched the docs, I'm a little confused though. It tells me that sys.path.append only appends to the PYTHONPATH and not the actual system path. Is there a way I can programmatically append to the system path temporarily?
Add a comment
|
1 Answer
Just update the environment PATH variable:
old_path = os.environ['PATH']
try:
os.environ['PATH'] = "{}{}{}".format('/my/new/path', os.pathsep, old_path)
finally:
os.environ['PATH'] = old_path
Alternately, its common for programs to keep a separate environment they use when calling other tools.
env = os.environ.copy()
env['PATH'] = "{}{}{}".format('/my/new/path', os.pathsep, env['PATH'])
# change other env here...
subprocess.check_call(['my', 'tool'], env=env)
3 Comments
Pyth0nicPenguin
That works perfectly, so am I correct that
sys.append.path only does the PYTHONPATH itself?tdelaney
@Pyth0nicPenguin - Not quite.
sys.path.append appends to the module lookup path for the running program only. If it executes other programs, they will only see the PYTHONPATH from the original environment. - And I mean execute as a child process, not import. If you execute other python scripts and want them to see a different path, you need to play the same os.environ game with PYTHONPATH.