Reputation: 6332
I have following code structure:
config_dir
config.py
main.py
There is a method in config.py as follows:
def get_path():
# TODO
return "the absolute path of config.py, not the path of the main.py that import this config module"
in the main.py, I import the config module and call config's method get_path
from config_dir import config
print(config.get_path())
I would like print the absolute path of config.py, not the path of the main.py that import this config module
I would like how to code this, thank!
Upvotes: 0
Views: 342
Reputation: 3450
Try the following code:
import os
os.path.abspath(config)
Add the following code in config.py
import os
def get_path():
return os.path.abspath(__file__)
Upvotes: 1
Reputation: 8064
You can use this:
import os
def get_path():
return os.path.abspath(__file__)
Upvotes: 2
Reputation: 39
You can use file to get absolute path for imported module. For example:
from config_dir import config
print(config.__file__)
>>> import datetime
>>> datetime.__file__
'/usr/local/Cellar/python@2/2.7.17/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/datetime.so'
>>>
Upvotes: 2