Explain Codes LogoExplain Codes Logo

Get name of current script in Python

python
script-name
pathlib
sys-argv
Alex KataevbyAlex Kataev·Aug 7, 2024
TLDR

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:

import os # This line prints the script name. So simple, it's almost suspicious, right? print(os.path.basename(__file__))

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:

import sys # Sherlock Holmes would need a magnifying glass, but we have sys.argv[0] print(sys.argv[0])

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:

import os # Follow the yellow brick road... to your script's full path! print(os.path.abspath(__file__))

And do you need to resolve symlinks' mystery? os.path.realpath comes to the rescue:

# The Real Slim Shady, please stand up. Aka, your script's path. print(os.path.realpath(__file__))

Say goodbye to file extensions

To get the script name sans extension, pair os.path.splitext() with __file__:

import os # Sayonara, extension! You're not needed here. script_name_without_extension = os.path.splitext(os.path.basename(__file__))[0] print(script_name_without_extension)

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:

from pathlib import Path # The modern-day incantation to get your script's name. Voila! print(Path(__file__).name)

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:

# For older versions, we dial back the time machine. import __main__ # Vintage method of fetching the script's name. Works like a charm. print(__main__.__file__)

or explicitly in the main module:

# Safety check engaged. Let's see if we're in the main module. if __name__ == "__main__": # Drumroll please... And there's your script's name! print(__file__)

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.