python-os

作者: KillerManA | 来源:发表于2016-08-23 11:41 被阅读103次

    python的os模块经常用到,我们进入os的源码,看看模块的构造过程,便于扩展思路。
    1.进入模块先会看到模块引入的一些限制:

    __all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep",           "defpath", "name", "path", "devnull",           "SEEK_SET", "SEEK_CUR", "SEEK_END"]
    

    2.接着就是跨平台适配

    if 'posix' in _names:
        name = 'posix'
        linesep = '\n'
        from posix import *
        try:
            from posix import _exit
        except ImportError:
            pass
        import posixpath as path
    
        import posix
        __all__.extend(_get_exports_list(posix))
        del posix
    
    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
    

    代码只是粘贴部分内容共参考,这里可以看到在不同平台中,path将被分配成对应平台的path
    这为下面的应用提供了方便。

    2.下面开始函数部分:
    makedirs

    def makedirs(name, mode=0777):
        """makedirs(path [, mode=0777])
    
        Super-mkdir; create a leaf directory and all intermediate ones.
        Works like mkdir, except that any intermediate path segment (not
        just the rightmost) will be created if it does not exist.  This is
        recursive.
    
        """
        head, tail = path.split(name)
        if not tail:
            head, tail = path.split(head)
        if head and tail and not path.exists(head):
            try:
                makedirs(head, mode)
            except OSError, e:
                # be happy if someone already created the path
                if e.errno != errno.EEXIST:
                    raise
            if tail == curdir:           # xxx/newdir/. exists if xxx/newdir exists
                return
        mkdir(name, mode)
    

    这个函数里面使用了递归创建,创建目录到最后一层时返回。至于怎么创建目录的,看了半天也没看出来,应该是调用了windows系统的函数。

    walk

    def walk(top, topdown=True, onerror=None, followlinks=False):
        """
        Example:
        import os
        from os.path import join, getsize
        for root, dirs, files in os.walk('python/Lib/email'):
            print root, "consumes",
            print sum([getsize(join(root, name)) for name in files]),
            print "bytes in", len(files), "non-directory files"
            if 'CVS' in dirs:
                dirs.remove('CVS')  # don't visit CVS directories
    
        """
    
        islink, join, isdir = path.islink, path.join, path.isdir
        try:
            # Note that listdir and error are globals in this module due
            # to earlier import-*.
            names = listdir(top)
        except error, err:
            if onerror is not None:
                onerror(err)
            return
    
        dirs, nondirs = [], []
        for name in names:
            if isdir(join(top, name)):
                dirs.append(name)
            else:
                nondirs.append(name)
    
        if topdown:
            yield top, dirs, nondirs
        for name in dirs:
            new_path = join(top, name)
            if followlinks or not islink(new_path):
                for x in walk(new_path, topdown, onerror, followlinks):
                    yield x
        if not topdown:
            yield top, dirs, nondirs
    

    这里可以看出,walk函数也是利用递归来进行目录和文件的分类,并且利用yield生成一个迭代器,便于我们对每一层文件的操作。
    其它的函数操作基本类似,这里就不过多解释,想看源码的童鞋可以下一个PyCharm然后直接点击就能看,比较方便。

    这里还有个疑问,os.py里面并没有提供那么多的方法,但是我们在zeal(查看各种框架的内容的工具,强烈推荐)中看到os有特别多的方法,这其实是开头我们看到的平台适配的时候,将针对不同平台封装的方法添加到了all里面,这是我们就可以直接调用方法,比如在windows平台时,os将nt.py(windows平台对应的封装)里面的所有方法导入进来,

    os.chdir()
    

    如我们直接点击chdir函数,会发现源码目录在nt.py里面,这就是os将nt的函数全部导入的作用。

    相关文章

      网友评论

          本文标题:python-os

          本文链接:https://www.haomeiwen.com/subject/nvggsttx.html