1

I'm trying to add an environment variable to my windows machine using python and the code is something like:

import os
os.environ["TONY"] = "C:\\"

or

import os
os.putenv["TONY", "C:\\"]

But I dont see the entry in the system environment variables. Is the because the list of variables when you type 'set' in cmd is read from the machines registry?

Is there a way to add a variable on windows so it shows up in system variables?

martineau
  • 119,623
  • 25
  • 170
  • 301
lia1000
  • 159
  • 1
  • 4
  • 13
  • 1
    This question may help you (or make you sad) - http://stackoverflow.com/questions/1506010/how-to-use-export-with-python-on-linux – NG. Jun 26 '13 at 23:04
  • Answer this question please: Do you want to change an env var for your python process and its children, or for all new processes on the system? The former is easy, the latter is OS-specific. – dstromberg Jun 26 '13 at 23:50
  • Windows has a [setx](http://ss64.com/nt/setx.html) command line utility which is available as part of the OS or in optional Resource Kits (depending on the version in question) that can do what you want. It's also possible to do something similar by modifying parts of its registry, see [this](http://stackoverflow.com/questions/573817/where-are-environment-variables-stored-in-registry) SO answer. – martineau Jun 27 '13 at 04:44

2 Answers2

0

Short answer: Python cannot edit environment variables in a way that sticks. BUT, if all you want to do is run something in a temporarily modified environment, you can do that with the subprocess module:

import os
from subprocess import Popen

myEnv = dict(os.environ)
myEnv['newKey'] = 'newVal'
shellCmd = Popen(['sh', 'someScript.sh'], env=myEnv)
(shellOut, shellErr) = shellCmd.communicate()
Will
  • 380
  • 4
  • 14
0

If you're getting an error because the program you're running is not defined in the Windows Environment path and you don't want to ask the user to do that manually then a workaround is to specify the full location of the exe file such as in this example in the picture

enter image description here

Chadee Fouad
  • 2,630
  • 2
  • 23
  • 29