简体   繁体   中英

How to get the name of the module, calling a specific function, in Python.

Is there a way to find out which file is calling a function? (similar to os.path.basename(__file__) )

Program structure:

  • module contains function in question

Somewhere else in the program:

import modulex as mx

mx.function(arg1,arg2)

I need a universal function to tell me what file 'somewhere else in the program' is.

You can try traceback module:

import traceback
currentStack=traceback.extract_stack()

currentStack variable will hold list of file names from where current code is called.

If you have behaviour that depends on the file calling the function, maybe you should pass an extra argument to the function, indicating it?

In python, explicit solutions are considered the best - having behaviour that depends on the caller is not explicit.

If you really have good reasons to need this, you may want to look into the traceback module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM