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)
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:This worked both with and without
sudo
on Mac and Linux.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, ...home_folder = os.getenv('HOME')
This should work on Windows and Mac OS too, works well on Linux.