Python (Scripting) - Return and print script name
by
Jeremy Canfield |
Updated: October 02 2026
| Python (Scripting) articles
The os module can be used to get the name of your Python script.
#!/usr/bin/python3
import os.path
print(f"scriptname = {os.path.basename(__file__)}")
Which should print something like this.
scriptname = example.py
Or sys can be used.
#!/usr/bin/python3
import sys
print(f"scriptname = {sys.argv[0]}")
Which should print the path to the script from your present working directory.
scriptname = /home/john.doe/example.py
If you only want the script name, and not the path, you can include os.path.basename.
#!/usr/bin/python3
import sys
print(f"scriptname = {os.path.basename(sys.argv[0])}")
Which should print just the scriptname.
scriptname = example.py
Path can be used.
#!/usr/bin/python3
from pathlib import Path
print(f"scriptname = {Path(__file__).resolve()}")
Which should print the absoluete path to the script.
scriptname = /home/john.doe/example.py
Or os can be used.
#!/usr/bin/python3
import os
print(f"scriptname = {os.path.abspath(__file__)}")
Which should print the absoluete path to the script.
scriptname = /home/john.doe/example.py
Did you find this article helpful?
If so, consider buying me a coffee over at 