Delete log file if it is empty after being closed

2019-05-26 07:10发布

I have a library function that launches a generic background process and logs it.

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)

Main question: Is it possible to revise this function so that upon the log file being closed, if it is empty it is deleted automatically?

Note: I want a solution where I can call this function and forget it. I don't want to have to remember to call a cleanup function every time after the job ends.

(Rejected?) Idea: I can use threading to launch a separate thread that monitors the process and/or log file, but this seems more complicated than necessary.

Note: Must work in Python 2.7, but I'm also interested in a Python 3 solution, if it's simpler.

1条回答
你好瞎i
2楼-- · 2019-05-26 07:40

Try reversing the concept, and only create the file when you're ready to write. Create your own class to handle the file object:

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()

Then your with statement becomes this:

with MyFile(logfile) as log:

Proposed but rejected edit from supergra manually incorporated

查看更多
登录 后发表回答