如何使用Python找到真实的用户主目录?

2024-05-16 06:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我看到,如果我们更改HOME(linux)或USERPROFILE(windows)环境变量并运行python脚本,当我尝试时,它会将新值作为userhome返回, 操作系统环境['HOME'] 操作经验

有没有什么方法可以在不依赖环境变量的情况下找到真正的用户主目录?

编辑:
下面是一种通过在注册表中读取来在windows中查找userhome的方法,
http://mail.python.org/pipermail/python-win32/2008-January/006677.html

编辑:
使用pywin32查找windows主页的一种方法

from win32com.shell import shell,shellcon
home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)

Tags: 方法脚本编辑home环境linuxwindows环境变量
3条回答
from pathlib import *

str(Path.home())

适用于Python3.5及更高版本。Path.home()返回一个提供APIPath对象,我发现它非常有用。

我认为^{}可能会有帮助。

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user‘s home directory.

On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

所以你可以:

os.path.expanduser('~user')

我认为os.path.expanduser(path)是您问题的最佳答案,但是在Unix世界中有一个替代方案值得一提:这个^{}包。e、 g

import os, pwd

pwd.getpwuid(os.getuid()).pw_dir

相关问题 更多 >