2

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

That works perfectly, so am I correct that sys.append.path only does the PYTHONPATH itself?
@Pyth0nicPenguin First of all it is sys.path(.append) and yes only PYTHONPATH.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.