0

Example input script

import time
for i in range(5):
    print("LOADING " + str(i))
    time.sleep(1)
for i in range(10):
    print("RUNNING " + str(i))
    time.sleep(1)

Need a way to run launch the script, preferably python 3 subprocess and monitor and print the output continuously and terminate it as soon as it starts printing 'RUNNING', similar to sending CTRL+C in terminal

There are similar solution but nothing seems to be serving this purpose How to terminate a python subprocess launched with shell=True

JKJ
  • 11
  • 2

1 Answers1

0

If you are fine with using pwntools (https://github.com/Gallopsled/pwntools), you could start with the following code:

# pip install pwntools

from pwn import *

# don't print pwntool stuff
context.log_level = 'error'

# start process
proc = process(["python3", "child.py"])

# read line-by-line and print line (until 'RUNNING' is printed)
while not (line := proc.readline()).startswith(b"RUNNING"):
    print(line.decode(), end = "")

# kill process
proc.kill()

# this will be printed (parent is not killed)
print("Parent still running")

This code reads the input line-by-line. If you need to terminate before the full line is read, try proc.read(1) to read a single byte.