In python, if a module calls upon another module's functions, is it possible for the function to access the first module's filepath?

旧城冷巷雨未停 提交于 2019-12-09 23:52:15

问题


Without passing it as a parameter...

Ex. In test1.py:

def function():
    print (?????)

and in test2.py

import test1

test1.function()

Is it possible to write ????? so running test2.py prints out 'test2.py' or the full filepath? __file__ would print out 'test1.py'.


回答1:


This can be achieved using sys._getframe():

% cat test1.py
#!/usr/bin/env python

import sys

def function():
    print 'Called from within:', sys._getframe().f_back.f_code.co_filename

test2.py looks much like yours but with the the import fixed:

% cat test2.py
#!/usr/bin/env python

import test1

test1.function()

Test run...

% ./test2.py 
Called from within: ./test2.py

N.B:

CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.




回答2:


You can get the caller's frame first.

def fish():
    print sys._getframe(-1).f_code.co_filename



回答3:


If I understand correctly, what you need is:

import sys
print sys.argv[0]

It gives:

$ python abc.py 
abc.py



回答4:


Is this what you're looking for?

test1.py:

import inspect
def function():
  print "Test1 Function"
  f = inspect.currentframe()
  try:
    if f is not None and f.f_back is not None:
      info = inspect.getframeinfo(f.f_back)
      print "Called by: %s" % (info[0],)
  finally:
    del f

test2.py:

import test1
test1.function()
$ python test2.py
Test1 Function
Called by: test2.py


来源:https://stackoverflow.com/questions/7025538/in-python-if-a-module-calls-upon-another-modules-functions-is-it-possible-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!