簡體   English   中英

如何從父目錄導入 Python Class 或 Function?

[英]How to import Python Class or Function from parent directory?

0

我有這個項目結構,

.\src
  .\api
    test.py
  .\config
    config.py
  app.py

當我嘗試從 config.py 中的 test.py 導入 function 或 class 時,使用此語句

from src.api.test import tes_func

我收到這個錯誤

ModuleNotFoundError: No module named 'src.api'

如果我使用這兩行,我可以使用導入

from api.test import tes_func.

import sys
sys.path.append("../")

為什么它在使用時不起作用 from src.api.test import test_func 有沒有辦法在沒有sys.path.append("../")的情況下導入 python 文件。

提前致謝。

請閱讀: https://docs.python.org/3/reference/import.html#package-relative-imports

你必須使用這樣的東西:

from ..api.test import tes_func

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM