Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python脚本更改环境变量_Python_Windows_Python 3.x_Windows 7 X64_Python 3.4 - Fatal编程技术网

从Python脚本更改环境变量

从Python脚本更改环境变量,python,windows,python-3.x,windows-7-x64,python-3.4,Python,Windows,Python 3.x,Windows 7 X64,Python 3.4,我编写的脚本检查路径中的目录并删除无法访问的目录。我还使用snippet作为管理员运行脚本。但当我在脚本执行后检查路径时,一切都是一样的 import os import sys import win32com.shell.shell as shell if __name__ == "__main__": if os.name != 'nt': raise RuntimeError("This script is implemented only for Window

我编写的脚本检查路径中的目录并删除无法访问的目录。我还使用snippet作为管理员运行脚本。但当我在脚本执行后检查路径时,一切都是一样的

import os
import sys
import win32com.shell.shell as shell

if __name__ == "__main__":

    if os.name != 'nt':
        raise RuntimeError("This script is implemented only for Windows")

    ASADMIN = 'asadmin'

    if sys.argv[-1] != ASADMIN:
        script = os.path.abspath(sys.argv[0])
        params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
        shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
        print("I am root now")

    paths = os.environ.get('Path').split(';')
    accessible_paths = []
    for path in paths:
        if os.access(path, os.R_OK):
            accessible_paths.append(path)

    new_path = ';'.join(accessible_paths)
    os.environ['Path'] = new_path

    print(new_path)
    print(new_path == os.environ['Path'])
那么,如何通过Python脚本实际更改环境变量呢?

根据,以调用
os.putenv()
的方式设置环境变量,但此函数的描述不清楚。事实上,据说:

对环境的此类更改会影响从os.system()、popen()或fork()和execv()启动的子进程


所以我不确定
os.environ
的设计是否符合您的期望。这在某种程度上得到了确认,其中答案仅表示子进程将受到此更改的影响…

初始系统环境变量由会话管理器(smss.exe)从注册表项
HKLM\system\CurrentControlSet\Control\session manager\environment
加载。winlogon.exe还合并从用户的
HKCU\Environment
键加载的每个用户
路径。