py2exe无法从其他目录导入模块
我将 python 源代码与 py2exe 捆绑在一起。目录结构如下:
some_Mod.py
some_dir/another_dir/some_Mod.py
在后者 some_dir/another_dir/some_Mod.py 中,我尝试导入其他 Python 模块,
from ..some_Mod import *
使用导入不会导致 python 解释器出现问题,但如果我在捆绑包中运行相同的星座,我遇到异常:
ImportError: No module named some_Mod
有人可以解释为什么吗?
备注:重命名模块实际上没有问题,但我只是想知道,为什么 py2exe 不能处理这个星座。
I am bundling python source code with py2exe. The directory structure is as follows:
some_Mod.py
some_dir/another_dir/some_Mod.py
Inside the latter some_dir/another_dir/some_Mod.py I am trying to import the other Python Module with
from ..some_Mod import *
Using the import causes no problems with the python interpreter, but if I run the same constellation in the bundled package, I get an Exception:
ImportError: No module named some_Mod
Can somebody explain why?
Remark: Renaming the Modules is actually no problem, but I was just wondering, why py2exe cannot deal with this constellation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果每个子目录中都有
__init__.py
文件,那么所有导入语句都应该正常工作。假设这不是问题,这里有一个导入最佳实践的优秀指南:
http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/
总之,永远不要使用相对导入 - 始终是绝对的(请参阅上面的链接了解原因)。
其次(我不完全确定为什么),始终将 py2exe setup.py 脚本保存在主脚本所在的确切文件夹中。我尝试修改 py2exe 的“脚本”选项以允许我的脚本位于其他地方......但你的确切问题发生在我身上。因此,请尝试确保它位于主脚本所在的位置。
最后,你总是可以给 py2exe 一点帮助。我通常必须将根目录添加到系统路径中,以便导入语句有效。请注意,我没有修改任何应用程序代码中的
sys.path
- 仅修改我用来构建 exe 的 py2exe 脚本。在我的 py2exe 设置脚本的顶部:
不过,通常我不导入包,在它们通常存在的位置添加项目根就足够了。
If you have
__init__.py
files in each of those sub-directories then all import statements should work correctly.Assuming that's not the problem, here's an excellent guide to importing best practices:
http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/
In summary, never use relative imports - always absolute (see the link above for why).
Second (and I'm not entirely sure why), always keep your py2exe setup.py script in the exact folder where your main script is. I've tried modifying py2exe's 'script' option to allow my script to be somewhere else... but your exact problem happened to me. So, try making sure it is right where the main script is.
Finally, you can always give py2exe a little help. I usually have to add the root directory to the system path so the import statements are valid. Note, I'm not modifying
sys.path
in any of my application's code - only the py2exe script I use to build the exe.At the top of my py2exe setup script:
Generally I don't import packages though, adding the project root where they exist usually is enough.
我不确定 py2exe 现在如何处理
from ..some_Mod import *
语法,请检查此以确保 some_Mod.py 模块正确打包:python -m py2exe.mf -d some_dir/another_dir/some_Mod.py
如 py2exe 常见问题中所述I'm not sure that py2exe now how to handle the
from ..some_Mod import *
syntax, check this to ensure that the some_Mod.py module is correctly packaged :python -m py2exe.mf -d some_dir/another_dir/some_Mod.py
as explained in the py2exe FAQ