Get name of current script in Python
Instantly obtain your script's filename by employing os.path.basename(__file__)
. This nifty line of code yields the name of your file, excluding its path.
Example:
This will output your current script's filename.
Morethan just __file__
How to use sys.argv[0]
sys.argv[0]
, produces the script name as it is invoked via the command line. It loves to keep company with scripts converted through py2exe:
Handle with care, it could get messy if you're doing argument parsing or mystical symlinks change your script's name.
Absolute path with __file__
Go full Matilda and get the smartest answer. In Python 3.4+, __file__
serves an absolute path with the exception of if executed via a relative command:
And do you need to resolve symlinks' mystery? os.path.realpath
comes to the rescue:
Say goodbye to file extensions
To get the script name sans extension, pair os.path.splitext()
with __file__
:
This could be your lifesaver when dealing with Python modules on the run.
The magic of pathlib
Who needs a magic wand when you got pathlib
, a modern, savvy approach to file paths manipulation:
When all else fails
If none of these tickles your fancy, consider the inspect
module, or third-party libraries like lib_programname
, for those rainy days when you need more than a basic solution.
Python versions' compatibility
Note that some methods might behave differently across Python versions. Always run a check with your friendly neighborhood version checker:
or explicitly in the main module:
Avoid tripwires in path handling
Clever scripts must navigate a jungle of variable paths, where the unfamiliar terrain can lead to unexpected missteps.
The case of the variable working directory
For scripts running mid-journey, a wayward __file__
might lead to the wrong path. Be on your guard for shifting landscape.
Scripts lost in relocation
A post-move or symlink-accessed script might lose itself, serving you an alias unless you resolve the true path.
Other useful tools
While os.path.basename(__file__)
is the community's favorite, you might want to expand your detective toolkit according to the case at hand.
Was this article helpful?