繁体   English   中英

Python3模块导入

[英]Python3 module importing

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

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=$(pwd)设置了PYTHONPATH 但是,我仍然有相同的错误。

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

在您的test_tools文件夹中添加一个空的__init__.py文件,以使python知道它是一个模块。

有关Python模块的更多知识,请阅读这篇文章的文档。

暂无
暂无

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

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