简体   繁体   中英

cmd command in python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM