Search code examples
pythonmoduleprogram-entry-point

refer to __file__ from imported module


I have a main program main.py which imports a module lib.py

Is it possible to have a variable in lib.py which returns the name of the main program which called the script? I mean something which would return "lib.py" if lib.py is run directly and "main.py" if it is main.py which has been run and have called lib.py

Here is lib.py

import os
print(os.path.basename(__file__))

If I run lib.py, then the output is what I want, that is

lib.py

Here is main.py

import lib
print(__file__)

The output is

lib.py
main.py

Is there a variable, that I can call from lib.py, containing the name of the main program? I would like the output

main.py
main.py


Solution

  • According to [Python.Docs]: sys.argv (emphasis is mine):

    The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

    Therefore, you should use sys.argv[0] (don't forget to import sys 1st).