Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a portable way to get the current username in Python?

Is there a portable way to get the current user's username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid:

>>> os.getuid() 42 >>> os.getusername() 'slartibartfast' 

I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.

like image 303
Jacob Gabrielson Avatar asked May 08 '09 22:05

Jacob Gabrielson


People also ask

How do I find my current username?

Summary. You can make a Windows API (application programming interface) call to a Microsoft Windows DLL (dynamic-link library) to get the current user name. The current user name can be obtained by using the GetUserNameA function in ADVAPI32. DLL.

What is the code in Python to know the current user of the window *?

If so, it's as simple as it sounds: just write getpass. getuser() where you've written 'USERNAME' , and you're done.

How do you PWD in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

How do I ask for a username and password in Python?

The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.


2 Answers

Look at getpass module

import getpass getpass.getuser() 'kostya' 

Availability: Unix, Windows


p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."

like image 184
Konstantin Tenzin Avatar answered Oct 10 '22 01:10

Konstantin Tenzin


You best bet would be to combine os.getuid() with pwd.getpwuid():

import os import pwd  def get_username():     return pwd.getpwuid( os.getuid() )[ 0 ] 

Refer to the pwd docs for more details:

http://docs.python.org/library/pwd.html

like image 41
Liam Chasteen Avatar answered Oct 10 '22 02:10

Liam Chasteen