Search code examples
pythonpython-2.7introspection

How to get the name of the top most (entry) script in python?


I have a utility module in Python that needs to know the name of the application that it is being used in. Effectively this means the name of the top-level python script that was invoked to start the application (i.e. the one where __name=="__main__" would be true). __name__ gives me the name of the current python file, but how do I get the name of the top-most one in the call chain?


Solution

  • Having switch my Google query to "how to to find the process name from python" vs how to find the "top level script name", I found this overly thorough treatment of the topic. The summary of which is the following:

    import __main__
    import os
    
    appName = os.path.basename(__main__.__file__).strip(".py")