简体   繁体   English

python 中的 cmd 命令

[英]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.我需要检查一个目录是否已经在系统环境变量 PATH 中,如果没有则添加。 I run cmd commands in python to add a directory to the PATH (may not be the best practice but im desperate).我在 python 中运行 cmd 命令以将目录添加到 PATH(可能不是最佳实践,但我很绝望)。 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.是否直接运行setx PATH "%path%;C:\\Octave\\Octave-5.2.0.0\\mingw64\\bin到 cmd 工作,但是当在 Z23EEEB4347BDD276BFC6B7EE9A 中实施它时,任何帮助都会损坏。非常感激。

It is possible not only to read from os.environ['PATH'] but also assign to it.不仅可以从os.environ['PATH']读取,还可以分配给它。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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