我看到,如果我们更改HOME(linux)或USERPROFILE(windows)环境变量并运行python脚本,当我try 时,它会以用户主页的形式返回新值

os.environ['HOME']
os.exp

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

edit:
Here is a way to find userhome in windows by reading in the registry,
http://mail.python.org/pipermail/python-win32/2008-January/006677.html

edit:
One way to find windows home using pywin32,

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

推荐答案

我想os.path.expanduser(path)美元可能会有帮助.

在Unix和Windows上,返回参数时,初始组件为~~user,替换为该用户的主目录.

在Unix上,如果设置了初始值~,则它将被环境变量HOME替换;否则,通过内置模块pwd在密码目录中查找当前用户的主目录.An initial 102 is looked up directly in the password directory

在Windows上,如果设置了HOME和USERPROFILE,则将使用HOME和USERPROFILE,否则将使用combination of HOMEPATH and HOMEDRIVE.An initial 100 is handled by stripping the last directory component from the created user path derived above

如果扩展失败或路径不是以波浪号开头,则返回的路径将保持不变.

所以你可以这样做:

os.path.expanduser('~user')

Linux相关问答推荐

如何注释掉SLURM中的延迟调度命令?

为什么我在退出SD-Bus容器时出现错误?

在 bash 中使用 tee 时如何返回错误代码

"‘operator<<’匹配失败(可能是因为我的C++/GCC版本问题)"

Perl/cpan: 找不到 JSON/Parse.pm @INC

如何使 awk 输出更具可读性?

为什么当凭证助手设置为存储 SSH 远程存储库时 git pull 不使用 .git-credentials

ln命令报错target not a directory

linux shell 脚本获取文件夹中

如何将通配符参数传递给 bash 文件

BASEDIR 环境变量未正确定义

如何使用 AWK 合并两个文件?

何时判断 EINTR 并重复函数调用?

如何下载较旧的 google play 服务?

用于数据库备份的 Linux shell 脚本

Linux 配置/制作,--prefix?

在 Linux 上用 C 语言读写串口

错误:ld.so:无法预加载对象 LD_PRELOAD:忽略

GNU Octave 方法对矩阵中的每个项目进行操作.octave arrayfun(...)示例

比较文件的日期 bash