I'm running a python script as a daemon and want to query window information using xprop
. This seems to only be possible if I run xprop
as the same user as is logged in and started X locally. I've tried running the daemon as my user and it works, but it'd be more robust and work for other users if I could just run xprop
as which ever user is currently logged in.
How do I get the name of the currently logged in user?
EDIT: I can't just read $USER
or getpass.getuser()
because the script may be running as root. I need the username of the guy who's running X
.
I'm not sure if this means looking for the user owning display :0
as below (is it always :0
?). What's the best way?
> who
myusername :0 2015-03-13 19:52
myusername pts/0 2015-03-13 19:53
Perhaps something along the lines of:
ps -o user -p `pgrep -n '^(startkde|gnome-session)'` | tail -1
although clearly this depends on the window manager.
The answer here suggesting os.getlogin()
seems promising but doesn't work because it "returns the name of the user logged in on the controlling terminal of the process" and thus fails with OSError: [Errno 25] Inappropriate ioctl for device
from my daemon.