Hopefully I’ll stick with this project through to the end.
Category: python
Basic Twisted echo server
Nothing mind blowing here. I’m playing with Python’s twisted engine, and here is a slightly modified server from their home page example:
from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): newdata = 'reversed: ' + ''.join(reversed(data.strip())) + 'n' self.transport.write(newdata) class EchoFactory(protocol.Factory): #build an Echo object for each connection def buildProtocol(self, addr): return Echo() reactor.listenTCP(8000, EchoFactory()) #register a callback reactor.run()
Run the script and telnet to port 8000 of this box. This is what it looks like:
Connected to erdos. Escape character is '^]'. hello reversed: olleh reverse this! reversed: !siht esrever
The example is also here, with a more detailed explanation of the basics.
The API reference helps to see what methods need to be implemented while sub-classing one of its classes.
Python for day-to-day tasks: the webbrowser module
An initiative at work requires me to analyze a large spreadsheet of data. One of the columns contains a csv-separated list of bugs that I need to take a look at. Normally, this would be a painful job of copying each defect and pasting it in the browser repeatedly. When hundreds of rows needed analysis, each involving multiple defect IDs, I switched to python to ease my pain.
I knew where to look because of this cute easter-egg in python:
import antigravity
The help text for this module led me to the library, c:python33libantigravity.py in my case. The webbrowser module imported here showed how easy it is to launch a browser tab by passing a URL from python:
import webbrowser
import hashlib
webbrowser.open(“http://xkcd.com/353/”)
This was all I need for my job as well. I wrote a 10 line script that basically:
- asked the user for input (in my case a comma separated list of defects),
- converted the input to a list and stripped unneeded whitespace,
- iterated through this list and appended the defect ID to the base URL, and
- called the webbrowser module to open the tabs.
The resulting script looks like this:
import webbrowser
bugs=input(‘Paste the list of bugs:n’)
buglist=bugs.split(‘,’)
for i,x in enumerate(buglist):
buglist[i]=x.strip()
for i in buglist:
url=”+i+”
webbrowser.open(url)
And that’s it! A half-dozen tabs open immediately and I can move on to analyzing them. Python has proved to be a boon in my daily job for quick and dirty scripts like this.
Turtle Power
Thanks to this great website, I’ve been having some more fun with Python. I’m now in the chapter on Recursion, which introduces Python’s Turtle module. Turtle is an implementation of Logo, a language I remember playing with happily in my younger years. What you can do with it in Python is quite amazing sometimes. There are some demo scripts that come pre-installed, and can be accessed this way:
python -m turtledemo
I’ve still not wrapped my head around the more complex ones, but the Sierpinski example in the tutorial is a nice start. I learned from their example and wrote my own (fairly similar) version. The result looks pretty nice:
A couple of weeks back I wouldn’t have been able to come up with something like this at all, so I’m pretty happy with what I’ve learned so far.
Below is the script. Just pasting it in a python3 prompt should suffice.
import turtle def drawTriangle(points, color, t): t.fillcolor(color) t.penup() t.goto(points[0][0],points[0][1]) t.pendown() t.begin_fill() t.goto(points[1][0],points[1][1]) t.goto(points[2][0],points[2][1]) t.goto(points[0][0],points[0][1]) t.end_fill() def findMid(p1,p2): return( (p1[0]+p2[0])/2, (p1[1]+p2[1])/2 ) def sierpinski(points,depth,t): colormap=['purple2','tomato2','khaki3','gold','orchid','spring green','turquoise'] drawTriangle(points,colormap[depth-1],t) if depth>1: sierpinski([points[0],findMid(points[0],points[1]), findMid(points[0],points[2])],depth-1,t) sierpinski([points[1],findMid(points[1],points[2]), findMid(points[0],points[1])],depth-1,t) sierpinski([points[2],findMid(points[2],points[0]), findMid(points[2],points[1])],depth-1,t) def main(): t = turtle.Turtle() myWin = turtle.Screen() t.speed(0) points=[[-300,-150],[0,150],[300,-150]] sierpinski(points,6,t) t.hideturtle() myWin.exitonclick() main()
Flask trial run on PythonAnywhere
I felt it was about time I got into the web development side of Python, having learned enough of it to be dangerous. Since I moved my site to a PaaS, I wanted a quick and dirty alternative Python host that was easy to set up and use. Enter PythonAnywhere. This seemed to fit my immediate needs, as the site provides web-based bash, python and ipython shells for free users. They support both Python 2 and 3, so I went with the latter.
Next up, Flask. Their quickstart tutorial was what I used as a baseline. It seemed easier to start with than heavier alternatives like Django. Although the tutorial covers a minimal blog, I was able to make enough tweaks to it to get what I wanted.
Finally, a purpose. My wife is about a month away from delivering our first baby (oh let it be a girl, please :) ), so I decided to make a simple site where the two of us could enter names that we wanted, for both genders. Each entry is equivalent to a blog post in the Flask tutorial, so the underlying code remained largely the same. It was easy enough to add the rest of the parts I needed. Here then is what it ended up looking like, and here’s a screenshot if I end up taking down the site later:
PythonAnywhere turned out to be a great experience. The founders were friendly enough to exchange a couple of mails directly, which was a fresh change from the noreply@website.com welcome mails that other sites favour. Getting the site up from my local test setup was a simple matter of ftp’ing a tar file over and extracting it.
Overall it took me less than half a day to get everything up, and another few hours of tweaking to add cute pictures and stuff.
Fetch unique words in a web page (in 7 lines of Python)
I got a chance to enroll for some Python training at work and had a nice time with it. I’ve tried getting into other languages myself before, and this has been my freshest experience so far. The three days of training were enough to show me how insanely easy it is to get productive in Python.
A quick example we saw was to:
- Get the contents of a web page, and
- Find all the unique words in it.


