簡體   English   中英

即使創建了模塊,也找不到 Python 模塊

[英]Python module not found even though module was created

這是我當前的目錄結構,我試圖從src/helpers/log.py導入一個函數到src/data/download_dataset.py 我已經遵循了這個答案,但它仍然不起作用。

|-- AUTHORS.rst
|-- CONTRIBUTING.rst
|-- HISTORY.rst
|-- LICENSE
|-- MANIFEST.in
|-- Makefile
|-- README.rst
|-- data
|   |-- external
|   |-- interim
|   |-- processed
|   `-- raw
|       `-- wine-quality.csv
|-- docs
|   |-- Makefile
|   |-- authors.rst
|   |-- conf.py
|   |-- contributing.rst
|   |-- history.rst
|   |-- index.rst
|   |-- installation.rst
|   |-- make.bat
|   |-- readme.rst
|   `-- usage.rst
|-- dvc_mlflow
|   |-- __init__.py
|   `-- dvc_mlflow.py
|-- logs
|-- models
|-- requirements_dev.txt
|-- setup.cfg
|-- setup.py
|-- src 
|   |-- data
|   |   |-- __init__.py
|   |   `-- download_dataset.py
|   |-- features
|   |   `-- __init__.py
|   |-- helpers
|   |   |-- __init__.py
|   |   `-- log.py
|   `-- models
|       `-- __init__.py
|-- tests
|   |-- __init__.py
|   `-- test_dvc_mlflow.py
`-- tox.ini

我在src/data/download_dataset.py導入文件log_error像這樣:

from helpers.log import log_error

但是當我嘗試使用python3 src/data/download_dataset.py運行文件時,我收到錯誤ModuleNotFoundError: No module named 'helpers' 我有點困惑,因為我已經在每個目錄中添加了__init__.py文件以使它們成為模塊,但問題仍然存在。

你可以試試sys.path.append方法。 無論您想導入什么模塊,找到這些模塊的路徑並將其傳遞給函數。

例子:

如果我當前的工作目錄是/home/user_name/Desktop/Scripts/Main.py並且我想導入一些位於/home/user_name/Documents/OtherScripts/文件Factorial.py ,我可以執行以下操作

# Inside your Main.py file
import sys
sys.path.append("/home/user_name/Documents/OtherScripts/")
from Factorial import *

您正在從項目的根目錄運行它,其中只有src 所以它要么需要from src.helpers.log import log_error要么你需要從src目錄運行它。

通常,您希望使用與項目相同的名稱命名src目錄,因此導入看起來合乎邏輯。

我發現了一種更簡單的方法,我不必使用sys.path.append()附加路徑,只需要使用export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"在命令行中設置 python 路徑export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/"

暫無
暫無

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

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