SUGGEST: os.getuser()
Michael P. Reilly
arcege at shore.net
Wed Jan 19 11:24:09 EST 2000
Gerrit Holl <gerrit.holl at pobox.com> wrote:
: Fredrik Lundh wrote on 948044608:
:> Gerrit Holl wrote:
:> > may I suggest this function for in the posix module:
:> >
:> > def getuser():
:> > import pwd
:> > return pwd.getpwuid(getuid())[0]
:>
:> you'll find a more complete implementation of that
:> function in the getpass module:
: The code of that getuser() is:
: def getuser():
: """Get the username from the environment or password database.
: First try various environment variables, then the password
: database. This works on Windows as long as USERNAME is set.
: """
: import os
: for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
: user = os.environ.get(name)
: if user:
: return user
: # If this fails, the exception will "explain" why
: import pwd
: return pwd.getpwuid(os.getuid())[0]
: So the user can mislead the program. I think the other way would be better:
: ...
: try:
: import pwd
: return pwd.getpwuid(os.getuid())[0]
: except ImportError:
: import os
: for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
: user = os.environ.get(name)
: if user:
: return user
: return None
And this can mislead the program. getpwuid() usually only stops at the
first entry matching the given userid. There are a lot of systems
which have multiple accounts with the same userid, for legitimate
reasons. If the user has changed the environment variable, there is
usually a reason. If your program is so paranoid, then you probably
want your own mechanism.
Not to mention that in some ways, it is far easier to "fake" out
accounts on a MS box than it is on a UNIX box. And then there are Mac
"accounts".
-Arcege
More information about the Python-list
mailing list