문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top