【问题标题】:showing import error in python while i have the packages in sys.path当我在 sys.path 中有包时,在 python 中显示导入错误
【发布时间】:2020-08-17 14:03:45
【问题描述】:

我在 sys.path 上有包,但它显示导入错误。但是如果我尝试在目录结构的上层导入相同的包,它就可以工作。

(flask) [ tests ] $ python3
Python 3.7.5 (default, Nov 20 2019, 09:21:52) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/rohit/flask/lib/python3.7/site-packages', '/home/rohit/flask/src/flaskr', '/home/rohit/flask/src/mycode']
>>> import mycode
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'mycode'
>>> import flaskr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flaskr'
>>> exit()


(flask) [ tests ] $ cd ..
(flask) [ src ] $ python3
Python 3.7.5 (default, Nov 20 2019, 09:21:52) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/rohit/flask/lib/python3.7/site-packages', '/home/rohit/flask/src/flaskr', '/home/rohit/flask/src/mycode']
>>> import mycode
>>> import flaskr
>>> 

【问题讨论】:

    标签: python python-3.x flask import


    【解决方案1】:

    如您的测试所示:如果您要导入的包是/home/rohit/flask/src/flaskr/home/rohit/flask/src/mycode,则需要将/home/rohit/flask/src 添加到您的路径中。您的第二次尝试有效,因为您在此文件夹中。

    你可以进一步测试它:

    import sys
    sys.path.append('/home/rohit/flask/src')
    # with relative import for a test module in test subdirectory:
    # sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    import mycode
    import flaskr
    

    来源:https://docs.python.org/3.7/tutorial/modules.html#packagesWhen importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 2020-12-14
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多