3

So i wonder if there is a way to find out which user is currently logged in on the computer, and store it in a variable so i get print it out or do something else with it later. The reason why i need this is because when i enter a path including the user, it's gonna be diffrent depending on which user is logged in. I tried to look for this on the internet but i could't find what I was looking for.

OS: Windows 8.1 Version: Python 3.4 Let me know if there is anything i need to clearify.

OT: I'm sorry for any potential mistakes i've done, i'm new to this site.

Example:

checkuser = #The user currently logged in

print("The user currently logged in is: " + checkuser)

So for example if ExampleUser would be logged in it would print:

"The user currently logged in is: ExampleUser"

Lojas
  • 195
  • 3
  • 13
  • You must provide more information on the environment in order for anyone here to help you. Is this Linux, Windows, Mac OS, or do you want it to work for all environments? – Random Davis Feb 21 '17 at 19:35
  • Added operating system. – Lojas Feb 21 '17 at 19:37
  • 2
    Possible duplicate of [Is there a portable way to get the current username in Python?](http://stackoverflow.com/questions/842059/is-there-a-portable-way-to-get-the-current-username-in-python) – MuertoExcobito Feb 21 '17 at 20:24

2 Answers2

4

Check this site

the answer with your snippet would be:

import getpass
checkuser = getpass.getuser()

print("The user currently logged in is: " + checkuser)

Also if you need the name just because of the home directory path you can use os.environ['HOMEPATH'] (on Windows) to get the path directly.

kyjanond
  • 418
  • 3
  • 8
0

Use the getpass module. It provides you with a getuser function that will return current user.

https://docs.python.org/2/library/getpass.html

Example:

from getpass import getuser

print(getuser())
Luke
  • 744
  • 2
  • 7
  • 23