我有一个库函数,用于启动通用后台进程并记录它。
def LaunchAndLog(cmd):
cmd_args = cmd.split() # Split arguments into array
logfile = cmd_args[0] + '.log'
with open(logfile,'w') as log:
return subprocess.Popen(cmd_args, stdout=log,stderr=log)
主要问题:是否可以修改此功能,以便在日志文件关闭时如果为空,它会自动删除?
注意:我想要一个解决方案,我可以调用此函数并忘记它。我不想记得每次工作结束后都要调用清理功能。
(已拒绝?)想法:我可以使用threading
启动一个监视进程和/或日志文件的单独线程,但这似乎比必要的更复杂。
注意:必须在Python 2.7中运行,但如果它更简单,我也对Python 3解决方案感兴趣。
答案 0 :(得分:3)
尝试颠倒概念,只在准备写入时创建文件。创建自己的类来处理文件对象:
class MyFile():
def __enter__(self):
return self
def __init__(self, path):
''' store the path, but don't actually open the file '''
self.path = path
self.file_object = None
def write(self, s):
''' you open the file here, just before writing '''
if not self.file_object:
self.file_object = open(self.path, 'w')
self.file_object.write(self, s)
def close(self):
''' close the file '''
if self.file_object:
self.file_object.close()
def __exit__(self, exc_type, exc_value, exc_traceback):
self.close()
然后您的with
语句变为:
with MyFile(logfile) as log:
从supergra手动合并
建议但拒绝编辑