Skip to content

Instantly share code, notes, and snippets.

@fearofcode
Last active August 26, 2018 11:07
Show Gist options
  • Save fearofcode/02599c31269ac34100cd6a0554048c53 to your computer and use it in GitHub Desktop.
Save fearofcode/02599c31269ac34100cd6a0554048c53 to your computer and use it in GitHub Desktop.
Evaluate a Python file and pipe it to stdout in a hot reload loop
import sys
import io
import traceback
import socketserver
class EvaluationHandler(socketserver.BaseRequestHandler):
def handle(self):
while True:
path = self.request.recv(2048).strip()
if path == b"warmup":
self.request.sendall(bytes("OK\n", "utf-8"))
else:
old_stdout = sys.stdout
sys.stdout = io.StringIO()
old_stderr = sys.stderr
sys.stderr = io.StringIO()
did_error = False
try:
exec(open(path).read())
except Exception:
traceback.print_exc()
did_error = True
out = sys.stdout.getvalue()
sys.stdout = old_stdout
err = sys.stderr.getvalue()
sys.stderr = old_stderr
if did_error:
self.request.sendall(bytes(err + "\n", "utf-8"))
else:
self.request.sendall(bytes(out + "\n", "utf-8"))
if __name__ == "__main__":
HOST, PORT = "localhost", 50051
with socketserver.TCPServer((HOST, PORT), EvaluationHandler) as server:
server.serve_forever()
using System.IO;
using static System.Console;
using System.Net.Sockets;
namespace filesystemwatchertest
{
class Program
{
static System.Object fileWatch = new System.Object();
static System.DateTime lastEventRaised;
static StreamWriter sw;
static StreamReader sr;
static void Main(string[] args)
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("localhost", 50051);
NetworkStream networkStream = tcpClient.GetStream();
sr = new StreamReader(networkStream);
sw = new StreamWriter(networkStream);
var fileSystemWatcher = new FileSystemWatcher(@"C:\Users\Warren\Downloads\watch_test\", "*.py");
fileSystemWatcher.Changed += FileSystemWatcher_Changed;
fileSystemWatcher.EnableRaisingEvents = true;
ReadLine();
}
private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
lock (fileWatch)
{
System.DateTime now = System.DateTime.Now;
if (now.Subtract(lastEventRaised).TotalMilliseconds >= 250)
{
sw.WriteLine(e.FullPath + "\n");
sw.Flush();
string line;
do
{
line = sr.ReadLine();
if (line == null || line.Length == 0)
{
break;
}
WriteLine(line);
} while (true);
}
lastEventRaised = now;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment