In python, if a module calls upon another module&#

2020-07-31 07:52发布

问题:

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