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\\bindirectly to the cmd works but when implement it in python, PATH corrupts. Did i miss something? Any help will be greatly appreciated.
os.systemalready executes viacmd /c, andsetxis not an internal CMD command anyway. It's setx.exe, and how you're using it to modifyPATHis wrong and corrupts the per-user "Path" value in the registry with the expanded and concatenated system + userPATHvalue. You need to use the winreg module to modify the user's unexpanded "Path" value in "HKCU\Environment".setx PATH "%path%;C:\\Octave\\Octave-5.2.0.0\\mingw64\\bindirectly in command prompt does the trick but doing it inside python truncates my path to 1024 characterspathto other variables. Just add the path you want. If its not in the path it will be added to the path else if it is in the path nothing will happen.PATH. It makes a mess to store the concatenated and expanded system+user value ofPATHinto either the system or user value. The way to use setx.exe to modifyPATHis in combination with reg.exe, and in that case setx.exe is only used instead of just using reg.exe because it broadcasts theWM_SETTINGCHANGEmessage that causes Explorer to reload its environment. But in Python there's no need for that when we can more idomatically use winreg and broadcast the window message via ctypes or PyWin32.