【问题标题】:python ModuleNotFoundError when trying to import a package尝试导入包时出现python ModuleNotFoundError
【发布时间】:2020-06-03 18:26:59
【问题描述】:

我的桌面上有两个文件夹,一个名为“testpackage”,另一个名为“testplay”。 'testpackage' 包含一个 init.py 和另一个名为 'numberstuff.py' 的文件(一个有两种方法的类)。 'testplay' 包含'play_01.py',一个简单的脚本来检查我可以将一个包添加到 sys.path 而不将它物理添加到 sys.path 中的库中,我想我可以通过 sys.path.append 做到这一点(path\to\file) 在 windows 上的 python3 上。

测试播放“play_01.py”代码:

import sys
for i in sys.path:
    print(i,'\n')

sys.path.append('C:\\Users\\priper\\Desktop\\testpackage')
from testpackage import numberstuff


a = numberstuff.maffs()
print(a.sqrtx(3))

控制台返回:

   C:\Users\priper\AppData\Local\Programs\Python\Python37\python37.zip 
C:\Users\priper\AppData\Local\Programs\Python\Python37\DLLs 
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib 
C:\Users\priper\AppData\Local\Programs\Python\Python37 
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib\site-packages 
C:\Users\priper\AppData\Roaming\Python\Python37\site-packages 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ 
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib\site-packages\win32 
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib\site-packages\win32\lib 
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib\site-packages\Pythonwin 
C:\Users\priper\Desktop\sdnplay 
C:\Users\priper\Desktop\mypackage 
sdnplay.py 
sdnplay.py 
sdnplay.py 
sdnplay 
sdnplay 
C:\Users\priper\Desktop\sdnplay 
C:\Users\priper\Desktop\sdnplay 
C:\Users\priper\Desktop\sdnplay 
C:\Users\priper\Desktop\sdnplay 
C:\Users\priper\Desktop\testplay 
C:\Users\priper\Desktop\testpackage 
C:\Users\priper\Desktop\testpackage 

错误:

ModuleNotFoundError: No module named 'testpackage'

File"C\Users\priper\Desktop\testplay\play_01.py", line 6, in <module> from testpackage import numberstuff

我可以看到 sys.path 中有 testpackage,我只是不知道为什么它被视为一个模块以及为什么我不能导入它>

预期输出为“9”。

【问题讨论】:

  • 试试from testpackage.numberstuff import * 而不是from testpackage import numberstuff
  • 嗨 Anwarvic,同样的错误。

标签: python module package sys.path


【解决方案1】:

我能想象的唯一一件事是您已将文件夹命名为“testpackage”,但您尝试导入的文件有另一个名称。但是由于您尝试导入名为“testpackage”的文件,因此您会遇到异常。

我已尝试重建您的问题,但无法重建。

我的文件夹/文件结构如下:

/full/path/to/the/parent/folder:
    - main.py
    - theFolder/
        - IAMATEST.py

ma​​in.py

import sys

sys.path.append('/full/path/to/the/parent/folder/theFolder')

from IAMATEST import IAMATESTClass

IAMATESTClass.calla()

IAMTEST.py

class IAMATESTClass:
    @staticmethod
    def calla():
        print("GOT CALLED")

在执行 ma​​in.py 时,我得到输出“GOT CALLED”。

祝你好运!

【讨论】:

    猜你喜欢
    • 2019-07-03
    • 2020-03-21
    • 2021-07-12
    • 2021-12-05
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多