I want to make a subprocess(writer.py) that keeps adding "test" to a file('20180309.txt') every second and maintain the subprocess with another python process(starter.py).
It works fine, but one thing that bothers me is that the file object
is not closed before terminating the subprocess. I'd like to know if there's a way to close the file object when the subprocess recieves terminate() signal, or if there are other ways to handle this problem.
#starter.py
import os
import sys
import subprocess
p1 = subprocess.Popen( ["d:\python36-32\python.exe", r"""writer.py"""], shell=False )
print(p1.pid)
try:
p1.communicate(timeout=5)
except subprocess.TimeoutExpired:
p1.terminate()
#writer.py
import time
from datetime import datetime
file = open( datetime.now().strftime('%Y-%m-%d') + '.txt', 'a')
while True:
file.write('test\n')
file.flush()
time.sleep(1)