I recently published my first ever Python module to PyPi – macusers. It simplifies getting the current logged in user even when the script is running as root or at login window. I’ve been using the code for a long time now in my Munki scripts and custom packages.
I’ve been annoyed at having to constantly drop in the template code each time that I need to use it making my scripts much longer than they need to be (especially if it’s going to be a pkginfo script.) So, I made it into an installable Python module.
The syntax is simple:
>>> import macusers >>> macusers.console() 'bryanheinz'
This code works when the Manage Software Center is installing including while installing at the login window. It uses
stat to get the current console user which I’ve only seen fail when MSC is installing at the login window. When this happens, it falls back to reading
. This combo has worked really well for me.
When to use
When should you use this module? I use it any time a Python script might run as root, but need to get the currently logged in console user. As stated above, typically this is during a Managed Software Center install, although I’ve used it in a few other places as well.
Why this module over other methods?
Great question, I’m glad that you asked. If you’re deploying and using the PyObjC method and you’re happy with it, then don’t!
Anecdotally I’ve noticed importing PyObjC modules tend to be a little slow (~0.5 seconds slower at getting the console user according to
time.) Slower enough to matter? No, not really, but for some reason I care.
If you’re using a Python 3 framework without PyObjC already installed, then this gives you a small and quick module to install instead of having to install PyObjC or dropping in the template code.
Cool, any other tricks?
One other thing that this module can do is return a list of local users. This was a last minute add and needs more testing. I’d like to expand it to network users eventually as well.
It’s syntax is also simple:
>>> import macusers >>> macusers.users() ['root', 'bryanheinz', 'natalieheinz']
Cool cool cool, but how do you install it? Since it’s in PyPi you can use pip to install it!
python3 -m pip install macusers
I hope that someone besides myself finds this module useful. If you run into any issues with this module please open an issue here.