簡體   English   中英

在python的父文件夾中導入自定義模塊

[英]Import a custom module in the parent folder in python

雖然我認為這應該很簡單,但我仍然無法讓它運行。

我有以下文件夾結構:

├── apartment          
│   ├── src        
│       ├── train_model
│           ├── __init__.py 
│           ├── train_model.py
│           ├── utils.py
│       ├── interference.py
│       └── __init__.py

utils.py我試過:

from src.interference import create_sample

錯誤:ModuleNotFoundError:沒有名為“src”的模塊

from .interference import create_sample

錯誤:ImportError:嘗試在沒有已知父包的情況下進行相對導入

from interference import create_features_sample

ModuleNotFoundError: 沒有名為“interference”的模塊

有什么辦法讓它工作? 我不是非 Pythonic 方式的忠實粉絲,因為它看起來很臟。

您需要將包含干擾的目錄添加到PYTHONPATH

您可以在sys.path列出的“模塊搜索路徑”中使用依賴於操作系統的路徑。 因此,您可以輕松添加父目錄,如下所示:

import sys
sys.path.insert(0, '..')

from interference import create_features_sample

請注意,前面的代碼使用相對路徑,因此您必須在同一位置啟動文件,否則它可能無法工作。 要從任何地方啟動,您可以使用pathlib模塊中的Path

from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)

from interference import create_features_sample

src/開頭的結構明確旨在通過from src.intereference import ...啟用導入,並且您不應將__init__.py文件放在src/文件夾中。

相反,請遵循以下很好的解釋和示例: https : //blog.ionelmc.ro/2014/05/25/python-packaging/ ,這是我推薦的:

  • 安裝軟件包:

    • 在文件夾的根目錄添加一個setup.py文件(這顯然不像看起來那么難)
    • 也許創建一個虛擬環境
    • 使用pip install -e . (帶有尾隨點!)命令
  • 然后只需通過from interference import ...導入您的包from interference import ...

為了響應您的主要請求,您可以使用from intereference import create_sample src/__init__.py from intereference import create_sample更新src/__init__.py ,以在更高級別公開此函數,然后鏈式導入將起作用。 但是,我不推薦這樣做,因為它使一切變得非常僵化。

您是否嘗試過from ..interference import create_sample

或者對於整個模塊from .. import interference

我在這里檢查過,我正在使用另一個命令,在撰寫本文時問題中缺少某些內容。 我使用的命令是apartment文件夾中的python -m src.train_model.utils

感謝RMPR幫助我。

這個問題類似於這個

如果您想永久添加自定義路徑到您的 PYTHONPATH,請轉到當前 Python 環境的“site-packages”文件夾並添加文件“custompaths.pth”,其中每行應包含一個目錄,然后將檢查該目錄是否存在您嘗試導入模塊。

假設 'src' 是您要導入的模塊,您應該將以下行添加到 .pth 文件中:

your_preceding_path/公寓

由於python無法找到特定文件或包而導致的錯誤。 Python 通常只查找子包或文件,否則需要指定絕對路徑。

import sys, os
sys.path.append(os.path.abspath(os.path.join('../..', 'src')))

請參閱“ 如何從 Python 中的文件夾外部訪問模塊?

暫無
暫無

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

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