'Run tail command as background process in Python [duplicate]

I have file named test.py and I am trying to run below command as a background process as part of this script

"tail -n0 -f debug.log" 

Also, I want this process to end as soon as test.py execution is completed. However, I can't get this to working. I have tried below code but tail command not exiting even after main script is completed. I am new Python, can someone help me do this clean way ?

pro = subprocess.Popen(["tail", "-n0", "-f", log_file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in pro.stdout:
    print(line)
os.killpg(os.getpgid(pro.pid), signal.SIGTERM)


Solution 1:[1]

I used it once before, so I can't remember exactly, but I think I exiting 'subprocess.Popen' using 'with'. I'm not sure, but I recommend giving it a try.

with subprocess.Popen(["tail", "-n0", "-f", log_file], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as pro:
    for line in pro.stdout:
        print(line)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Desty