Kenneth Baltrinic
Kenneth Baltrinic

Reputation: 2981

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?

Upvotes: 4

Views: 4033

Answers (3)

MSalters
MSalters

Reputation: 179877

In Python 3.9 (as noted in the comments) there's no __main__ identifier. However, the name of that module is still '__main__' (with quotes, since it's a string). Else the usual __name__=='__main__' idiom wouldn't work.

Hence, the solution is easy: Just use sys.modules['__main__'].__file__ instead of __main__.__file__.

Upvotes: 2

Kenneth Baltrinic
Kenneth Baltrinic

Reputation: 2981

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")

Upvotes: 9

Cairnarvon
Cairnarvon

Reputation: 27782

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.

Upvotes: 3

Related Questions