質問

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