2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

This does not quite work as written. It needs an __enter__ function and the __exit__ function needs to accept 4 arguments, not 1. See here for an edit: stackoverflow.com/review/suggested-edits/3772114 which was helpfully rejected by the SO goons.
Sorry, one more problem I've run into. You need to define a fileno() function in the class. I did this: def fileno(self): if self.file_object: return self.file_object.fileno() else: return None. Perhaps there's a better way.
@user2066480, __exit__() calls close(). can't edit that out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.