How to know from inside a module, during run time, which script has called a function in it

StackOverflow https://stackoverflow.com/questions/12930867

  •  07-07-2021
  •  | 
  •  

Frage

I have a module in python, and based on the script that has called a function in it, I want to take a decision inside that module.

So if we have 2 file file1.py and file2.py, both import the module testmod and call a function in it. Inside the module testmod, I want to know which script has called it ? file1.py or file2.py.

I want to write a code like below in testmod if then do this else if then do that else do something else !

War es hilfreich?

Lösung

As already stated in the comments you can avoid this (since it is bad design and complicates things a lot) adding a parameter to that function. Or you could write two versions of this function if the code inside is much different from time to time.

Anyway, if you want to know from where your function got called you need the inspect module. I'm not an expert at it, but I don't think it's too hard to obtain the stack frame that called the function and from there understand which script called it.

Update:

If you really want to use inspect and do the ugly thing, here's a minimal working example:

#file a.py

import inspect
def my_func():
    dad_name = inspect.stack()[1][1]
    if inspect.getmodulename(dad_name) == 'b':   #or whatever check on the filename
         print 'You are module b!'
    elif inspect.getmodulename(dad_name) == 'c':
         print 'You are module c!'
    else:
         print 'You are not b nor c!'

#file b.py
import a

a.my_func()

#file c.py

import a
a.my_func()

#file d.py
import a
a.my_func()

Output:

$ python b.py
You are module b!
$ python c.py
You are module c!
$ python d.py
You are not b nor c!

If you want to add a parameter to the function:

#file a.py
def my_func(whichmod=None):
    if whichmod == 'b':
         print 'You are module b!'
    elif whichmod == 'c':
         print 'You are module c!'
    else:
         print 'You are not B nor C!'

#files b.py/c.py
import a
a.my_func(whichmod='b')   # or 'c' in module c

#file d.py
import a
a.my_func()

The output is the same.

Andere Tipps

I published a wrapper for inspect with simple stackframe addressing covering the stack frame by a single parameter spos, these do what the name promisses:

  • PySourceInfo.getCallerModuleFilePathName
  • PySourceInfo.getCallerModuleName

See:

Traceback

See if there is anything in the docs on traceback that gives you ideas.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top