How to use OS library In Python
OS library in Python allows you to directly interact with the operating system. There are multiple functions you can use from the OS library to get the current username:
- os.getlogin()
- os.path.expanduser()
- os.environ.get()
Using the getlogin() method to get the current username
getlogin() method of OS library is used to get the current username.
Syntax :
os.getlogin( )
Example 1: Using getlogin() method
# importing os module
import os
# using getlogin() returning username
os.getlogin()
Output :
'KRISHNA KARTHIKEYA'
Using the expanduser() method to get the current username
os.path.expanduser() method retrieves the name of the user currently logged in to the operating system.
Example: Get username using os.path.expanduser() method
There is another method available in the OS library named path.expanduser() method. In this function, we need to pass the Tilde operator within single quotes as an argument.
Syntax :
os.path.expanduser( )
Note: In this method, we need to pass the tilde operator as an argument.
# importing required module
import os
# using path.expanduser() getting username
os.path.expanduser('~')
Output :
'C:\\Users\\KRISHNA KARTHIKEYA'
Using the environ.get() method to get the current username
You can use os.environ.get() method to get the current username from the USERNAME environment variable.
Example 3: Get username using os.environ.get() method
This method is also available in the os module. We need to pass USERNAME as an argument into this method. Let us see the syntax and example.
Syntax :
os.environ.get( " USERNAME" )
Note: In some cases, we need to pass USER instead of USERNAME. In most cases, we pass USERNAME as an argument.
# importing os module
import os
# using environ.get() method getting
# current username
os.environ.get('USERNAME')
Output :
'KRISHNA KARTHIKEYA'
How to get the current username in Python
When building interacting Python programs you might need to get the current username for features like personalizing user experience, providing user-specific resources, Implementing robust logging and debugging, strengthening security, etc.
We will use different Python modules and functions like os.getlogin(), os.path.expanduser(), environ.get() method to get the current username in Python.
In this tutorial, we will discuss how to get the current username in Python.