简体   繁体   English

如何获取导入的python文件的绝对路径

[英]How to get the absolute path of the imported python file

I have following code structure:我有以下代码结构:

config_dir
    config.py

main.py

There is a method in config.py as follows:在config.py中有一个方法如下:

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在 main.py 中,我导入配置模块并调用配置的方法 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我想打印 config.py 的绝对路径,而不是导入此配置模块的 main.py 的路径

I would like how to code this, thank!想请教一下这个代码怎么写,谢谢!

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'
>>> 

You can use this:你可以使用这个:

import os

def get_path():
    return os.path.abspath(__file__)

Try the following code:试试下面的代码:

import os
os.path.abspath(config)

edit-1 (credits: Milan Cermak) edit-1(学分:Milan Cermak)

Add the following code in config.pyconfig.py中添加如下代码


import os

def get_path():
    return os.path.abspath(__file__)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM