gigglie 2024-07-10 00:37 采纳率: 0%
浏览 24

Python如何取得Windows当下用户的(不是系统的)环境变量?

Python如何取得Windows当下用户的(不是系统的)环境变量?
Windows 11的变量分为“用户变量”和“系统变量”两部分,os.environ只能取得"系统变量"(所有用户共享),怎么才能取得当下(或其他特定)用户的“用户变量”呢?
看下图比较清楚,提前谢过!

img

  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2024-07-10 00:37
    关注

    以下内容由CHATGPT及阿里嘎多学长共同生成、有用望采纳:


    在 Python 中获取 Windows 当前用户的用户变量,可以使用 ctypes 库来调用 Windows API 函数。以下是一个示例代码,展示了如何获取当前用户的用户变量:

    import ctypes
    from ctypes import wintypes
    
    def get_user_environment_variables():
        # 获取当前用户的用户名
        username = ctypes.c_buffer(1024)
        size = wintypes.DWORD(1024)
        if ctypes.windll.shell32.GetUserNameW(username, ctypes.byref(size)) == 0:
            raise Exception("Failed to get username")
    
        # 获取用户环境变量的句柄
        environment_block = ctypes.windll.kernel32.GetEnvironmentStringsW()
        if not environment_block:
            raise Exception("Failed to get environment strings")
    
        try:
            # 将环境变量字符串转换为字典
            environment_variables = {}
            while True:
                var = ctypes.wstring_at(environment_block)
                if not var:
                    break
                key, _, value = var.partition('=')
                environment_variables[key] = value
                environment_block += wintypes.DWORD(ctypes.sizeof(wintypes.wchar_t))
        finally:
            # 释放环境变量的内存
            ctypes.windll.kernel32.FreeEnvironmentStringsW(environment_block)
    
        return environment_variables
    
    # 打印当前用户的用户变量
    user_env_vars = get_user_environment_variables()
    print(user_env_vars)
    

    这段代码首先调用 GetUserNameW 函数获取当前用户的用户名,然后调用 GetEnvironmentStringsW 函数获取环境变量的字符串块。接着,它遍历这个字符串块,将每个环境变量解析为键值对,最后将它们存储在一个字典中。

    请注意,这段代码仅适用于 Windows 系统,并且需要 Python 3.5 或更高版本。

    至于获取特定用户的用户变量,这通常需要访问该用户的注册表项,因为用户变量在 Windows 注册表中也有相应的存储。但是,这涉及到更复杂的操作,并且可能需要管理员权限。如果你需要进一步的帮助,可以告诉我,我会尽力提供更多的信息。

    目前,我没有找到特定的参考链接来提供给你,因为这个问题通常需要特定的编程知识和对 Windows 系统内部的了解。如果你需要进一步的资源或教程,我可以帮你搜索相关的信息。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 7月10日