html tool

2014年6月3日星期二

goagent_local源码阅读_main()_II:os.chdir(os.path.dirname(os.path.abspath(__file__)))

os.chdir(os.path.dirname(os.path.abspath(__file__)))

  •        1.os.path.dirname()
    os.path.dirname(path)
    Return the directory name of pathname path. This is the first half of the pair returned by split(path).
    测试了一下,在windows中如果路径不用\\转义head,tail的分割会出现问题,参见如下lab结果
    >>> print os.path.dirname("F:\pc\work\个人中心\分析\1.txt")
    F:\pc\work\个人中心
    >>> print os.path.dirname("F:\\pc\\work\\个人中心\\分析\\1.txt")
    F:\pc\work\个人中心\分析
    >>> print os.path.dirname("D:\My Documents\AppScan\1.txt") #不包含中文
    D:\My Documents
    >>> print os.path.dirname("D:\\My Documents\\AppScan\\1.txt")
    D:\My Documents\AppScan
    • help 对 split()的解释为:
      os.path.split(path)
      Split the pathname path into a pair, (head,  tail) where tail is the last pathname component and head is everything leading up to that. The tail  part will never contain a slash; if path ends in a slash, tail  will be empty. If there is no slash in path, head  will be empty. If path is empty, both head and tail  are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path  (the only exception being when there were multiple slashes separating head from tail).
      这样看来应该是用最后一个反斜杠来划分head,tail的,查一下源码看看如何实现的:
      • 先查到os,发现如下定义:
        - os.path is one of the modules posixpath, or ntpath
        再查posixpath.py 中如下:
        def split(p):
            """Split a pathname.  Returns tuple "(head, tail)" where "tail" is
            everything after the final slash.  Either part may be empty."""
            i = p.rfind('/') + 1
            head, tail = p[:i], p[i:]
            if head and head != '/'*len(head):
                head = head.rstrip('/')
            return head, tail
        help这个str.rfind()为:
        str.rfind(sub[, start[, end]])
        Return the highest index in the string where substring sub  is found, such that sub is contained within s[start,end]. Optional arguments start and end  are interpreted as in slice notation. Return -1  on failure
        实验了一下如下:
        >>> x="F:\pc\work\个人中心\分析\1.txt"
        >>> a=x.rfind("\\")
        >>> a=a+1
        >>> print x[:a]
        F:\pc\work\个人中心\
        >>> print x[a:]
        分析.txt

        ok了,像自己猜测的一样了,str.rfind()返回了最大的匹配位置,而 head, tail = p[:i], p[i:] 的写法就是用这个位置直接分割字符了,但是这个 if head and head != '/'*len(head): 应该是处理head为空,即当前目录的文件,问题是head != '/'*len(head) 是什么呢?[next]
        def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" i = p.rfind('/') + 1 head, tail = p[:i], p[i:] if head and head != '/'*len(head): head = head.rstrip('/') return head, tail
    2.os.chdir()  

没有评论:

发表评论