【Python测试】unittest源码解析三----loader.py之_get_name_from_path(self, path)

    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 allbecome A/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 that root+ 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值