0

I want to invoke infinite loop script from parent code.

from subprocess import Popen
import subprocess
import os
import sys
proc=subprocess.Popen([sys.executable, os.getcwd()+'/A.py'],shell=False, stdout=subprocess.PIPE)
print(proc.communicate())
print('Hi')

and my script is:

import time

def main():
    while True:
        print('HI2')
        time.sleep(3)
if __name__ == '__main__':
    main()`

but it does not work and does Popen block the script. I mean that why print('Hi') syntax does not work.

Peter Badida
  • 11,310
  • 10
  • 44
  • 90

1 Answers1

1

proc.communitcate() waits for proc to finish. It then returns the output from the subprocess.

In this example out is the output printed on stdout and err the output on stderr:

out, err = proc.communicate()

If you don't need the output, simple skip the communicate().

Peter Gerber
  • 1,023
  • 10
  • 13
  • Would you tell me how to terminate infinite child subprocess? – Veria Hoseini Mar 11 '17 at 21:49
  • You should be able to use `proc.terminate()`for that – Peter Gerber Mar 11 '17 at 21:54
  • Thank you for your answer. E subprocess invoke script, and within each script there are multiprocess. While I terminate parent process(I mean closing the script) the children process are still alive!!! – Veria Hoseini Mar 17 '17 at 12:57
  • How do you close the script? Let it run till it terminates by itself? Or do you use something like CTRL + C? – Peter Gerber Mar 17 '17 at 13:46
  • If you want to have child processes automatically terminated, take a look at [this question](https://stackoverflow.com/questions/1884941/killing-the-children-with-the-parent) – Peter Gerber Mar 17 '17 at 13:56