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
lcj2class
V2EX  ›  Python

分享个 python 模块导入的坑

  •  
  •   lcj2class · 2016-08-02 17:27:16 +08:00 · 2887 次点击
    这是一个创建于 2795 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 标准库里面有个名叫 select 的 module ,所以如果你的项目里面也有个叫select.py的文件,那么可怕的事就发生了。

    我的情况是没直接 import select,而是import subprocesssubprocess 里面引用了select,可见这个问题还是比较隐蔽的,希望大家不要遇到。

    EVIL demo

    $ cat select.py
    
    import subprocess as sp
    
    sp.call('ls')
    
    $ python select.py
    

    SO 上有很多类似的问题,这里是一例

    8 条回复    2016-08-02 22:29:04 +08:00
    ayaseangle
        1
    ayaseangle  
       2016-08-02 17:30:00 +08:00
    这坑基本都会遇到几次,然后就免疫了。。
    GeekGao
        2
    GeekGao  
       2016-08-02 17:37:30 +08:00
    记得 celery 也是 >_<
    zhizhongzhiwai
        3
    zhizhongzhiwai  
       2016-08-02 18:28:49 +08:00
    这就是相对路径导入的好处: from . import module
    argsno
        4
    argsno  
       2016-08-02 18:50:25 +08:00
    这怎么处理?
    slysly759
        5
    slysly759  
       2016-08-02 20:17:43 +08:00
    没事命名别那么大众化啦
    billlee
        6
    billlee  
       2016-08-02 21:42:05 +08:00
    python 的正确使用姿势:

    MyProject
    |- __init__.py
    |- select.py
    `- __main__.py

    python -m MyProject
    Ge4Los
        7
    Ge4Los  
       2016-08-02 22:17:52 +08:00
    如果还有个 select/__init__.py 的文件夹,也会坑到。
    julyclyde
        8
    julyclyde  
       2016-08-02 22:29:04 +08:00
    cgi.py 飘过……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5333 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:27 · PVG 15:27 · LAX 00:27 · JFK 03:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.