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

import os 和 import os.path 的效果有什么不同?

  •  
  •   MyLeoWind · 2015-09-09 16:18:59 +08:00 via Android · 3824 次点击
    这是一个创建于 3151 天前的主题,其中的信息可能已经有所发展或是发生改变。
    5 条回复    2015-09-10 00:23:39 +08:00
    aisk
        1
    aisk  
       2015-09-09 17:06:42 +08:00
    效果一样,这点是 os 模块做了 hack ,所以上面两种 import ,都可以用 `os.path.xxx` 。

    不做 hack 的模块,比如这样的结构:

    ```
    a
    ├── __init__.py
    └── b.py
    ```

    就只能 `import a.b` ,或者 `from a import b` 来访问 b 模块的内容,而不能只 `import a` 然后 `a.b.xxx`。
    MyLeoWind
        2
    MyLeoWind  
    OP
       2015-09-09 18:15:18 +08:00 via Android
    @aisk 感谢!
    julyclyde
        3
    julyclyde  
       2015-09-09 21:09:41 +08:00
    os.path 比较特殊:
    1 import os 后可以直接使用 os.path 这个不稀罕,因为 import os 的时候,它已经把 path 放到了自己的__all__里,作为 exported symbol 了
    2 可以直接 import os.path 但需要注意的是 os 并不是一个 package 。这里利用了 python 的两个漏洞: 1 它并不严格区分 package 和 module ,所以会先尝试 import os 然后再判断 os.path 是否成功加载; 2 为了让它以为 os.path 成功加载, os 在 sys.modules 里加入了一项名为 os.path 的元素,作弊

    另外,根据 os.path 的注释,正确的做法是 import os 然后使用 os.path ,而不是直接 import os.path (虽然标准库和文档也有 import os.path 的做法,但不提倡)
    PythonAnswer
        5
    PythonAnswer  
       2015-09-10 00:23:39 +08:00
    os.path 是个 hack

    win 下导入的是 ntpath.py

    # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
    """Common pathname manipulations, WindowsNT/95 version.

    Instead of importing this module directly, import os and refer to this
    module as os.path.
    """

    *nix 下是 posixpath.py

    """Common operations on Posix pathnames.

    Instead of importing this module directly, import os and refer to
    this module as os.path. The "os.path" name is an alias for this
    module on Posix systems; on other systems (e.g. Mac, Windows ),
    os.path provides the same operations in a manner specific to that
    platform, and is an alias to another module (e.g. macpath, ntpath ).

    Some of this can actually be useful on non-Posix systems too, e.g.
    for manipulation of the pathname component of URLs.
    """
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5559 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 03:06 · PVG 11:06 · LAX 20:06 · JFK 23:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.