IntelliJ Python插件&运行类路径

2024-05-01 21:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个位于/home/myself/workspace/Project1的项目,为此我从Python 2.7.3virtualenv中创建了一个SDK,我已经安装了它。
这个项目使用一些我在可访问目录中拥有的外部代码,例如/home/myself/LIBRARY;这个目录包含几个带有代码、文档等的目录……
例如,有一个模块“important_util”位于/home/myself/LIBRARY/mymodule/important_util.py。

现在,我在SDK类路径中添加了整个dir/home/myself/LIBRARY,在编辑器窗口中看起来很好。可以识别导入和调用,我还可以在库目录中浏览代码。

问题是,当我试图运行我的程序时,它在第一次使用库导入时失败!!!

Traceback (most recent call last):
   File "/home/myself/workspace/Project1/my_program.py", line 10, in <module>
      from mymodule import important_util as ut 
      ImportError: No module named mymodule

我还试图将相同的目录添加到源代码部分的“全局库”部分…但没有成功。

我似乎找不到将此代码添加到运行类路径的方法,如何才能做到这一点?


Tags: 项目代码py路径目录homeutillibrary
3条回答

在Intellij14中,有点不同,你是这样的模块/鸡蛋:

  • 转到文件->;项目结构
  • 现在选择模块,然后选择“依赖项”选项卡
  • 单击“+”图标并选择“库”
  • 点击“New Library”并选择Java(我知道这很奇怪…)
  • 现在选择多个模块/鸡蛋和“确定”。
  • 从类别中选择“类”。
  • 给你的新库起个名字,“我的Python不是Java库”
  • 最后点击“添加选定项”

从2017.1版本开始,添加内容再次更改。文件菜单中没有项目结构。写下当前过程:

  1. 转到首选项/设置。文件->;设置(IDE名称->;macOS首选项)

  2. 选择构建、执行、部署

enter image description here

  1. 选择Python解释器

  2. 选择项目解释器的下拉菜单并选择项目所需的Python版本的路径。

enter image description here

  1. 单击Apply并等待几分钟,让IntelliJ为python包编制索引。

所有错误现在都应该消失了,您应该能够在外部库列表中看到项目中使用的Python。

enter image description here

快乐的编码。

确保在mymodule目录中有__init__.py目录:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later. ©

更新:在IntelliJ IDEA中,应将其他目录添加为模块依赖项或配置为Libraries(添加到依赖项),而不是Python SDK的Classpath选项卡:

Dependencies

我已验证此文件夹(D:\dev\lib)已添加到PYTHONPATH并导入工作。

相关问题 更多 >