【发布时间】:2020-04-21 01:33:00
【问题描述】:
我有一个简单的python项目,目录结构如下:
sample-project/
main/
config/
config.yaml
docker/
Dockerfile
tests/
__init__.py
sometests.py
config.py
run.py
__init__.py
requirements.txt
README.rst
在 config.py 文件中,我有:
import yaml
class Config:
def __init__(self):
with open("config/config.yaml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
self.host = cfg["mysql"]["host"]
self.database = cfg["mysql"]["database"]
self.user = cfg["mysql"]["user"]
self.password = cfg["mysql"]["password"]
my_config = Config()
在run.py文件中,我有一个import语句如下:
from main.config import my_config
当我使用命令行运行时:python3.5 run.py,我得到错误:
从 main.config 导入 my_config
ImportError: 没有名为“main”的模块
但是当我在 run.py 导入中添加它时,它可以工作:
import sys
sys.path.append('/home/tomas/sample-project/')
有没有更好的方法让它工作而不是给出绝对路径或任何其他方式?请举个例子:)
【问题讨论】:
-
您可以使用
sys.path.append('..')附加相对部分。
标签: python python-import