简体   繁体   English

Python; 无法从其他目录导入模块

[英]Python; Cant import module from other directory

I am trying to decompose my program on python .我正在尝试在python上分解我的程序。 I have read a lot of information and other answers about how import works, but still cant understand how exactly.我已经阅读了很多关于import如何工作的信息和其他答案,但仍然无法理解到底是如何工作的。

I want to use my module Graph.Graph2D for implementation in InteractiveGraph2D .我想使用我的模块Graph.Graph2DInteractiveGraph2D中实现。 Before importing it, I add path to this module.在导入它之前,我添加了这个模块的路径。 But it tells NameError: name 'Graph2D' is not defined .但它告诉NameError: name 'Graph2D' is not defined

Project path:项目路径:

~/MyData/Python/Pygame/RoadSearchAlgorithm/src ~/MyData/Python/Pygame/RoadSearchAlgorithm/src

Module path:模块路径:

~/MyData/Python/Pygame/MY_MODULES/Graph ~/MyData/Python/Pygame/MY_MODULES/Graph

Code:代码:

# ~/MyData/Python/Pygame/RoadSearchAlgorithm/src/Graph_package/InteractiveGraph2D.py

...
sys.path.append('./')
sys.path.append('/home/rayxxx/MyData/Python/MY_MODULES')
try:
    from Graph.Graph2D import Graph2D, ...
    ...
except Exception as e:
    assert (e)

class InteractiveGraph2D(Graph2D):
    ...

What's the problem?有什么问题?

I tried to look at paths, list of imported modules.我试图查看路径、导入模块列表。 The Graph module presented in it.其中显示的 Graph 模块。

You say that the modules path is ~/MyData/Python/Pygame/MY_MODULES/Graph while in the python code you added the string '/home/rayxxx/MyData/Python/MY_MODULES' to the os.path.您说模块路径是~/MyData/Python/Pygame/MY_MODULES/Graph而在 python 代码中您将字符串'/home/rayxxx/MyData/Python/MY_MODULES'添加到 os.path。 Maybe the point is this也许重点是这个

this is a common error, when you run a python script it looks at the dir where you are running the script so four your case when you run这是一个常见的错误,当您运行 python 脚本时,它会查看您运行脚本的目录,因此当您运行时有四种情况

from Graph.Graph2D import Graph2D, ...

From

~/MyData/Python/Pygame/RoadSearchAlgorithm/src

Python at most can import from src. Python 最多可以从src导入。

Some solution, make your module installable by adding a setup in MY_MODULE , then doing a pip install.一些解决方案,通过在MY_MODULE中添加一个设置,然后进行 pip 安装,使您的模块可安装。 in that folder, here is an example How to setup .在该文件夹中,这里有一个示例如何设置. And maybe you need to add an init .py to MY_MODULES/, check here Do I need init .py也许你需要添加一个init .py 到 MY_MODULES/,检查这里我需要init .py

Another solution is to add MY_MODULES/ to python path, avoid this if possible but here is an example Add to python path .另一种解决方案是将MY_MODULES/添加到 python 路径,如果可能请避免这种情况,但这里有一个示例Add to python path

You should make the Graph module installable by adding a setup.py file to it's directory ( doc ).您应该通过将setup.py文件添加到它的目录 ( doc ) 来使 Graph 模块可安装。 Then you could install it with pip and import it like any library.然后你可以用 pip 安装它并像任何库一样导入它。

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

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