[問題] 資料夾結構問題

看板Python作者 (Rebellionyu)時間8年前 (2017/03/20 16:08), 編輯推噓0(0022)
留言22則, 4人參與, 最新討論串1/1
Hi all, 最近在寫一個line chat bot練習。 而現在我想寫一些unit test快速測試code。 但遇到import的問題。 資料夾結構如下: linebot/ |__bot/ | |__ __init__.py | |__ app.py | |__ Dockerfile | | | |__ db_operator/ | | |__ db_operator.py | | |__ db_init.py | | | |__ weatherParser/ | | |__ weather.py | | |__ distInfor.json | | | |__ metroParser/ | |__ metro.py | |__ metroCode.ini | |__ metroCodeParser.py |__ mysqlbot/ |__ MYSQLFILES.. 我現在bot資料夾裡,加了tests/unit/這樣的資料夾, 在tests/unit/test.py裡寫我要測的test case。 但想不出在test.py裡要怎麼import bot/weatherParser/weather。 資料夾都有新增__init__.py,目前簡單測試都是顯示沒有bot這個module。 想請問python常見的資料夾結構會是長什麼樣? 或是我應該把db_operator, weatherParser, metroParser裡面的.py檔都合成一個py檔? 謝謝各位。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.60.175 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1489997316.A.39E.html

03/20 17:28, , 1F
一般會把測試和你的主要程式平行放, 你的例子應該是和
03/20 17:28, 1F

03/20 17:29, , 2F
bot 同一層; 不知道你怎麼執行 unit test, 但通常會寫成
03/20 17:29, 2F

03/20 17:30, , 3F
import bot.weatherParser.weather
03/20 17:30, 3F

03/20 18:22, , 4F
from bot import ... ,在 bot/ 執行
03/20 18:22, 4F

03/20 18:34, , 5F
我剛剛測試了一下,放在tests/unit/test.py,
03/20 18:34, 5F

03/20 18:35, , 6F
要用python -m unittest tests.unit.test 跑
03/20 18:35, 6F

03/20 18:35, , 7F
而test.py只要from weatherParser import weather
03/20 18:35, 7F

03/20 18:36, , 8F
但如果直接跑 python ./tests/unit/test.py 就不行
03/20 18:36, 8F

03/20 18:36, , 9F
會說找不到weatherParser這個module
03/20 18:36, 9F

03/21 23:14, , 10F
你資料夾每一層都要有 __init__.py
03/21 23:14, 10F

03/21 23:32, , 11F
import 搜尋是看 sys.path,根據你執行方式會改變
03/21 23:32, 11F

03/21 23:33, , 12F
python ./tests/unit/test.py 他 sys.path 就會在 \unit
03/21 23:33, 12F

03/21 23:34, , 13F
https://goo.gl/zpPZHx 這應該是你想知道的問題
03/21 23:34, 13F

03/23 14:46, , 14F
我後來的測試,bot資料夾裡面長這樣
03/23 14:46, 14F

03/23 14:47, , 15F
03/23 14:47, 15F

03/23 14:47, , 16F
我在bot資料夾裡,python tests/unit/test_weather_
03/23 14:47, 16F

03/23 14:48, , 17F
parser.py,而此py檔from ...weather_parser import
03/23 14:48, 17F

03/23 14:49, , 18F
會出現此error ValueError: attempted relative
03/23 14:49, 18F

03/23 14:49, , 19F
import beyond top-level package
03/23 14:49, 19F

03/23 14:49, , 20F
照理說我的sys.path應該是 /unit,那我用...weather_
03/23 14:49, 20F

03/23 14:50, , 21F
parser應該要可以才是…
03/23 14:50, 21F

03/23 21:39, , 22F
執行 python 的 path 才會是 pwd
03/23 21:39, 22F
文章代碼(AID): #1Opuu4EU (Python)
文章代碼(AID): #1Opuu4EU (Python)