2017-07-18 49 views
0

我使用下面的解决方案导入依赖关系。 我发现这个解决方案工作,如果我在Pycharm中运行的代码,但不是在终端。 终端中的错误信息是“can not find graphics.primitive”。 我正在使用Mac和Python 3.5。 为什么我看到终端和Pycharm的不同行为? 我该如何让解决方案适用于两者?导入依赖项在Pycahrm中不起作用?


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语句,如下列:

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

回答

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软件包放置到系统默认搜索的位置。