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

2015-09-09 16:18:59 +08:00
 MyLeoWind
3840 次点击
所在节点    Python
5 条回复
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
2015-09-09 18:15:18 +08:00
@aisk 感谢!
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 的做法,但不提倡)
julyclyde
2015-09-09 21:13:51 +08:00
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.
"""

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/219406

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX