为什么我每个目录下都加了__init__.py 还是一直报 no module name **

2016-10-13 18:31:30 +08:00
 crytis

** 是我自己的代码. 跟代码有关系吗?需要贴代码吗

4728 次点击
所在节点    Python
13 条回复
Chyroc
2016-10-13 19:00:15 +08:00
贴代码
crytis
2016-10-13 20:26:07 +08:00
# coding=utf-8

import sys
import xml.etree.cElementTree as ET

from flask import Flask, request

from src import RedPacketsService
from src.lib.WXBizMsgCrypt import WXBizMsgCrypt
from src.WXUtils import WXUtils

app = Flask(__name__)
wxutils = WXUtils()


@app.route('/auth', methods=["GET", "POST"])
def auth():
pass


if __name__ == '__main__':
try:
app.run(host="0.0.0.0", port=8080)
except IOError:
print "error"

@Chyroc
crytis
2016-10-13 20:26:54 +08:00
@Chyroc 这是目录结构
├─.idea
│ └─inspectionProfiles
├─lib
├─py
│ └─model
├─sql
└─src
├─lib
└─model
crytis
2016-10-13 20:27:29 +08:00
python src\Weixin.py


Traceback (most recent call last):
File "src\Weixin.py", line 8, in <module>
from src import RedPacketsService
ImportError: No module named src
eric6356
2016-10-13 20:29:55 +08:00
建议你研究一下 python import 的时候都会从哪些地方 import
crytis
2016-10-13 20:46:24 +08:00
@eric6356 sys.path append 了也不行
crytis
2016-10-13 20:46:54 +08:00
但是为什么在 pycharm 里运行就没有问题
KingsWay
2016-10-14 00:59:49 +08:00
我也发现过这个问题,一般情况是,直接命令行里运行最外层的那个 python 文件,就没问题。
如果进入某个子目录执行某个文件,就会报和你一样的错误。
应该是 python 代码里引入自定义包的相对路径问题。

最后一个提示:使用 ipython 运行就不会遇到这个问题
zhibin
2016-10-14 10:50:21 +08:00
我遇到过,你这样:
import sys
print sys.path

然后你就明白了,参考:

https://docs.python.org/2/tutorial/modules.html

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

the directory containing the input script (or the current directory).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
the installation-dependent default.

btw:
你 append 怎么写的? append src 上一级的绝对或相对路径 应该是没问题的。
crytis
2016-10-14 15:48:59 +08:00
@zhibin 解决了 困扰了一天啊 好不智能 append 了包的上一级目录就行了 唉
NxnXgpuPSfsIT
2016-10-16 22:47:44 +08:00
@crytis 你的主文件入口是需要在包里面还是在包外面?
crytis
2016-10-17 00:36:34 +08:00
@NxnXgpuPSfsIT 包里面
NxnXgpuPSfsIT
2016-10-17 07:44:04 +08:00
如果我没有理解错的话,是在 src 包里的一个文件作为主入口,调用另一个 src 包里的文件了。
那直接用相对引用就可以了, import .RedPacketsService
如果需要调用的是 lib 里的东西,那么这样, import ..lib.somefile.py
如果目录层数更多,建议做成包从外部调用。
例如现在整个 lib 是个只从外部调用的包,那么 lib/d1/d2/d3/file.py 就可以这样调用 lib/somefile.py , import lib.somefile

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/312577

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX