I want to obtain the file path of a function in Python.
How to do it?
For example,
JavaScript
x
6
1
import keras.backend as K
2
y = K.resize_images(x, 2, 2, 'channels_last')
3
path = function(K.resize_images)
4
print(path)
5
#C:Program FilesPython36Libsite-packageskerasbackendtensorflow_backend.py
6
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
JavaScript
1
12
12
1
#!/usr/bin/python
2
3
import os
4
import inspect
5
import external_def
6
7
def foo():
8
pass
9
10
print(os.path.abspath(inspect.getfile(foo)))
11
print(os.path.abspath(inspect.getfile(external_def.bar)))
12
external_def.py
JavaScript
1
3
1
def bar():
2
pass
3
Executing inspect_example.py
produces the following output:
JavaScript
1
4
1
$ python inspect-example.py
2
/home/chuckx/code/stackoverflow/inspect-example.py
3
/home/chuckx/code/stackoverflow/external_def.py
4