Obtain user folder for any user in Linux (Ubuntu)

2

I've recently come across functionality that does not seem to be currently implemented in python.

Currently we can obtain the active user's folder in several ways (speaking of linux):

import os
os.environ("HOME")
os.path.expanduser("~/")

But what if our script has been called with sudo?

$sudo python my_script.py
import os
print(os.environ["HOME"]) => /root
print(os.path.expanduser("~/")) => /root/
print(os.geteuid()) => 0
print(os.getenv("HOME")) => /root
print(os.getenv("USER")) => root
print(os.getenv("SUDO_UID")) => 1000
print(os.getenv("SUDO_USER")) => dev

Before implementing my own function to obtain a user's folder, I would like to know if someone knows the most pythonic form or if someone has already implemented it.

    
asked by Aaron Giovannini 12.06.2017 в 17:38
source

1 answer

2

Using this library link I have found the solution, however with the above mentioned it could be. ...

import os
os.path.expanduser("~{0}".format(os.getenv("SUDO_USER")))

But with pathlib it can be made more pythonic and beautiful

from pathlib import Path
Path("~").expanduser().resolve()
Path.home().resolve()
Path("~{0}".format(os.getenv("SUDO_USER"))).resolve()
    
answered by 12.06.2017 / 18:54
source