-
-
Save vchahun/5340937 to your computer and use it in GitHub Desktop.
Quick script to serve a plot of the input via HTTP.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
import argparse | |
import re | |
import pylab | |
import random | |
import socket | |
from StringIO import StringIO | |
from base64 import b64encode | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
page = """<html><head><title>Quick plot</title></head> | |
<body><img src="data:image/png;base64,{}"/></body></html>""" | |
def make_handler(data): | |
data.seek(0) | |
content = page.format(b64encode(data.read())) | |
class ServeFileHandler(BaseHTTPRequestHandler): | |
def do_GET(self): | |
# index.html / plot.png | |
if self.path == '/': | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
self.wfile.write(content) | |
else: | |
self.send_error(404, 'Invalid path') | |
def log_message(self, fmt, *args): | |
pass | |
return ServeFileHandler | |
def read_data(pattern): | |
pattern_re = re.compile((pattern or '')+'([-+]?\d*\.?\d*([eE][-+]?\d+)?)') | |
for line in sys.stdin: | |
m = pattern_re.search(line) | |
if m: | |
yield float(m.group(1)) | |
def main(): | |
parser = argparse.ArgumentParser(description='Quick plot') | |
parser.add_argument('pattern', help='Will match {pattern}{number}', nargs='?') | |
args = parser.parse_args() | |
y = list(read_data(args.pattern)) | |
if len(y) == 0: | |
sys.stderr.write('No data found\n') | |
sys.exit(1) | |
pylab.plot(y) | |
img_data = StringIO() | |
pylab.savefig(img_data) | |
host = socket.gethostname() | |
port = random.randint(1000, 10000) | |
server = HTTPServer((host, port), make_handler(img_data)) | |
print('http://{}:{} -- found {} values'.format(host, port, len(y))) | |
try: | |
server.serve_forever() | |
except KeyboardInterrupt: | |
pass | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment