forked from dilligencer-zrj/code_zoo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils
66 lines (50 loc) · 1.49 KB
/
utils
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import os
import errno
import sys
import utils
def mkdir_if_missing(directory):
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as e:
if e.error != errno.EEXIST:
raise
class Logger(object):
'''
Write console output to external text file.
usage:
sys.stdout = utils.Logger(
os.path.join(save_dir, 'log_train-%s.txt' % time.strftime("%Y-%m-%d-%H-%M-%S")))
'''
def __init__(self, fpath=None):
self.console = sys.stdout
self.file = None
if fpath is not None:
mkdir_if_missing(os.path,dirname(fpath))
self.file = open(fpath,'w')
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
self.close()
def write(self,mag):
self.console.write(msg)
if self.file is not NOne:
self.file.write(msg)
def flush(self):
self.console.flush()
if self.file is not None:
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
self.console.close()
if self.file is not None:
self.file.close()
if use_gpu:
state_dict = model.module.state_dict()
else:
state_dict = model.state_dict()
def save_checkpoint(state,fpath='checkpoint.pth.tar'):
mkdir_if_missing(os.path.dirname(fpath))
torch.save(state,fpath)