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.


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


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



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