[英]python: prevent creating empty files
對於批量任務,我創建了ProgressLog
對象的幾個實例,每個實例都會創建一個空的日志文件,無論是否實際存在任何錯誤。 預防這種情況的最佳方法是什么?
class ProgressLog(object):
"""Write a message to log + progress indicator.
"""
total = 0
def __init__(self, name):
source_path, file_name = os.path.split(name)
self.name = file_name
self.source_path = source_path
self.log_dir_name = r'log'
self.make_log_dir(self.source_path, self.log_dir_name)
self.reset()
log_file = self._logfilename()
try:
self.f = open(log_file, 'w')
print('\n***logging errors to {0}***\n'.format(log_file))
except IOError, err:
msg = 'Cannot open logfile {0}. Traceback is: {1}'.format(
log_file, err)
raise msg
def _logfilename(self):
## hms_ddmmyyyy format
log_name = r'{1}_{0}{2}_errors.csv'.format(
time.strftime("%I%M%S"),
time.strftime("%d%m%Y"),
self.name)
return os.path.join(self.source_path, self.log_dir_name, log_name)
沒有“神奇”的方法,只需重構代碼即可僅在第一次實際調用log時打開日志文件。
為此,請將__init__
的一部分打開日志文件,並將其_open_log
壓縮到單獨的_open_log
方法中。 在__init__
self.f
初始化為None
。 然后,您的實際記錄方法可以開始於:
if self.f is None:
self._open_log()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.