Home turboPC
Python scripts Python tutorial Bouncing dice Diagram editor LRC network simulation
Qt embedded
OS Bootfloppy Go 64 bits Bochs

Python scripting

Python and Qt script examples

This section contains some scripts exemplifying the use of python and Qt.

Most basic application

This is the simplest PyQt application. Start with this example.
import sys
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.show()
app.exec_()

Get weather from KNMI site

This script retrieves a weathermap of holland as a png and displays it on a QLabel.
from PyQt4 import QtGui
import sys
import httplib

def getTempPNG():
   conn = httplib.HTTPConnection("www.knmi.nl")
   conn.request("GET", "/actueel/images/tempgmt.png")
   return conn.getresponse().read()

def main():
   app = QtGui.QApplication(sys.argv)
   png = getTempPNG()
   pixmap = QtGui.QPixmap()
   pixmap.loadFromData(png)
   label = QtGui.QLabel()
   label.setPixmap(pixmap)
   label.setWindowTitle('Het laatste weer!')
   label.show()
   app.exec_()

if __name__ == '__main__':
   main()

Image of the widget with weather map in it.

openGL widget with Qt

This example is how you can use opengl in a Qt widget.
from OpenGL.GL import *
from OpenGL.GLU import gluPerspective
from PyQt4.QtGui import QApplication
from PyQt4.QtOpenGL import QGLWidget
import sys

class myGLwidget(QGLWidget):
   def __init__(self, parent=None):
      QGLWidget.__init__(self, parent)
   def initializeGL(self):
      glClearColor(0.0, 0.5, 0.0, 1.0)
      glEnable(GL_DEPTH_TEST)
      glDepthFunc(GL_LESS)
      glEnable(GL_DEPTH_TEST)
      glShadeModel(GL_SMOOTH)
   def resizeGL(self,w,h):
      glViewport(0, 0, w, h)
      glMatrixMode(GL_PROJECTION)
      glLoadIdentity()
      gluPerspective(45.0, float(w)/float(h), 0.1, 100.0)
      glMatrixMode(GL_MODELVIEW)
   def paintGL(self):
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
      glLoadIdentity()

app = QApplication(sys.argv)
w = myGLwidget()
w.show()
app.exec_()

Retrieve subtitles from opensubtitles.org

This script downloads subtitles from opensubtitles.org. It has the hash function from opensubtitles.org and downloads this subtitle using xmlrpc.

#!/usr/bin/python
import xmlrpclib, os, struct
import base64, gzip, StringIO
import sys

LANG = 'dut'
AGENT = 'Totem'
USERNAME = ''
PASS = ''

def hashFile(name):
      try:
                longlongformat = 'q'  # long long 
                bytesize = struct.calcsize(longlongformat)
                f = open(name, "rb")
                filesize = os.path.getsize(name)
                hash = filesize
                if filesize < 65536 * 2:
                       print "File is too small"
                       sys.exit(-2)
                for x in range(65536/bytesize):
                        buffer = f.read(bytesize)
                        (l_value,)= struct.unpack(longlongformat, buffer)
                        hash += l_value
                        hash = hash & 0xFFFFFFFFFFFFFFFF #to remain as 64bit number  
                f.seek(max(0,filesize-65536),0)
                for x in range(65536/bytesize):
                        buffer = f.read(bytesize)
                        (l_value,)= struct.unpack(longlongformat, buffer)
                        hash += l_value
                        hash = hash & 0xFFFFFFFFFFFFFFFF
                f.close()
                returnedhash =  "%016x" % hash
                return (filesize, returnedhash)
      except(IOError):
                return "IOError"

if len(sys.argv) < 2:
   print 'Usage: '
   print '    ',sys.argv[0], ' MOVIEFILE '
   sys.exit(-1)
else:
   filename = sys.argv[1]
filesize, hash = hashFile(filename)
s = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc')
r = s.LogIn(USERNAME, PASS, LANG, AGENT)
token = r['token']
searchdata = { 'sublanguageid':LANG, 'moviehash':hash, 'moviebytesize':str(filesize) }
result = s.SearchSubtitles(token, [searchdata])
data = result['data']
if data:
   newdata = sorted(data, key=lambda k: k['SubDownloadsCnt'])
   newdata = filter(lambda k: k['SubFormat'] == 'srt', newdata)
   if len(newdata) == 0:
      print 'No srt subs found'
      sys.exit(-3)
   for d in newdata:
      print d['MovieName'], ' (language: ', d['LanguageName'], ', 
      print downloaded', d['SubDownloadsCnt'], 'times)'
   id = newdata[-1]['IDSubtitleFile']
   targetfilename = filename[:-3]+'srt'
   print 'Downloading sub into ',targetfilename,'...'
   result = s.DownloadSubtitles(token, [id])
   subtitle64 = result['data'][0]['data']
   GzippedFile = gzip.GzipFile(fileobj=StringIO.StringIO(base64.decodestring(subtitle64)))
   f = open(targetfilename, 'wb')
   f.write(GzippedFile.read())
   f.close()
   print 'Done!'
else:
   print 'No subs found'
s.LogOut(token)