Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the real user home directory using python?

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 try

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) 
like image 425
asdfg Avatar asked Apr 19 '10 15:04

asdfg


People also ask

How do I find my home directory?

To find your Home folder, open Finder and use the keyboard shortcut Command-Shift-H. You can use the Go pull-down menu from the menu bar to go to the Home folder. (Oddly, the home folder is called Home in this menu.)

How do I find out what directory a directory is in Python?

os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.


1 Answers

I think os.path.expanduser(path) could be helpful.

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.

So you could just do:

os.path.expanduser('~user') 
like image 191
Felix Kling Avatar answered Sep 18 '22 20:09

Felix Kling