How to find the real user home directory using pyt

2019-01-05 02:27发布

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

Is there any way to find the real user home directory without relying on the environmental variable?

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)

9条回答
Bombasti
2楼-- · 2019-01-05 03:13

I realize that this is an old question that has been answered but I thought I would add my two cents. The accepted answer was not working for me. I needed to find the user directory and I wanted it to work with and without sudo. In Linux, my user directory is "/home/someuser" but my root directory is "/root/". However, on my Mac, the user directory is "/Users/someuser". Here is what I ended up doing:

_USERNAME = os.getenv("SUDO_USER") or os.getenv("USER") 
_HOME = os.path.expanduser('~'+_USERNAME)

This worked both with and without sudo on Mac and Linux.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-05 03:14

On Linux and other UNIXoids you can always take a peek in /etc/passwd. The home directory is the sixth colon-separated field in there. No idea on how to do better than the environment variable on Windows though. There'll be a system call for it, but if it's available from Python, ...

查看更多
成全新的幸福
4楼-- · 2019-01-05 03:16

home_folder = os.getenv('HOME')

This should work on Windows and Mac OS too, works well on Linux.

查看更多
登录 后发表回答