Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 stores all the command line arguments of the 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.
Getting Script Name Only
To print just the script filename without the full path ?
import sys
import os
# Get just the filename
script_name = os.path.basename(sys.argv[0])
print(f"Script name: {script_name}")
Script name: script.py
Getting Full Absolute Path
To get the complete absolute path of the script file ?
import sys
import os
# Get the absolute path
absolute_path = os.path.abspath(sys.argv[0])
print(f"Full path: {absolute_path}")
Full path: /Users/username/Desktop/script.py
Understanding sys.argv
The sys.argv is a list containing command−line arguments. Let's examine its contents ?
import sys
print("All command-line arguments:")
for i, arg in enumerate(sys.argv):
print(f"sys.argv[{i}]: {arg}")
print(f"\nScript name: {sys.argv[0]}")
All command-line arguments: sys.argv[0]: script.py Script name: script.py
Alternative Methods
You can also use the __file__ variable to get script information ?
import os
# Using __file__ variable
print(f"Using __file__: {__file__}")
print(f"Basename: {os.path.basename(__file__)}")
print(f"Absolute path: {os.path.abspath(__file__)}")
Using __file__: script.py Basename: script.py Absolute path: /Users/username/Desktop/script.py
Comparison
| Method | Result | Use Case |
|---|---|---|
sys.argv[0] |
Script as invoked | Command-line execution |
__file__ |
Current module path | Module identification |
os.path.basename() |
Filename only | Clean script name |
Conclusion
Use sys.argv[0] to get the script name as invoked from command line. Use os.path.basename() for just the filename or os.path.abspath() for the full path. The __file__ variable is an alternative that works in most contexts.
