Reputation: 113
I need to check if a directory is already in the system environment variables PATH and add if it is not. I run cmd commands in python to add a directory to the PATH (may not be the best practice but im desperate). Here is the code:
import os
new_list = os.environ['PATH'].split(";")
try:
search = new_list.index('C:\\Octave\\Octave-5.2.0.0\\mingw64\\bin2')
except ValueError:
print('directory not found')
command_cmd = 'setx PATH "%path%;C:\\Octave\\Octave-5.2.0.0\\mingw64\\bin"'
os.system('cmd /c ' + command_cmd)
Running setx PATH "%path%;C:\\Octave\\Octave-5.2.0.0\\mingw64\\bin
directly to the cmd works but when implement it in python, PATH corrupts. Did i miss something? Any help will be greatly appreciated.
Upvotes: 0
Views: 88
Reputation: 36735
It is possible not only to read from os.environ['PATH']
but also assign to it. Please try following code:
import os
new_list = os.environ['PATH'].split(";")
new_path = 'C:\\Octave\\Octave-5.2.0.0\\mingw64\\bin2'
if new_path not in new_list:
os.environ['PATH'] = os.environ['PATH'] + ';' + new_path
Upvotes: 1