Python 如何在运行时从模块内部知道哪个脚本调用了其中的函数

Python 如何在运行时从模块内部知道哪个脚本调用了其中的函数,python,module,trace,inspect,Python,Module,Trace,Inspect,我有一个python模块,基于调用其中函数的脚本,我想在该模块内做出决定 因此,如果我们有两个文件file1.py和file2.py,则都导入模块testmod并调用其中的函数。在模块testmod中,我想知道哪个脚本调用了它file1.py或file2.py 我想在testmod中编写如下代码 若然 这样做 否则 那样做 其他的 做点别的 查看traceback上的文档中是否有任何内容可以为您提供想法。如评论中所述,您可以避免向该函数添加参数(因为这是一种糟糕的设计,会使事情变得复杂)。或者

我有一个python模块,基于调用其中函数的脚本,我想在该模块内做出决定

因此,如果我们有两个文件
file1.py
file2.py
,则都导入模块testmod并调用其中的函数。在模块testmod中,我想知道哪个脚本调用了它
file1.py
file2.py

我想在testmod中编写如下代码 若然 这样做 否则 那样做 其他的 做点别的


查看
traceback
上的文档中是否有任何内容可以为您提供想法。

如评论中所述,您可以避免向该函数添加参数(因为这是一种糟糕的设计,会使事情变得复杂)。或者,如果函数中的代码有时有很大差异,您可以编写两个版本的函数

无论如何,如果你想知道你的函数是从哪里被调用的,你需要这个模块。我不是这方面的专家,但我认为获取调用函数的堆栈帧并从中了解哪个脚本调用它并不太难

更新:

如果您真的想使用
检查
并做一些丑陋的事情,下面是一个简单的工作示例:

#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()
输出:

$ python b.py
You are module b!
$ python c.py
You are module c!
$ python d.py
You are not b nor c!
如果要向函数添加参数,请执行以下操作:

#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()

输出是相同的。

我发布了一个用于inspect的包装器,使用简单的stackframe寻址,通过单个参数spos覆盖堆栈帧,它们实现了名称所承诺的功能:

  • PySourceInfo.getCallerModuleFilePathName
  • PySourceInfo.getCallerModuleName
见:


您的用例是什么?为什么
file1
file2
不能使用切换开关的额外参数调用函数<代码>函数myfunc(arg1,arg2,dosomething=False)
或类似。如果您的模块需要知道是谁调用了它,那么您将无法达到模块化的目的。您只需将参数添加到用于执行此操作的函数中即可