Skip to content
This repository has been archived by the owner on Aug 19, 2021. It is now read-only.
flying-sheep edited this page Jan 18, 2012 · 4 revisions

I’m currently working on PyRepl. Since many of my project never see the light of the day, i present you the approach and skeleton of it: The finished project would have many convenience functions built around the js function.

import sys, re
from telnetlib import Telnet

class Mozrepl(object):
	def __init__(self, ip="127.0.0.1", port=4242):
		self.ip = ip
		self.port = port
		self.prompt = b"repl>"
	
	def __enter__(self):
		self.t = Telnet(self.ip, self.port)
		intro = self.t.read_until(self.prompt, 1)
		if not intro.endswith(self.prompt):
			self.prompt = re.search(br"repl\d+>", intro).group(0)
			print("Waited due to nonstandard prompt:", self.prompt.decode())
		return self
	
	def __exit__(self, type, value, traceback):
		self.t.close()
		del self.t
	
	def js(self, command):
		self.t.write(command.encode() + b"\n")
		return self.t.read_until(self.prompt).decode()

Usage

You can use the with statement to create a telnet connection like this:

with Mozrepl() as mozrepl:
	print(mozrepl.js("repl.whereAmI()"))

alternatively, use the connection machanism manually:

mozrepl = Mozrepl().__enter__()

print(mozrepl.js("getPageUrl()"))

mozrepl.__exit__()

TODO

  • create new telnet sessions via __enter__ and __exit__ that can be used in parallel
  • expose repl’s functions in the Mozrepl class by parsing the output of inspect and doc