0

In my python program I need to set a shell variable. Ive tried using both subprocess.Popen and subprocess.run. However, even when no errors are returned the shell variable doesn't change. here is my code:

subprocess.run(["set", "JWD=", variablename], shell=True)
  • 3
    This spawns a *new* shell, sets a variable, and *then the shell exits*. It doesn't change things in an existing shell session. – larsks Jul 13 '22 at 17:52
  • To create or modify environment variables in the user or system environment, use the `cmd` shell's `setx` command. – martineau Jul 13 '22 at 18:31

1 Answers1

-1

You're looking for os.environ, which is a dictionary-like object representing the environment variables available to your program.

import os

os.environ['JWD'] = variablename

But, as noted in the comments, if your expectation is that this affect the shell that's running the Python code, it still won't work. Your Python program is a separate process and gets its own environment variables (which may be inherited from the shell but will not modify them back upstream). See this answer to a similar question for a more detailed explanation, but the summary is: If you want to mess with the shell's state, write a shell script, not a Python script.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • ...caveat that Windows _does_ have the concept of a global environment (both systemwide and per-user), so while this answer and the linked one are 100% correct for UNIX, they're... maybe somewhat less than 100% for Windows. (I don't know that changes to the global environment are immediately reflected in already-running processes even on Windows, though, so what the OP wants still may not be possible). – Charles Duffy Jul 13 '22 at 18:07
  • @CharlesDuffy *AFAIK* There is no way in windows to set "global" environment variables with os.environ or subprocess.run and allike - Global environment variables in windows are either set via registry or via ui from control panel (which will set them to registry) and then those env variables will be active for *new* shells after the process has been done.. – rasjani Jul 13 '22 at 18:19
  • Right, but you can absolutely set registry entries from the command line, or the `win32api` Python library, etc. And I wouldn't be all that surprised if Windows had a way to update your already-running shell's environment variables _from_ the registry, even if it required the shell to take an affirmative step. – Charles Duffy Jul 13 '22 at 18:23