Program to print its script name as output in Python


In this tutorial, we are going to write a program that prints the name of the Python script file. We can find the script name using the sys module.

The sys module will store all the command line arguments of python command in the sys.argv list. The first element in the list is the script name. We can extract it from that list. Python makes it easy.

Let's see the steps involved in the program.

  • Import the sys module.

  • Now, print the first element of the sys.argv list.

  • That's it. You got the script name.

Example

Let's see it practically.

 Live Demo

# importing the sys module
import sys
# importing os module for absolute path
import os
# printing the script name
# first element of sys.argv list
print(os.path.abspath(sys.argv[0]))

Output

If you run the above code, you will get the absolute path of your Python script.

C:\Users\hafeezulkareem\Desktop\sample\tutorialspoint.py

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 24-Apr-2020

855 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements