V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
tioover
V2EX  ›  Python

基础问题 Python 包导入错误

  •  
  •   tioover ·
    tioover · 2013-08-10 22:17:58 +08:00 · 4454 次点击
    这是一个创建于 3905 天前的主题,其中的信息可能已经有所发展或是发生改变。
    http://segmentfault.com/q/1010000000263255

    这个一直没搞明白……虽然感觉是很小白的问题。
    12 条回复    1970-01-01 08:00:00 +08:00
    thedevil5032
        1
    thedevil5032  
       2013-08-10 22:52:17 +08:00 via iPad
    tioover
        2
    tioover  
    OP
       2013-08-10 23:17:52 +08:00
    @thedevil5032 这样有点丑……
    iEverX
        3
    iEverX  
       2013-08-10 23:52:11 +08:00   ❤️ 1
    python3 a.py,则a.py是最顶级的模块,只能找到b.py以及__init__.py,不知道test是个什么东西,所以。。
    而后面的 from . import b,这种引用,由于a.py是作为__main__的,是不允许的

    http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python
    reorx
        4
    reorx  
       2013-08-11 00:29:41 +08:00   ❤️ 1
    1. segmentfault 中 felix021 和 detailyang 的回答都是错误的(依云的答案是对的),对包内模块的引用使用 from b import c 的形式是绝对错误的,仅有 from .b import c 和 from test.b import c 是正确的。

    2. 之所以没找到 test 包是因为你在 test/ 下运行 a.py,test/ 的确在系统路径中,但 test/ 的上级目录不在,所以 test/ 依然是找不到的。包内模块作为运行入口本就不是好的选择,最佳实践方案应该是单独写一个脚本 from test import a 来做些什么,或者在 test/ 的上级目录运行 python -m test.a,这样将包整个进行调用,避免在包内直接运行。

    2. 看一下 pep 328
    reorx
        5
    reorx  
       2013-08-11 00:32:41 +08:00   ❤️ 3
    补充一点在 test/a.py 中 from b import c 或者 import b 之所以是错的,是因为这样是把 b 当作模块命名空间的顶级,也就是包来调用,而 b 只是 test 包中的模块,因此极为容易引发各种错乱。
    tioover
        6
    tioover  
    OP
       2013-08-11 00:44:54 +08:00
    @reorx
    @iEverX
    感谢!
    reorx
        8
    reorx  
       2013-08-11 11:38:29 +08:00
    @felix021 嗯,不过2和3在包和模块的引用方式这块应该遵循的是同一理念。
    reorx
        9
    reorx  
       2013-08-11 11:42:35 +08:00
    @felix021 竟然是同院校友,震惊泪目!我是09,你是哪一届的?
    felix021
        10
    felix021  
       2013-08-11 22:36:49 +08:00
    @reorx 所以是05级的师兄?我是06级/10届的……
    reorx
        11
    reorx  
       2013-08-11 23:21:52 +08:00
    @felix021 我是09级/13届的……哈哈,你是师兄才对 XD
    felix021
        12
    felix021  
       2013-08-12 08:59:14 +08:00
    @reorx 这么说来我给你们上过课,OJ系统使用的,不过你可能逃课了吧~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2547 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:33 · PVG 23:33 · LAX 08:33 · JFK 11:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.