簡體   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