简单整理一下一些常用函数,方便自己查阅。
目录
文件操作
文件夹/目录
文件
数据格式
链表
类
特殊函数
一些常用函数
常用库
tqdm进度条库
tqdm模块参数说明
常用函数使用方法
yacs参数配置库
简介
使用方法
logging日志库
使用方法
文件操作
文件夹/目录
import os
1、os.path.exists(path) 判断一个文件/目录是否存在,只要存在相匹配的文件或目录就返回True,因此当目录与文件同名时可能报错
2、os.path.isdir(fname) 判断目录是否存在,必须是目录才返回True
3、os.makedirs(path) 多层创建目录
4、os.mkdir(path) 创建目录
5、os.rmdir(path) 删除目录,只能删除空目录
6、os.rename(原文件名,新文件名) 重命名文件或文件夹
注意:makedirs与mkdir之间最大的区别是当父目录不存在的时候os.mkdir(path)不会创建,os.makedirs(path)则会创建父目录。
文件
1、os.remove(path) 删除文件
2、os.rename(原文件名,新文件名) 重命名文件或文件夹
3、os.listdir(path) 提取目录下所有文件
4、os.path.isfile(fname) 判断文件是否存在,必须是文件才返回True
5、random.sample(file_list, n) 从file_list中随机选择n个文件–import random
6、copyfile(src_path, dst_path) 将src文件内容复制到dst文件中–from shutil import copyfile
7、copy(src_path, dst_path) 将src文件复制到dst文件夹中–from shutil import copy
8、move(src_path, dst_path) 将src文件剪切到dst文件夹—from shutil import move
9、dst=os.path.join(path,”../for_bitmain/”+img) 修改文件路径
10、str.endswith(suffix[, start[, end]]) 判断字符串是否以指定后缀结尾或指定字符串,如果以指定后缀结尾返回True,否则返回False。可选参数”start”与”end”为检索字符串的开始与结束位置。
数据格式
链表
1、len(list) 长度
2、max(list) 最大值
3、min(list) 最小值
4、del(list)/del(list[i]) 删除链表或某一个元素
5、list.append(obj) 插入元素
6、list.count(obj) 统计某个元素出现的次数
7、list.pop([index = -1]) 移除一个元素,并返回其值,默认是最后一个
8、list.sort() 排序
9、list.clear() 清除
10、list.copy() 复制
类
特殊函数
__init__()
等同于类的构造器,初始化某个类的一个实例。
__del__()
等同于类的析构函数,析构某个类的一个实例。
__call__()
使实例能够像函数一样被调用,同时不影响实例本身的生命周期(__call__()
不影响一个实例的构造和析构)。但是__call__()
可以用来改变实例的内部成员的值。
- class X(object):
- def __init__(self, a, b, range):
- self.a = a
- self.b = b
- self.range = range
- def __del__(self, a, b, range):
- del self.a
- del self.b
- del self.range
- def __call__(self, a, b):
- self.a = a
- self.b = b
- print('__call__ with ({}, {})'.format(self.a, self.b))
-
-
- >>> xInstance = X(1, 2, 3)
- >>> xInstance(1,2)
- __call__ with (1, 2)
- >>> del X
一些常用函数
1、enumerate(sequence, [start=0])
为可迭代的序列添加了一个计数器默认从0开始
- elements = ('foo', 'bar', 'baz')
- >>> for elem in elements:
- ... print elem
- ...
- foo
- bar
- baz
- >>> for count, elem in enumerate(elements):
- ... print count, elem
- ...
- 0 foo
- 1 bar
- 2 baz
- >>> for count, elem in enumerate(elements, 42):
- ... print count, elem
- ...
- 42 foo
- 43 bar
- 44 baz
2、 ‘sep’.join(seq)
seq:分隔符,可以为空
seq:要连接的元素序列、字符串、元组、字典
连接字符串数组。将字符串、元组、列表中的元素以指定的分隔符连接生成一个新的字符串。
- #对序列进行操作(分别使用' '与':'作为分隔符)
- >>> seq1 = ['hello','good','boy','doiido']
- >>> print(' '.join(seq1))
- hello good boy doiido
- >>> print(':'.join(seq1))
- hello:good:boy:doiido
-
-
- #对字符串进行操作
- >>> seq2 = "hello good boy doiido"
- >>> print(':'.join(seq2))
- h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o
-
- #对元组进行操作
- >>> seq3 = ('hello','good','boy','doiido')
- >>> print(':'.join(seq3))
- hello:good:boy:doiido
-
- #对字典进行操作
- >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
- >>> print(':'.join(seq4))
- boy:good:doiido:hello
常用库
tqdm进度条库
tqdm模块参数说明
- class tqdm(object):
- """
- Decorate an iterable object, returning an iterator which acts exactly
- like the original iterable, but prints a dynamically updating
- progressbar every time a value is requested.
- """
-
- def __init__(self, iterable=None, desc=None, total=None, leave=False,
- file=sys.stderr, ncols=None, mininterval=0.1,
- maxinterval=10.0, miniters=None, ascii=None,
- disable=False, unit='it', unit_scale=False,
- dynamic_ncols=False, smoothing=0.3, nested=False,
- bar_format=None, initial=0, gui=False):
- iterable: 可迭代的对象, 在手动更新时不需要进行设置
- desc: 字符串, 左边进度条描述文字
- total: 总的项目数
- leave: bool值, 迭代完成后是否保留进度条
- file: 输出指向位置, 默认是终端, 一般不需要设置
- ncols: 调整进度条宽度, 默认是根据环境自动调节长度, 如果设置为0, 就没有进度条, 只有输出的信息
- unit: 描述处理项目的文字, 默认是’it’, 例如: 100 it/s, 处理照片的话设置为’img’ ,则为 100 img/s
- unit_scale: 自动根据国际标准进行项目处理速度单位的换算, 例如 100000 it/s >> 100k it/s
常用函数使用方法
1.tqdm(iterator)
基于迭代器运行:
- import time
- from tqdm import tqdm, trange
-
- #trange(i)是tqdm(range(i))的一种简单写法
- for i in trange(100):
- time.sleep(0.05)
-
- for i in tqdm(range(100), desc='Processing'):
- time.sleep(0.05)
-
- dic = ['a', 'b', 'c', 'd', 'e']
- pbar = tqdm(dic)
- for i in pbar:
- pbar.set_description('Processing '+i)
- time.sleep(0.2)
- 100%|██████████| 100/100 [00:06<00:00, 16.04it/s]
- Processing: 100%|██████████| 100/100 [00:06<00:00, 16.05it/s]
- Processing e: 100%|██████████| 5/5 [00:01<00:00, 4.69it/s]
手动进行更新:
- import time
- from tqdm import tqdm
-
- with tqdm(total=200) as pbar:
- pbar.set_description('Processing:')
- # total表示总的项目, 循环的次数20*10(每次更新数目) = 200(total)
- for i in range(20):
- # 进行动作, 这里是过0.1s
- time.sleep(0.1)
- # 进行进度更新, 这里设置10个
- pbar.update(10)
- Processing:: 100%|██████████| 200/200 [00:02<00:00, 91.94it/s]
yacs参数配置库
简介
yacs是作为一个轻量级库创建的,用于定义和管理系统配置,比如那些通常可以在为科学实验设计的软件中找到的配置。这些“配置”通常包括用于训练机器学习模型的超参数或可配置模型超参数(如卷积神经网络的深度)等概念。由于您正在进行科学研究,所以再现性是最重要的,因此您需要一种可靠的方法来序列化实验配置。
使用方法
1、初始化并赋值
- # my_project/config.py
- from yacs.config import CfgNode as CN
-
-
- _C = CN()
-
- _C.SYSTEM = CN()
- # Number of GPUS to use in the experiment
- _C.SYSTEM.NUM_GPUS = 8
- # Number of workers for doing things
- _C.SYSTEM.NUM_WORKERS = 4
-
- _C.TRAIN = CN()
- # A very important hyperparameter
- _C.TRAIN.HYPERPARAMETER_1 = 0.1
- # The all important scales for the stuff
- _C.TRAIN.SCALES = (2, 4, 8, 16)
-
-
- def get_cfg_defaults():
- """Get a yacs CfgNode object with default values for my_project."""
- # Return a clone so that the defaults will not be altered
- # This is for the "local variable" use pattern
- return _C.clone()
-
- # Alternatively, provide a way to import the defaults as
- # a global singleton:
- # cfg = _C # users can `from config import cfg`
2、解析yaml文件
config.yaml
- GPUS: (0,1,2,3)
- OUTPUT_DIR: 'output'
- CUDNN:
- ENABLED: true
-
- MODEL:
- NAME: 'yolo'
- PRETRAINED: 'xx.pth'
- EXTRA:
- FINAL_CONV_KERNEL: 1
- STAGE2:
- NUM_MODULES: 1
config.py
- import os
-
- from yacs.config import CfgNode as CN
-
- class config():
-
- def __init__(self):
- self.cfg = CN()
-
- self.cfg.GPUS= (0,1,2,3)
- self.cfg.OUTPUT_DIR= 'output'
- self.cfg.CUDNN=CN()
- self.cfg.CUDNN.ENABLED=True
- self.cfg.MODEL=CN()
- self.cfg.MODEL.NAME=''
- self.cfg.MODEL.PRETRAINED=''
- self.cfg.MODEL.EXTRA=CN()
- self.cfg.MODEL.EXTRA.FINAL_CONV_KERNEL=0
-
- self.cfg.MODEL.EXTRA.STAGE2=CN()
- self.cfg.MODEL.EXTRA.STAGE2.NUM_MODULES=0
-
- def get_cfg(self):
- return self.cfg.clone()
-
- def load(self,config_file):
- self.cfg.OUTPUT_DIR = ''
- self.cfg.defrost()
- self.cfg.merge_from_file(config_file)
- self.cfg.freeze()
-
-
- if __name__ == '__main__':
- cc=config()
- cc.load("test.yaml")
- print(cc.cfg)
- print(cc.get_defalut_cfg())
logging日志库
使用方法
1、将控制台的输出写入文件中
- import logging
-
-
- def setLog():
- log_file = 'L:/log/console.log'
- head = '%(asctime)-15s %(message)s'
- logging.basicConfig(filename=str(log_file), format=head)
-
- logger = logging.getLogger()
- logger.setLevel(logging.INFO)
-
- console = logging.StreamHandler()
- logging.getLogger('').addHandler(console)
-
- return logger
-
-
-
- if __name__ == '__main__':
- logger = setLog()
-
- logger.info('input message')
-
-