'Kill subprocess started by imported module

I have a call_script.py:

def call():
    pro = subprocess.Popen(['make_batches.py'])
    with open('call.pid', 'w') as file:
        file.write(str(pro.pid))
    file.close()
    pro.wait()

def main():
    call()

if __name__ == '__main__':
    main()

and a main_script.py:

import call_script
from pathlib import Path

def main():
    call.main()
    path = Path.cwd()
    pid = path.glob('**/call.pid')
    if criteria_met:
         #KILL PROCESS

main()

The call_script.py is producing batches every 5 min and so I need to wait for those but once criteria_met is True in main_script.py I would like to kill the process defined in call.pid, however main_script.py will not continue past call.main() since it's waiting



Solution 1:[1]

You need to call pro.wait in a nonblock way. Try with pro.wait(timeout=1) or some timeout suits you. Then check in a upper loop wait for 'criteria_met' or the subprocess.TimeoutExpired exception for normal exit.

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