Skip to content

Instantly share code, notes, and snippets.

@gronnbeck
Created August 29, 2021 17:46
Show Gist options
  • Save gronnbeck/75b4994bd6989fc835e6eab9ab6d5b15 to your computer and use it in GitHub Desktop.
Save gronnbeck/75b4994bd6989fc835e6eab9ab6d5b15 to your computer and use it in GitHub Desktop.
Simple script for monitoring a subprocess and restart it based on string match
import subprocess
import sys
def start_program(program):
proc = subprocess.Popen([program], stdout=subprocess.PIPE)
return proc
def monitor_program(proc, match):
for line in iter(proc.stdout.readline, ''): # replace '' with b'' for Python 3
sys.stdout.write(line)
if match in line:
return 'restart'
return 'shutdown'
def start_and_monitor_program(program, match):
proc = start_program(program)
program_status = monitor_program(proc, match)
return (program_status, proc)
def run(program, match):
status, proc = start_and_monitor_program(program, match)
while status is 'restart':
sys.stdout.write('Restarting program\n')
proc.kill()
status, proc = start_and_monitor_program(program, match)
run('./infinite.sh', '5')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment