Skip to content

Instantly share code, notes, and snippets.

@matutter
Created June 20, 2014 03:37
Show Gist options
  • Select an option

  • Save matutter/b1423bb3e5598c3f21f8 to your computer and use it in GitHub Desktop.

Select an option

Save matutter/b1423bb3e5598c3f21f8 to your computer and use it in GitHub Desktop.
a process utility for logging and restarting apps.
import subprocess
import select
import time
import sys
#no-nonsense python utility for app testing
#pythons subprocess class is really weird...
class pMonitor:
pM_proc = False
pM_path = False
pM_log = False
pM_rept = False
def __init__(self, path, persist, log ):
self.pM_path = path
self.pM_log = log
self.pM_rept = persist
if log:
print '[] creating logfile ' + log
self.pM_log = open(log,'w')
def start(self):
self.pM_proc = subprocess.Popen(self.pM_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = []
stderr = []
while True:
Queu = [self.pM_proc.stdout.fileno(),self.pM_proc.stderr.fileno()]
Next = select.select(Queu, [], [])
for it in Next[0]:
if it == self.pM_proc.stdout.fileno():
line = self.pM_proc.stdout.readline()
if self.pM_log:
self.pM_log.write(time.strftime("%I_%M") + ':' + line )
sys.stdout.write( 'out: ' + line )
stdout.append(line)
if it == self.pM_proc.stderr.fileno():
line = self.pM_proc.stderr.readline()
if self.pM_log:
self.pM_log.write(time.strftime("%I_%M") + ':' + line )
sys.stdout.write( 'err: ' + line )
stdout.append(line)
if self.pM_proc.poll() != None:
break
print self.pM_path + ' exited '
print '[] persistence %r' % self.pM_rept
if self.pM_rept:
print '[] restarting...'
self.start()
def end(self):
self.pM_proc.kill()
def start_example():
Log = 'LOG_' + time.strftime("%I_%M_%S")
proc = pMonitor( './a.out', True, Log )
try:
proc.start()
except KeyboardInterrupt:
print '[] process over'
proc.end()
start_example()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment