Skip to content

Instantly share code, notes, and snippets.

@ryankurte
Last active August 29, 2015 14:15
Show Gist options
  • Save ryankurte/7394a53931067cabb748 to your computer and use it in GitHub Desktop.
Save ryankurte/7394a53931067cabb748 to your computer and use it in GitHub Desktop.
Automatic color serial terminal
#!/usr/bin/python
#
# Color serial terminal
# Looks for the terms "error", "warning", "info" on each line and applies
# color if they are recognized.
# Additionally allows recognition of a regular expression passed into the function
import serial;
import argparse;
import subprocess;
import re;
import sys;
import signal;
from time import gmtime, strftime;
from termcolor import colored;
#Parse input argument
parser = argparse.ArgumentParser(description='Monitor and interact with a serial port');
parser.add_argument('port', type=str, help='serial port');
parser.add_argument('baud', type=str, help='baud rate');
parser.add_argument('--filter', type=str, help='regex filter to match');
parser.add_argument('--file', type=str, help='file to write serial data to');
args = parser.parse_args();
#Create and open serial port
port = serial.Serial(args.port, args.baud);
#Prepare expressions
regex_error = re.compile("error", re.IGNORECASE);
regex_warning = re.compile("warning", re.IGNORECASE);
regex_info = re.compile("info", re.IGNORECASE);
if args.filter:
regex_custom = re.compile(args.filter, re.IGNORECASE);
#Connect to file
if args.file:
f = open(args.file, 'w+');
else:
f = None;
#Setup signal handler
def signal_handler(signal, frame):
print "Exiting";
if f:
f.close();
port.close();
sys.exit(0);
signal.signal(signal.SIGINT, signal_handler);
running = True;
while(running):
data = port.readline();
if data:
#Append time
data = strftime("%Y-%m-%d %H:%M:%S] ") + data;
#Write to file
if f:
f.write(data);
f.flush();
#Strip newlines for terminal display
data = data.replace('\n', '').replace('\r', '');
#Match expressions for syntax highlighting
regex = regex_error.match(data);
if regex:
print colored(data, 'red', attrs=['bold']);
print '\a'
continue;
regex = regex_warning.match(data);
if regex:
print colored(data, 'yellow');
continue;
regex = regex_info.match(data);
if regex:
print colored(data, 'green');
continue;
if args.filter:
regex = regex_custom.match(data);
if regex:
print colored(data, 'magenta');
continue;
print colored(data, 'blue');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment