Python3模块导入

时间:2018-01-31 07:17:33

标签: python-3.x

美好的一天! 我有下一个项目结构:

config.json
tests/
-test_tcp.py
test_tools/
-include_proto.py

在我的'test_tcp.py'文件中,我有下一个代码:

    #! /usr/bin/python3

from google.protobuf import text_format

from test_tools import include_proto # the problem is here
import test_tools.temp_proto.timeline_api_pb2 as timeline_proto
import socket
...

我尝试使用下一个命令开始我的测试:python3 tests/test_tcp.py(我也尝试调用pytest .命令,但我认为在这种情况下它没有价值)。所以,我有预期的错误ImportError: No module named 'test_tools'。 我已经阅读了文档'man python3'并找到了下一个:

     PYTHONPATH
              Augments the default search path for module files.  The format is the  same  as  the
              shell's  $PATH:  one  or more directory pathnames separated by colons.  Non-existent
              directories are silently ignored.  The default search path  is  installation  depen‐
              dent,  but  generally  begins  with  ${prefix}/lib/python<version>  (see  PYTHONHOME
              above).  The default search path is always appended to  $PYTHONPATH.   If  a  script
              argument  is  given,  the directory containing the script is inserted in the path in
              front of $PYTHONPATH.  The search path can be manipulated from within a Python  pro‐
              gram as the variable sys.path.

因此,我使用我的根测试项目目录通过命令PYTHONPATH设置PYTHONPATH=$(pwd)。但是,我仍然有同样的错误。

怎么了? 对于这样的情况,是否存在任何良好的做法?

1 个答案:

答案 0 :(得分:0)

将空__init__.py文件添加到 test_tools 文件夹,让python知道它是一个模块。

有关Python模块的更多知识,请阅读文档中的this article