8

I want to append the path to exists environment variable PATH using python script.

I have tried to use os.environ['path'] = 'C:\foo\bin:%PATH%', but its deleting all the existing paths and creating 'C:\foo\bin:%PATH%' as new path value.

os.environ['path'] = 'C:\foo\bin:%PATH%'
4
  • 2
    Do you want your chances to be presistent when the script has finished running? Commented Sep 16, 2019 at 11:05
  • Is it a file or a folder? Commented Sep 16, 2019 at 11:10
  • @moeassal... I want to add multiple bin from different folders and some folders Commented Sep 16, 2019 at 11:18
  • @ I want those environment variables temperorly Commented Sep 16, 2019 at 11:18

3 Answers 3

8

You should be able to modify os.environ.

Since os.pathsep is the character to separate different paths, you should use this to append each new path:

os.environ["PATH"] += os.pathsep + path

or, if there are several paths to add in a list:

os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist)

As you mentioned, os.path.join can also be used for each individual path you have to append in the case you have to construct them from separate parts.

Sign up to request clarification or add additional context in comments.

Comments

5

You should be doing

  import os

  os.environ["PATH"] = "/your/path/"+ os.pathsep + os.environ["PATH"]

2 Comments

Is there any particular reason why you would want or even need to insert the new path at the front?
it is normally good to append it at the front so that in case there is another binary with the same name in os.environ["PATH"], the one in /your/path/ will take precedence. the lookup happens from left to right
0

In your code:

os.environ['path'] = 'C:\foo\bin:%PATH%

python does not know what to do with %PATH% in the string, but the old value of the PATH environment variable is accessible as os.environ['path'], so you can simply do:

os.environ['path'] = 'C:\foo\bin;' + os.environ['path']

Comments

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.