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?
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With