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 Files\Python36\Lib\site-packages\keras\backend\tensorflow_backend.py
Thank you.
PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.
Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .
To get current file's full path, you can use the os. path. abspath function. If you want only the directory path, you can call os.
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
if you want to obtain the path of the file that contains a function you can try the following code, note: this code only works if the object type is 'function'
def get_path(func):
if type(func).__name__ == 'function' :
return func.__code__.co_filename
else:
raise ValueError("'func' must be a function")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With