Python 相对导入在 VS Code 中无法使用,但在 PyCharm 中正常

0 投票
2 回答
51 浏览
提问于 2025-04-12 21:54

我想在 model/task.py 文件中导入 db/connectdb.py,而这两个文件夹 modeldb 都在主项目文件夹里。

当我尝试使用 from db.connectdb import ConnectDb 时,出现了这个错误:

ModuleNotFoundError: 没有名为 'db' 的模块

当我尝试使用 from ..db.connectdb import ConnectDb 时,出现了这个错误:

ImportError: 尝试进行相对导入,但没有已知的父包

在 PyCharm 中一切正常。

我尝试在每个文件夹中添加 __init__.py 文件,但问题依然存在。

这是 connectdb.py 的内容:

import os
import sqlite3


class ConnectDb():
    def __init__(self):
        db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app.db')
        if os.path.isfile(db_path):
            self.db = sqlite3.connect(db_path)
        else:
            #self.db = None
            print("non")

    def get_connection(self):
        return self.db

这是 task.py 的内容:

#from ..db.connectdb import ConnectDb or
from db.connectdb import ConnectDb
class Tasks():
    def __init__(self):
        self.db = ConnectDb().get_connection()

    def get_all_tasks(self):
        return self.db.execute("Select * from tasks").fetchall()


t = Tasks()
print(t.get_all_tasks())

这是文件夹结构:

在这里输入图片描述

2 个回答

0

当你在VS Code中运行task.py时,它会去找一个叫做db的文件夹,这个文件夹应该在model文件夹里面,但它找不到这个文件夹……你可以把db文件夹放到model文件夹里,这样就应该能正常工作了。(我觉得还有其他方法,但我不太清楚……)

0

你可以通过把当前目录添加到路径中来解决这个问题:

import os
import sys
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # the line help you to get current file path
sys.path.append(root) # the line add the file path to path list

如果你想把其他目录也添加到路径中,可以重复这个步骤:

sys.path.append(your_dir)

用你自己的目录。不过对于你的项目来说,你只需要把数据库文件夹的上级文件夹添加到路径中。

最后的代码应该像下面这样:

import os
import sys
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # the line help you to get current file path
sys.path.append(root) # the line add the file path to path list

from db.connectdb import ConnectDb
class Tasks():
.
.
.

撰写回答