Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 746
Kenneth Baltrinic Avatar asked Feb 16 '23 14:02

Kenneth Baltrinic


2 Answers

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")
like image 57
Kenneth Baltrinic Avatar answered Feb 19 '23 04:02

Kenneth Baltrinic


You could use the inspect module for this. For example:

a.py:

#!/usr/bin/python

import b

b.py:

#!/usr/bin/python

import inspect

print inspect.stack()[-1][1]

Running python b.py prints b.py. Running python a.py prints a.py.

However, I'd like to second the suggestion of sys.argv[0] as a more sensible and idiomatic suggestion.

like image 28
Cairnarvon Avatar answered Feb 19 '23 02:02

Cairnarvon