Python Forum

Full Version: Breaking subprocess loop from parent process
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
What is missing here to read the sent value into my_input and break the loop in tok2.py? Now it runs forever.

Using Debian 10 Buster with Python 3.7.

# tok1.py

import sys
import time
import subprocess

command = [sys.executable, 'tok2.py']
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

i=0
while proc.poll() is None:
    if i > 5:
        #Send BreakLoop after 5th iteration
        proc.stdin.write(b'exit')
        
    print('tok1: '  + str(i))

    time.sleep(0.5)
    i=i+1
#tok2.py

import sys
import time

ii=0
my_input =''

while True:
    my_input = sys.stdin.read()
    
    if my_input == b'exit':
        print('tok2: exiting')
        sys.stdout.flush()
        break
  
    print('tok2: ' + str(ii))
    sys.stdout.flush()
    ii=ii+1    
    
    time.sleep(0.5)
Use signals instead of sending a text to stdin.
https://docs.python.org/2/library/subpro...end_signal
The problem is that sys.stdin.read() tries to read the whole contents of the input stream. This call will block until you close the stdin. You need to send lines instead, so use proc.stdin.write("exit\n".encode()), then sys.stdin.readline() to read a single line of input.
@Gribouillis: Thats it, now it works. Thanks!

@fishhook: Python will run inside an os process started within a Lazarus free pascal application. To communicate with the python, I think pipes must be used. Signals are probably not possible.