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
1989922yan
V2EX  ›  Python

[相对导入]

  •  
  •   1989922yan · 2014-06-23 17:48:47 +08:00 · 4321 次点击
    这是一个创建于 3607 天前的主题,其中的信息可能已经有所发展或是发生改变。
    .
    ├── h
    │   ├── __init__.py
    │   └── out.py
    ├── hh
    │   ├── __init__.py
    │   └── test.py
    ├── __init__.py
    └── test.py


    我有这样的目录结构,

    # h/out.py
    from ..test import h

    h()

    # test.py
    #coding=utf8

    def h():
    print 'hllo'

    _---------------

    我在 test.py目录,执行 python h/out.py

    Traceback (most recent call last):
    File "h/out.py", line 1, in <module>
    from ..hh import test
    ValueError: Attempted relative import in non-package


    ----------------

    这是 相对导入啊,这个怎么处理呢?
    6 条回复    2014-06-25 17:31:00 +08:00
    TankyWoo
        1
    TankyWoo  
       2014-06-23 18:33:13 +08:00   ❤️ 1
    » tree pack
    pack
    ├── h
    │   ├── __init__.py
    │   └── out.py
    ├── __init__.py
    └── test.py

    1 directory, 4 files

    » python -m pack.h.out
    hello
    cj1324
        2
    cj1324  
       2014-06-23 20:58:49 +08:00
    不推荐相对导入。。
    wynemo
        3
    wynemo  
       2014-06-23 21:21:53 +08:00
    直接运行包里的东西 比如这样 python h/out.py 会报“Attempted relative import in non-package”
    而这样 python -m h.out 会报"Attempted relative import beyond toplevel package"
    真要跑就照一楼这样跑吧。。。
    要把整个这一坨当成一个包 才能用relative import
    1989922yan
        4
    1989922yan  
    OP
       2014-06-25 17:29:41 +08:00
    @TankyWoo
    赞,这是个好办法
    1989922yan
        5
    1989922yan  
    OP
       2014-06-25 17:30:09 +08:00
    @cj1324

    显示相对导入 ,还是可以容忍的
    1989922yan
        6
    1989922yan  
    OP
       2014-06-25 17:31:00 +08:00
    @wynemo
    嗯的~~
    已经照一楼完成,不过,总感觉有些失落。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4050 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.