Bootstrap FreeKB - Python (Scripting) - Return and print script name
Python (Scripting) - Return and print script name

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 58ad4c in the box below so that we can be sure you are a human.