Skip to content

Instantly share code, notes, and snippets.

@awesomebytes
Created June 9, 2015 11:00
Show Gist options
  • Select an option

  • Save awesomebytes/37cf1d0b19b4fb179cab to your computer and use it in GitHub Desktop.

Select an option

Save awesomebytes/37cf1d0b19b4fb179cab to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 6/9/15
@author: sampfeiffer
top_subprocess.py contains...
"""
__author__ = 'sampfeiffer'
import subprocess
import threading
import Queue
import time
class AsynchronousFileReader(threading.Thread):
def __init__(self, fd, queue):
assert isinstance(queue, Queue.Queue)
assert callable(fd.readline)
threading.Thread.__init__(self)
self._fd = fd
self._queue = queue
def run(self):
'''The body of the tread: read lines and put them on the queue.'''
for line in iter(self._fd.readline, ''):
self._queue.put(line)
def eof(self):
'''Check whether there is no more content to expect.'''
return not self.is_alive() and self._queue.empty()
if __name__ == '__main__':
command = "top" # your hacky CAN BUS COMMAND (without grep)
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)#, shell=True)
stdout_queue = Queue.Queue()
stdout_reader = AsynchronousFileReader(process.stdout, stdout_queue)
stdout_reader.start()
# Check the queues if we received some output (until there is nothing more to get).
while not stdout_reader.eof():
# Show what we received from standard output.
while not stdout_queue.empty():
line = stdout_queue.get()
if "python" in line: # you do your grep stuff here in python :/
print 'Received line on standard output that contained "python": ' + str(line)
# Sleep a bit before asking the readers again.
time.sleep(.5)
stdout_reader.join()
process.stdout.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment