Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Breaking subprocess loop from parent process
#1
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)
Quote
#2
Use signals instead of sending a text to stdin.
https://docs.python.org/2/library/subpro...end_signal
Quote
#3
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.
Quote
#4
@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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  (Python help) Change in logic not breaking 'while' loop? btcg2807 1 87 Sep-18-2019, 09:43 AM
Last Post: Larz60+
  How to sharing object between multiple process from main process using Pipe Subrata 1 292 Sep-03-2019, 09:49 PM
Last Post: woooee
  logging: child module unable to get parent config jerryxiao 3 347 Apr-09-2019, 04:17 AM
Last Post: jerryxiao
  breaking even if conditions is not met Naito 5 629 Feb-03-2019, 12:30 PM
Last Post: perfringo
  parent/add and child/div PyMan 1 497 Feb-23-2018, 04:38 PM
Last Post: nilamo
  Breaking down long function LucasLambert 2 1,222 Mar-30-2017, 06:09 AM
Last Post: LucasLambert

Forum Jump:


Users browsing this thread: 1 Guest(s)