Python os.path is ntpath, how?

2019-06-18 02:23发布

Can someone tell me how Python "aliases" os.path to ntpath?

>>> import os.path
>>> os.path
<module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'>
>>>

2条回答
在下西门庆
2楼-- · 2019-06-18 02:49

Look at os.py, lines 55-67:

elif 'nt' in _names:
    name = 'nt'
    linesep = '\r\n'
    from nt import *
    try:
        from nt import _exit
    except ImportError:
        pass
    import ntpath as path

    import nt
    __all__.extend(_get_exports_list(nt))
    del nt

The import ntpath as path is the specific statement that causes os.path to be ntpath on your platforms (doubtlessly Windows).

查看更多
We Are One
3楼-- · 2019-06-18 02:51
>>> import os as my_aliased_module
>>> my_aliased_module
<module 'os' from 'C:\Program Files\Python 2.6\lib\os.pyc'>

EDIT: And since import is a simple statement in Python, you can do neat stuff like:

import sys

if sys.platform == 'win32':
  import windows_module as my_module
else:
  import unix_module as my_module
查看更多
登录 后发表回答