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.
Try reversing the concept, and only create the file when you're ready to write. Create your own class to handle the file object:
Then your
with
statement becomes this:Proposed but rejected edit from supergra manually incorporated