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

import 同名模块有什么好方法?

  •  
  •   datou552211 · 2014-08-13 11:20:04 +08:00 via iPhone · 6652 次点击
    这是一个创建于 3551 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如我有个叫test.py的脚本,我再它的内部调用import test 但test模块确实存在于site-packages中。在windows中这会默认引用的是test.py==有办法解决嘛
    6 条回复    2014-08-13 15:18:06 +08:00
    dreampuf
        1
    dreampuf  
       2014-08-13 11:58:09 +08:00
    - 尽量避开重名模块
    - 从项目路径导入 from YOURAPP import test
    - 改变 sys.path 顺序
    Zuckonit
        2
    Zuckonit  
       2014-08-13 12:28:01 +08:00
    名字没取好
    可以加上路径
    pyKun
        3
    pyKun  
       2014-08-13 12:48:49 +08:00
    以后不要取这种命
    除了一楼的方法还有
    import ..test 类的写法
    timonwong
        4
    timonwong  
       2014-08-13 12:56:20 +08:00   ❤️ 1
    还有更猥琐的方法
    import imp

    mod = imp.load_source(module_name, fullpath)
    datou552211
        5
    datou552211  
    OP
       2014-08-13 14:14:36 +08:00 via iPhone
    @dreampuf
    @Zuckonit
    @pyKun
    @timonwong
    绝b不是我的本意,维护代码的时候遇到bug了,然后debug了很久,我了个擦。
    dreampuf
        6
    dreampuf  
       2014-08-13 15:18:06 +08:00
    @datou552211 print(module.__file__) 事半功倍
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   794 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 21:07 · PVG 05:07 · LAX 14:07 · JFK 17:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.