今天刚下载了github上的源码运行测试了一下detect.py文件 比较好奇他的文件夹怎么一直自增的。
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
我们可以看到 路径的输出是通过colorstr函数来进行组合的 可以看到参数是可变参数,参数的含义包括了字体的各种格式字体的颜色,以及文件保存的路径。
*args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
colors = {
'black': '\033[30m', # basic colors
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'magenta': '\033[35m',
'cyan': '\033[36m',
'white': '\033[37m',
'bright_black': '\033[90m', # bright colors
'bright_red': '\033[91m',
'bright_green': '\033[92m',
'bright_yellow': '\033[93m',
'bright_blue': '\033[94m',
'bright_magenta': '\033[95m',
'bright_cyan': '\033[96m',
'bright_white': '\033[97m',
'end': '\033[0m', # misc
'bold': '\033[1m',
'underline': '\033[4m'}
return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
把传入的参数分为两个部分,一组字体格式另一组为存储路径字符串。然后进行一个字符串的组合。
那么关于文件路径save_dir的组合是由以下函数来完成
def increment_path(path, exist_ok=False, sep='', mkdir=False):
# Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
path = Path(path) # os-agnostic
if path.exists() and not exist_ok:
path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')
# Method 1
for n in range(2, 9999):
p = f'{path}{sep}{n}{suffix}' # increment path
if not os.path.exists(p): #
break
path = Path(p)
# Method 2 (deprecated)
# dirs = glob.glob(f"{path}{sep}*") # similar paths
# matches = [re.search(rf"{path.stem}{sep}(\d+)", d) for d in dirs]
# i = [int(m.groups()[0]) for m in matches if m] # indices
# n = max(i) + 1 if i else 2 # increment number
# path = Path(f"{path}{sep}{n}{suffix}") # increment path
if mkdir:
path.mkdir(parents=True, exist_ok=True) # make directory
return path
循环2~9999个后缀分别判断p路径是否存在如果不存在就满足我们创建的要求就跳出循环并将这个路径返回。
p 由
path:传入的参数在组成为项目路径拼接上我们自定义数据存储的文件夹源码中命名为exp 。
seq:默认为空根据拼接可以看作是一些标志类似 _ 等命名格式的符号。
n:for循环的数字
suffix:文件后缀 因为这里是文件夹所以为空
组成