0

I want to add a folder to the Windows PATH environment variable with Python. I tried these three code snippets but none worked:

os.environ['PATH'] += ";C:\my\folder"

and

sys.path.insert(0, os.path.abspath('C:\my\folder'))

and

if sys.platform == 'win32':
    sep = ';'
else:
    sep = ':'

os.environ['PATH'] += sep + r'"C:\my\folder"'
Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
SSH
  • 5
  • 4
  • [about revision 3] OP used the sys module in some of his attempts, but it doesn't make the question related to that module. – Gabriel Dec 05 '18 at 11:57
  • `"\f"` is a form-feed character. You need to use a raw string. `sys.path` has *absolutely nothing* to do with the system `PATH` environment variable. The path separator is `os.pathsep`; do no hard code it in your script. Never use double quotes in `PATH`; CMD can handle quotes, but almost everything else uses `SearchPath`, which treats the quotes as literal characters. – Eryk Sun Dec 05 '18 at 17:51
  • This already has answers at [How to add to and remove from system's environment variable “PATH”?](https://stackoverflow.com/questions/21138014/how-to-add-to-and-remove-from-systems-environment-variable-path) and [Change %PATH% from Python Script (Windows)](https://stackoverflow.com/questions/28951885/change-path-from-python-script-windows) – Niko Föhr Apr 12 '20 at 18:30

2 Answers2

0

The Windows command for permanently changing the path is

setx /M path "%path%;C:\my\folder"

You can execute arbitrary shell commands via Python with os.system

import os
os.system('setx /M path "%path%;C:\my\folder"')

Note:

You need to run this with elevated privileges.

References:

Gabriel
  • 1,922
  • 2
  • 19
  • 37
  • Thank You! how to require it to run as administrator – SSH Dec 05 '18 at 11:54
  • 1
    Never use setx.exe to change `PATH`. It's wrong in at least two seriously bad ways. (1) It hard codes the current value of named variables such as `%UserProfile%`. (2) `PATH` consists of a system value and a per-user value that get concatenated at load time, and using setx.exe with the already concatenated value sets the per-user component in the system component, which will increasingly make a mess of `PATH` every time you do this. – Eryk Sun Dec 05 '18 at 17:44
  • so how to add to PATH? – SSH Dec 10 '18 at 13:17
0

You should use:

os.environ['PATH'] += R";C:\my\folder"

G. Cohen
  • 604
  • 5
  • 4