I want to obtain the file path of a function in Python.
How to do it?
For example,
import keras.backend as K y = K.resize_images(x, 2, 2, 'channels_last') path = function(K.resize_images) print(path) #C:Program FilesPython36Libsite-packageskerasbackendtensorflow_backend.py
Thank you.
Advertisement
Answer
You can use the getfile() function from the inspect module for this purpose.
For example, given the following files:
inspect-example.py
#!/usr/bin/python
import os
import inspect
import external_def
def foo():
pass
print(os.path.abspath(inspect.getfile(foo)))
print(os.path.abspath(inspect.getfile(external_def.bar)))
external_def.py
def bar(): pass
Executing inspect_example.py produces the following output:
$ python inspect-example.py /home/chuckx/code/stackoverflow/inspect-example.py /home/chuckx/code/stackoverflow/external_def.py