casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
get_user.py
Go to the documentation of this file.
00001 import errno
00002 import os
00003 import pwd
00004 
00005 def get_user():
00006     # Seen in
00007     # http://cr.opensolaris.org/~migi/24_09_os_unix_using_osgetlogin_3595/test1.py
00008     def __get_username():
00009         # Cron jobs, at least in Ubuntu, are more likely to have LOGNAME set
00010         # than USER.
00011         #
00012         # Note that environment variables are easily forged...
00013         #
00014         user = os.getenv('USER') or os.getenv('LOGNAME') or \
00015                os.getenv('USERNAME')
00016 
00017         if not user:
00018             # ...but when su is being used it's hard to tell in advance
00019             # whether the uid or euid is wanted.
00020             return pwd_module.getpwuid(os.getuid()).pw_name
00021 
00022         return user
00023 
00024     try:
00025         # os.getlogin() is limited to whatever POSIX getlogin() does.
00026         return os.getlogin()
00027     except AttributeError:
00028         # os.getlogin() not available on this platform.
00029         return __get_username()
00030     except OSError, e:
00031         if e.errno == errno.ENOTTY:
00032             # Known failure case for gksu.
00033             return __get_username()
00034         else:
00035             # In most cases, just do an os.getlogin() yourself if you want to see the error.
00036             #print "os.getlogin() raised exception", e
00037             #print "get_user() is using __get_username() instead of os.getlogin()."
00038             return __get_username()
00039         #raise