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.
# 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.