简体   繁体   English

Python-ImportError:未命名模块

[英]Python - ImportError: No module named

I have following directory structure: 我有以下目录结构:

img_search
   --- server
       --- __init__.py
       --- server_flask.py
   --- tests
       --- __init__.py
       --- test_kdtree.py
       --- test_distance_matrix.py
   --- __init__.py
   --- kdtree.py
   --- distance_matrix.py

__init__.py in server and tests are empty and __init__.py in img_search contains following code: __init__.py的服务器和测试都是空的__init__.py在img_search包含以下代码:

from img_search import distance_matrix, kdtree

I use class from kdtree in server_flask.py using following import: 我使用以下导入在server_flask.py中使用来自kdtree的类:

from img_search import kdtree

When I run server_flask.py in PyCharm it works without any problems, however when I run it in terminal, I get an error. 当我在PyCharm中运行server_flask.py时 ,它可以正常工作,但是在终端中运行时,出现错误。

Traceback (most recent call last): File "server_flask.py", line 2, in <module> 追溯(最近一次通话): File "server_flask.py", line 2, in <module>

from img_search import kdtree

ImportError: No module named img_search

How can I fix this? 我怎样才能解决这个问题? Thank you in advance 先感谢您

I suppose you have some meaningful reason to do it that way but it doesn't need to look like this. 我想您有一些有意义的理由可以这样做,但它不必看起来像这样。

In general, modules should provide some functionalities and be consistent as one package or library that is providing some API. 通常,模块应该提供一些功能,并且与提供某些API的一个包或库一样,是一致的。

In other words this should be avoided: 换句话说,应该避免:

python server_flask.py

or 要么

python img_search/server/server_flask.py

But this one is totally fine: 但这完全没问题:

python main.py

With main.py having some kind of: main.py具有某种:

from img_search.server import server_flask
# Do something if needed

Have a good one! 祝你有个好的一天!

If you really need this, another option will be to mess with path . 如果您确实需要这样做,另一种选择是将path弄乱。 In your server_flask.py add following lines: 在您的server_flask.py添加以下行:

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))

sys.path.append will add to a path a module location which will be found by join ing dirname of server_flask.py __file__ and its ../.. directory. sys.path.append将增加的路径通过,会发现一个模块的位置join荷兰国际集团dirnameserver_flask.py __file__及其../..目录。 Here we are. 我们来了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM