Index: Doc/library/os.rst =================================================================== --- Doc/library/os.rst (revision 84639) +++ Doc/library/os.rst (working copy) @@ -244,12 +244,12 @@ .. function:: getlogin() Return the name of the user logged in on the controlling terminal of the - process. For most purposes, it is more useful to use the environment variable - :envvar:`LOGNAME` to find out who the user is, or + process. For most purposes, it is more useful to use the environment variables + :envvar:`LOGNAME` or :envvar:`USERNAME` to find out who the user is, or ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently effective user id. - Availability: Unix. + Availability: Unix, Windows. .. function:: getpgid(pid) Index: Lib/test/test_os.py =================================================================== --- Lib/test/test_os.py (revision 84639) +++ Lib/test/test_os.py (working copy) @@ -1194,6 +1194,21 @@ self.assertEqual(int(stdout), os.getpid()) +class LoginTests(unittest.TestCase): + @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin") + def test_getlogin(self): + user_name = os.getlogin() + self.assertNotEqual(len(user_name), 0) + + lname = os.getenv('LOGNAME') + if lname is not None: + self.assertEqual(lname, user_name) + + uname = os.getenv('USERNAME') + if uname is not None: + self.assertEqual(uname, user_name) + + def test_main(): support.run_unittest( FileTests, @@ -1212,6 +1227,7 @@ Win32SymlinkTests, FSEncodingTests, PidTests, + LoginTests, ) if __name__ == "__main__": Index: Modules/posixmodule.c =================================================================== --- Modules/posixmodule.c (revision 84639) +++ Modules/posixmodule.c (working copy) @@ -122,6 +122,7 @@ #ifdef _MSC_VER /* Microsoft compiler */ #define HAVE_GETCWD 1 #define HAVE_GETPPID 1 +#define HAVE_GETLOGIN 1 #define HAVE_SPAWNV 1 #define HAVE_EXECV 1 #define HAVE_PIPE 1 @@ -4426,6 +4427,12 @@ #ifdef HAVE_GETLOGIN + +#ifdef MS_WINDOWS +/* for UNLEN */ +#include +#endif + PyDoc_STRVAR(posix_getlogin__doc__, "getlogin() -> string\n\n\ Return the actual login name."); @@ -4434,6 +4441,17 @@ posix_getlogin(PyObject *self, PyObject *noargs) { PyObject *result = NULL; +#ifdef MS_WINDOWS + wchar_t user_name[UNLEN + 1]; + DWORD nChars = _countof(user_name); + + if (GetUserNameW(user_name, &nChars)) { + /* nChars is the number of unicode chars plus null terminator */ + result = PyUnicode_FromWideChar(user_name, nChars - 1); + } + else + result = PyErr_SetFromWindowsErr(GetLastError()); +#else char *name; int old_errno = errno; @@ -4448,10 +4466,10 @@ else result = PyUnicode_DecodeFSDefault(name); errno = old_errno; - +#endif return result; } -#endif +#endif /* HAVE_GETLOGIN */ #ifdef HAVE_GETUID PyDoc_STRVAR(posix_getuid__doc__,