Python (Scripting) - Return and print script name

by
Jeremy Canfield |
Updated: April 01 2024
| 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 absolute 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
Did you find this article helpful?
If so, consider buying me a coffee over at