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?

3
  • 1
    This question may help you (or make you sad) - stackoverflow.com/questions/1506010/… Commented Jun 26, 2013 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. Commented Jun 26, 2013 at 23:50
  • Windows has a setx 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 SO answer. Commented Jun 27, 2013 at 4:44

2 Answers 2

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.