While logged in as "standard" pi user, I am expecting the path to the user directory to be /home/pi – which is the case when I open File Manager, for example. However, when I run this script I get /root instead of the expected /home/pi:

import os

homedir = os.path.expanduser("~")
print (homedir)

Is my assumption wrong ?
What (else) should I use to get the pi user directory ?

Edit: I found the answer by myself: this happens because I am running the Python script prefixed with sudo. Sorry for confusion.

  • 1
    Are you sure you are not running the script as root? You have probaly started the script or its environment with sudo. The script shows my home directory if I start it without sudo. It shows /root if I start it with sudo. – joan Aug 8 '15 at 22:32
  • Yes, I realized that minutes after. Wrong doing on my part, sorry. And thank you for pointing this also :) – secarica Aug 8 '15 at 22:40
  • 2
    If you've figured the answer to your question, please submit it as an answer. – Jacobm001 Aug 8 '15 at 22:56

By running the script prefixed with sudo the script is running as super user, whose home directory is /root.

In order to get the current user home directory (/home/pi in this case) the script should be run directly, i.e. as pi user but not prefixed with sudo.

| improve this answer | |
  • You can configure sudo to preserve the HOME environment variable which would allow the other behavior. – hildred Aug 10 '15 at 0:35
  • That means changing the behavior of the system ? (for that user) If yes (?), then no, I prefer this to remain an application-specific approach. For this purpose I used sudo_username = os.getenv("SUDO_USER") home_dir = "/home/" + sudo_username which is mentioned here – secarica Aug 10 '15 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.