python unittest源码解析三----loader.py之_get_name_from_path(self, path)

来源:互联网 发布:耳机声音放大器软件 编辑:程序博客网 时间:2024/06/01 08:55
    def _get_name_from_path(self, path):        path = os.path.splitext(os.path.normpath(path))[0]        _relpath = os.path.relpath(path, self._top_level_dir)        assert not os.path.isabs(_relpath), "Path must be within the project"        assert not _relpath.startswith('..'), "Path must be within the project"        name = _relpath.replace(os.path.sep, '.')        return name

这个方法一开始先对传入的路径进行正常的格式化,使用os.path.normpath,官方注释:

os.path.normpath(path)

Normalize a pathname by collapsing redundant separators and up-levelreferences so thatA//B,A/B/, A/./B andA/foo/../B allbecomeA/B. This string manipulation may change the meaning of a paththat contains symbolic links. On Windows, it converts forward slashes tobackward slashes. To normalize case, usenormcase().

就是把路径中多余的'/',句点'.'去掉,确保路径格式的正确。


os.path.splitext(path)

Split the pathname path into a pair (root,ext) such thatroot+ext ==path, andext is empty or begins with a period and contains at most oneperiod. Leading periods on the basename are ignored;splitext('.cshrc')returns('.cshrc','').

splitext可以把文件的路径名和后缀文件格式名分成两部分返回,比如test.py,就会被分为('test', '.py')


os.path.relpath(path[,start])

Return a relative filepath to path either from the current directory orfrom an optionalstart directory. This is a path computation: thefilesystem is not accessed to confirm the existence or nature ofpath orstart.

relpath用来确定相对路径的path,返回一个filepath


str.replace(old,new[,count])

Return a copy of the string with all occurrences of substring old replaced bynew. If the optional argument count is given, only the firstcountoccurrences are replaced.

上面那个方法最后使用replace把路径分隔符'/',替换成句点'.'。

0 0
原创粉丝点击