作者rebellionyu (Rebellionyu)
看板Python
标题[问题] 资料夹结构问题
时间Mon Mar 20 16:08:33 2017
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://webptt.com/cn.aspx?n=bbs/Python/M.1489997316.A.39E.html
1F:→ uranusjr: 一般会把测试和你的主要程式平行放, 你的例子应该是和 03/20 17:28
2F:→ uranusjr: bot 同一层; 不知道你怎麽执行 unit test, 但通常会写成 03/20 17:29
3F:→ uranusjr: import bot.weatherParser.weather 03/20 17:30
4F:→ zerof: from bot import ... ,在 bot/ 执行 03/20 18:22
5F:→ rebellionyu: 我刚刚测试了一下,放在tests/unit/test.py, 03/20 18:34
6F:→ rebellionyu: 要用python -m unittest tests.unit.test 跑 03/20 18:35
7F:→ rebellionyu: 而test.py只要from weatherParser import weather 03/20 18:35
8F:→ rebellionyu: 但如果直接跑 python ./tests/unit/test.py 就不行 03/20 18:36
9F:→ rebellionyu: 会说找不到weatherParser这个module 03/20 18:36
10F:→ s860134: 你资料夹每一层都要有 __init__.py 03/21 23:14
11F:→ s860134: import 搜寻是看 sys.path,根据你执行方式会改变 03/21 23:32
12F:→ s860134: python ./tests/unit/test.py 他 sys.path 就会在 \unit 03/21 23:33
14F:→ rebellionyu: 我後来的测试,bot资料夹里面长这样 03/23 14:46
16F:→ rebellionyu: 我在bot资料夹里,python tests/unit/test_weather_ 03/23 14:47
17F:→ rebellionyu: parser.py,而此py档from ...weather_parser import 03/23 14:48
18F:→ rebellionyu: 会出现此error ValueError: attempted relative 03/23 14:49
19F:→ rebellionyu: import beyond top-level package 03/23 14:49
20F:→ rebellionyu: 照理说我的sys.path应该是 /unit,那我用...weather_ 03/23 14:49
21F:→ rebellionyu: parser应该要可以才是… 03/23 14:50
22F:→ zerof: 执行 python 的 path 才会是 pwd 03/23 21:39