Reputation: 93
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%'
Upvotes: 8
Views: 7042
Reputation: 582
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.
Upvotes: 8
Reputation: 709
You should be doing
import os
os.environ["PATH"] = "/your/path/"+ os.pathsep + os.environ["PATH"]
Upvotes: 5
Reputation: 20482
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']
Upvotes: 0