views:

255

answers:

3

Is there a way to modify the PATH environment variable in a platform independent way using python?

Something similar to os.path.join()?

+10  A: 

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.

RedGlyph
What with PATH environment separators ? ?linux - /usr/bin:/lib: ":"windows - C:\asdf\;C:\Prog...; ";"
bua
@bua: do you mean the `os.pathsep` I mentioned (specific to PATH)?
RedGlyph
Thanks, thats what I was looking for.
resi
@RedGlyph Yes, sorry I thought that os.pathsep is "/" and "\".I didn't check that before claiming ;).
bua
@bua: It's almost a "gotcha" that `os.path.sep != os.pathsep`.
krawyoti
@krawyoti, bua: Ah, now I see... well spotted! It's an easy mistake indeed :-)
RedGlyph
+3  A: 

The caveat to be aware of with modifying environment variables in Python, is that there is no equivalent of the "export" shell command. There is no way of injecting changes into the current process, only child processes.

Matt T
+1: Wise to point that out, commands like `os.system`, `os.popen` or `subprocess.Popen` should then be used from the Python application to launch other processes. Otherwise it's pretty much pointless.
RedGlyph
This is not true.
Glyph
A: 

(Since comments can't contain formatting, I have to put this in an answer, but I feel like it's an important point to make. This is really a comment on the comment about there being no equivalent to 'export'.)

Please note that os.environ is not actually a dictionary. It's a special dictionary-like object which actually sets environment variables in the current process using setenv.

>>> os.environ.__class__
<class os._Environ at 0x100472050>
>>> import os
>>> os.environ["HELLO"] = "WORLD"
>>> os.getenv("HELLO")
'WORLD'

This means that PATH (and other environment variables) will be visible to C code run in the same process.

Glyph