1

As part of a project, I need to ensure that a few paths are included in the user's %PATH% variable, which I am going to do at the beginning of the script. What's the best way to do this from a python script?

My first thought was to just use something like the following:

subprocess.call('path = %PATH%;c:\path1;c:\path2;c:\path3')

To add each of the paths, as this is how you would do it from the Windows command line, though my fear is that after a reboot these settings would not carry over (this is what seems to happen when I run it from the command line regularly - in order for it to stick, I actually have to go in through the GUI and change it).

Anyone have a better idea, or will this work as I'd like it to? (Ideally, the user will only have to execute this portion of the script once, at which point the 'setup' will be complete and not need to be run again)

Thanks!

DJMcCarthy12
  • 3,819
  • 8
  • 28
  • 34
  • User environment variables from `HKCU\Environment` get merged with system environment variables from `HKLM\System\CurrentControlSet\Control\Session Manager\Environment`. Append to whichever `Path` value is appropriate for your context. The data type is `REG_EXPAND_SZ`. Read the docs: https://docs.python.org/2/library/_winreg.html. – Eryk Sun Mar 10 '15 at 08:28

1 Answers1

-1
path = os.environ.get('PATH')
subprocess.call('setx /M PATH "' + path + ';c:\path1;c:\path2;c:\path3"')

...or use _winreg. Example from another question here: How to add to and remove from system's environment variable "PATH"?

Community
  • 1
  • 1
fredrik
  • 9,631
  • 16
  • 72
  • 132
  • 1
    This will mess your User Path since "PATH" contains both (union of User and System Path ) + setx has limitation of 1024 characters. – Niko Föhr Apr 12 '20 at 18:18
  • Yes, and on the average modern windows device, PATH is almost always longer than 1024 – cowlinator Feb 11 '21 at 22:28