[Tutor] How to use subprocess module to get current logged in user?

Steven D'Aprano steve at pearwood.info
Fri Aug 25 21:33:38 EDT 2017


On Fri, Aug 25, 2017 at 07:13:12PM -0500, boB Stepp wrote:

> My objective:  Determine who the currently logged in user is

py> import os
py> os.getlogin()
'steve'


> and
> determine if that user is in my list of users that I have authorized
> to use my programs.

That's probably best handled at the OS level, by setting your programs 
to be executable only by members of a particular group. In Linux, the 
relevant commands are chmod and chgrp but I don't know what they are in 
Solaris.


> I tried in the interpreter:
> 
> =================================================================================================
> py2> cmd = ['who', '-m']
> py2> import subprocess as sp
> py2> p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
> py2> out, err = p.communicate()
> py2> out
> ''
> py2> err
> "Must be attached to terminal for 'am I' option\n"

Check the documentation for who on your system, e.g. man who, but my 
guess is that the -m or "am I" option requires you to be attached to a 
terminal. By launching a subprocess, you're no longer attached to one.

Under my Linux system, the above gives no output or error.

No, I don't understand it either :-)

But reading man who tells me that the -m option returns the user 
connected to stdin. Sure enough, this works:

py> p = sp.Popen(cmd, stdin=sys.stdin, stdout=sp.PIPE, stderr=sp.PIPE)
py> out, err = p.communicate()
py> out
'steve    pts/5        2017-08-25 15:52 (:0.0)\n'



-- 
Steve


More information about the Tutor mailing list