如何使用python找到真正的用户主目录? [英] How to find the real user home directory using python?
问题描述
我看到,如果我们更改HOME(linux)或USERPROFILE(Windows)环境变量并运行一个python脚本,那么当我尝试时,它返回新值作为用户的家,
os.environ ['HOME ']
os.exp
I see that if we change the HOME(linux) or USERPROFILE(windows) environmental variable and run a python script, it returns the new value as the user home when I tried, os.environ['HOME'] os.exp
有没有办法找到真正的用户主目录而不依赖于环境变量? Thanx。
编辑:
这是通过在注册表中阅读在Windows中找到userhome的方法, http://mail.python.org/pipermail/python-win32 /2008-January/006677.html
Is there any way to find the real user home directory without relying on the environmental variable?. Thanx.
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
编辑:
单程从win32com.shell导入shell,shellcon
home = shell.SHGetFolderPath(0)中找到Windows家庭使用pywin32,
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)
可能是有帮助的。
I think os.path.expanduser(path)
could be helpful.
在Unix和Windows上,返回参数,初始组件为
〜
或〜user
替换为该用户的主目录。
On Unix and Windows, return the argument with an initial component of
~
or~user
replaced by that user‘s home directory.
在Unix上,初始的〜
被复制如果设置了环境变量HOME;否则,通过内置模块 pwd
在密码目录中查找当前用户的主目录。 直接在密码目录中查找初始〜user
。
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.
在Windows上如果设置,将使用HOME和USERPROFILE,否则将使用HOMEPATH和HOMEDRIVE 的组合。 初始〜用户
是通过从创建的用户路径中删除最后一个目录组件来处理的。
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')
这篇关于如何使用python找到真正的用户主目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!