簡體   English   中英

從另外兩個包導入一個公共包(python3)

[英]Importing a common package from two other packages (python3)

我是Python軟件包的新手,我正在努力讓事情變得有效。 我有3個包: engineuidb 我想從其他兩個包中使用db 這樣做的正確方法是什么?

我不想安裝db包,因為我目前正在同時開發3個包。

謝謝!


目前,我正試圖通過導入兄弟套餐來實現這一目標,但它太糟糕了,我不確定這是否是正確的方法。 這個問題與大量的問題密切相關,例如Python 3中的 相對導入ValueError:嘗試相對導入超出頂級包 ,但它們都沒有對我有效的工作答案:-(

這是我到目前為止所擁有的:

src/
  __init__.py     # empty file (is it useful?)
  db/
    __init__.py   # empty file
    constants.py
  ui/
    __init__.py   # empty file
    index.py
  engine/
    ...some stuff...

這是index.py:

from .. import db
print(db.constants.stuff)

但是,運行cd ui && python3 index.pypython3 -m index.py會因SystemError: Parent module '' not loaded, cannot perform relative import python3 -m index.py失敗SystemError: Parent module '' not loaded, cannot perform relative import

當我調整這個項目時,我有時會得到其他錯誤,比如ValueError: Attempted relative import in non-package

從我在https://docs.python.org/3/tutorial/modules.html上看到的,這應該有用,不應該嗎?

我究竟做錯了什么? 我該怎么做(做這么簡單的事情)使用另外兩個包中的通用包?

__init__.py非常有用,即使它是空的。 它告訴python文件夾是python包。

我認為你需要的是修改系統路徑。 例如,假設您要將constants.py導入index.py,index.py將如下所示:

import sys
sys.path.append("..")
from db import constants

暫無
暫無

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

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