Python Forum
Breaking subprocess loop from parent process
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)
Reply
#2
Use signals instead of sending a text to stdin.
https://docs.python.org/2/library/subpro...end_signal
Reply
#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.
Reply
#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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ChromeDriver breaking Python script genericusername12414 1 217 Mar-14-2024, 09:39 AM
Last Post: snippsat
  Openpyxl module breaking my code EnderSM 5 985 May-26-2023, 07:26 PM
Last Post: snippsat
  breaking out of nested loops Skaperen 3 1,174 Jul-18-2022, 12:59 AM
Last Post: Skaperen
  How to use += after breaking for loop? Frankduc 2 1,445 Dec-31-2021, 01:23 PM
Last Post: Frankduc
  Run multiple process using subprocess Shiri 3 3,731 Nov-28-2021, 10:58 AM
Last Post: ghoul
  How to fix while loop breaking off raphy11574 3 2,125 Oct-12-2021, 12:56 PM
Last Post: deanhystad
  breaking a large program into functions, not acting as expected Zane217 9 2,932 Sep-18-2021, 12:37 AM
Last Post: Zane217
  Need to run 100+ Chrome’s with Selenium but can’t get past ~15 without breaking imillz 0 1,322 Sep-04-2021, 04:51 PM
Last Post: imillz
Exclamation Help in breaking bytes into bits through masking and shifting kamui123 9 4,435 Jan-11-2021, 07:42 AM
Last Post: kamui123
  How to to tie the execution of one process to another inside a loop in Python ignorant_wanderer 0 2,018 Jul-11-2020, 03:44 AM
Last Post: ignorant_wanderer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020