【问题标题】:Importing dependencies works in Pycahrm not Terminal?导入依赖项适用于 Pycharm 而不是终端?
【发布时间】:2017-07-18 14:45:48
【问题描述】:

我使用以下解决方案来导入依赖项。 如果我在 Pycharm 中而不是在终端中运行代码,我发现此解决方案有效。 终端中的错误消息是“找不到 graphics.primitive”。 我正在使用 Mac 和 Python 3.5。 为什么我看到终端和 Pycharm 的不同行为? 我怎样才能使解决方案对两者都适用?


http://chimera.labs.oreilly.com/books/1230000000393/ch10.html#_solution_169

制作模块的分层包 问题

您希望将代码组织到一个包含分层模块集合的包中。

解决方案

制作包结构很简单。只需在文件系统上根据需要组织代码,并确保每个目录都定义一个 init.py 文件。例如:

graphics/
    __init__.py
    primitive/
         __init__.py
         line.py
         fill.py
         text.py
    formats/
         __init__.py
         png.py
         jpg.py

完成此操作后,您应该能够执行各种导入语句,例如:

import graphics.primitive.line
from graphics.primitive import line
import graphics.formats.jpg as jpg

【问题讨论】:

    标签: python import terminal pycharm


    【解决方案1】:

    您需要确保图形包位于 Python 搜索路径中。 PyCharm 通过扩展sys.path 来做到这一点,如下所示:

    import sys    
    sys.path.extend(['/Users/hackworth/Development/graphics_parent_dir', '/Applications/PyCharm.app/Contents/helpers/pycharm', '/Applications/PyCharm.app/Contents/helpers/pydev'])
    

    您可以在代码中执行相同的操作,将 /Users/hackworth/graphics_parent_dir 替换为适当的路径,或者您可以在 PYTHONPATH 环境变量中包含 graphics_parent_dir 的完整路径。有关详细信息,请参阅 Python documentation

    另一种选择是将graphics 包放在系统上默认搜索的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2023-02-21
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多