Simple query request with Wolfram api

Wolfram Alpha is really a good website if you want to perform some computation or ask some basic query like “distance between Paris and London”.So I wanted to test out Wolfram API (alpha)
The following program gets a query from the user and retrieves a result. Ofcourse, you will need an app id which could be got from website.

import sys
import urllib2
import urllib
import httplib
from xml.etree import ElementTree as etree

class wolfram(object):
    def __init__(self, appid):
        self.appid = appid
        self.base_url = ''
        self.headers = {'User-Agent':None}

    def _get_xml(self, ip):
        url_params = {'input':ip, 'appid':self.appid}
        data = urllib.urlencode(url_params)
        req = urllib2.Request(self.base_url, data, self.headers)
        xml = urllib2.urlopen(req).read()
        return xml

    def _xmlparser(self, xml):
        data_dics = {}
        tree = etree.fromstring(xml)
        #retrieving every tag with label 'plaintext'
        for e in tree.findall('pod'):
            for item in [ef for ef in list(e) if ef.tag=='subpod']:
                for it in [i for i in list(item) if i.tag=='plaintext']:
                    if it.tag=='plaintext':
                        data_dics[e.get('title')] = it.text
        return data_dics

    def search(self, ip):
        xml = self._get_xml(ip)
        result_dics = self._xmlparser(xml)
        #return result_dics 
        #print result_dics
        print result_dics['Result']

if __name__ == "__main__":
    appid = sys.argv[1]
    query = sys.argv[2]
    w = wolfram(appid)


This particular module to be included in PyTI is one of the most important part in the architecture. Even though the main goal of vmanager is to manage the vms, there are other secondary goals like getting the data from the virtual hard disk on to the host and viceversa . Even though it is designed with PyTI in mind, I guess it can work out pretty good for the rest of the projects(except the ones which requires networking) which plan to manage VirtualMachines. Ofcourse some tinkering has to be done to cater the project needs.

I will just illustrate with a simple example to start, save the state(snapshot), rollback and stopping the virtual box.

from vms import *
config = {'name': 'test123', 'memory':'123', \
              'disk_location': 'dsl-4.4.10.iso', \
              'hd_location': 'disk.vdi'}
a = VirtualMachine('hey', "vbox:///session", config=config) 
a.createSnapshot('hello', 'blah')

It is pretty clear from the above examples , each of the operations performed. Since vmanager uses libvirt library, it wont be difficult to migrate to other hypervisors if ever the need arises.

For reading the virtual hard disk , I wrote a diskhandler code , which uses libguestfs library .

A small illustration for mounting the disk , uploading and downloading data from and to the host machine

from diskhandler import *
d = DiskOperations('/home/yeswanth/a.vdi')
d.upload("/home/yeswanth/a.txt", "/root/a.txt")"/root/b.txt", "/home/yeswanth/b.txt")

Fore extensive read on vmanager or PyTI , please do read our documentation

Fun with VirtualMachines

Over the last one week , all I did was play with Virtual Machines. The tests on the distributions will happen over a Virtual Machine . So its very important that we can control these VMs with a script.

Candidate : VirtualBox
Operating System : Damn Small Linux
Virtual Hard disk : A VDI image of 2.5 GB
RAM: 256 MB
Library: used libvirt to control the virtual machines
Features tested: Start, Stop, Snapshot, Rollback

Using libvirt was nice. It supports a range of hypervisors to be controlled with the same library, though I had my fair share of difficulties especially with the documentation.

Another feature I worked on this week is mounting the virtual hard disk image on the host. I used libguestfs library to achieve this. The features I have added for PyTI for now are
uploading and downloading files from and to the virtual hard disk on to the host machine.

Would really thank Alexis, one of my mentor for his help in giving me feedback , refactoring my code and testing it .

PyTI (PyPI Testing Infrastructure) – My Gsoc Proposal

Project Overview

The goal of the project is to test distributions from PyPI repository to assess
quality and also to check if a distribution is malicious or not . In order to
achieve that we create a testing infrastructure for PyPI repository. There will
be a mechanism to get newly uploaded distributions from PyPI , install them in
an isolated VM environment , run tests on them (quality check , unittests) and
also determine tests they have harmful components(malicious) or not. The
project can be divided into two parts , one(environment) to subscribe to
uploaded packages,set up the environment and the other one(execution) to run
the tests and report the results back(to the environment part).

Detailed work

This project can be divided into two components : one is execution part and
another is environment part . Since each of these two parts are comprehensible
enough on its own, each will be handled by a single student. Execution part
takes cares of installing the distributions(to be tested) along with their
dependencies , run tests on these distributions and assess different quality
parameters. Tests may include unittests, or quality tests(like pep8,pylint) or
custom tests to check if the program is malicious or not .

Environment part of the project

This proposal concerns the environment part. The environment part of the
project is responsible for creating an abstraction for the execution part . It
handles delivery of distributions (and its dependencies), to the execution part
( to run tests on them). It handles all the protocols required to communicate
to the PyPI repository and also to the different architecture used in the
project. It subscribes to uploaded packages from PyPI for testing them (testing
done by the execution part). It is also responisible for setting up the
environment required for testing and to deliver the packages to the execution
part for testing them .


  • Raw data: the data generated by tasks execution.
  • Report: evaluation of the different features/attributes of the data.
  • Task : execution which produce raw data and "output". eg build, install,
    unittest, pylint…


  • Master – Slave architecture where the master dispatches jobs to the slave and
    the slave executes them.
  • The communication between master and slave happen through an API called
    command API
  • The slave communicates with the vm , sends the distributions require for testing
    and receive raw data (after installing the distributions and conducting tests)
    using another API called raw data API
  • Tests are run on VMs and each VM is handled by a slave

Raw Data API

  • The task is to build a raw data API for the communication between the VM and
  • The raw data API handles sending the data into the corresponding VMs.
  • The raw data API also handles the raw data (after the execution part has finished)
    on VM to be sent to the slave

Command API

  • The task is to build a command API to communicate between the Master and the
    Slave .
  • The command API handles the task requests issued by the Master to and
    assigns them to the slave.
  • Task requests can involve different configurations to be made on a VM,
    what distributions to be tested,etc.


  • For both the API I propose the use of XML format or json format for creating the API as I
    think both can be used easily and both have good support.


The slave performs the following tasks

  • Initialises an isolated VM and configures the VM using the configuration
    provided by the API call to it.
  • It should be able to communicate with PyPI repository and get the
    distributions to be tested.
  • Gets the distribution to be tested from the repository , computes
    dependencies and also gets the dependencies from the repository.
  • Passes all the packages to the VM.
  • Receive the raw data from the VM.


  • The slave is required to differentiate between the different VMs and also
    have a track of the activities happening with each of the VMs.
  • The slave intializes and configures the VM by making an API call to it.
  • When the packages are sent into the VM , they can be stored in a folder
    and the execution part can keep polling into the folder to see if any package
    has been received to start testing.


  • Master subscribes to uploaded packages in PyPI
  • It dispatches jobs to the Slave using command API
  • It receives the test results from the slave


  • Inorder to subscribe packages from PyPI , we can use pubhubsubbub protocol to
    get real time feed as and when a package has been uploaded.

Example scenario

  1. Developer uploads his distribution on pypi. (External)
  2. Pypi notifies PYTI(Here the master gets notified). (Environment)
  3. Master asks a slave(local or remote machine) to test a distribution
    using command API.(Environment)
  4. Slave computes the dependencies for the distribution(to be tested) and
    downloads the distribution(to be tested) along with the dependencies from
    the repository. (Execution)
  5. Slave starts a VM with settings as instructed by the Master (Environment)
  6. When the VM has started,the slave sends distribution(along with the
    dependencies) into the VM.(Environment)
  7. Inside the VM , the distribution is installed and different tests are
    conducted on it (unittests, quality check ,etc) (Execution)
  8. At the end, raw data(data obtained by testing) is sent to slave. (Execution)
  9. Slave sends raw data to master. (Environment)
  10. Then slave shutdown the VM and cleans it. (Environment)

Gsoc 2011

I am excited to publish this blog that I have been selected for Gsoc 2011 .

Dear yeswanth,

Congratulations! Your proposal “PyTI(PyPI Testing Infrastructure)” as submitted to “Python Software Foundation” has been accepted for Google Summer of Code 2011.

The overall details are given here PyTI
We will be two students working on this project me and Feld Boris. We will be collaborating our work during the summer.

I will be blogging about my progress regularly as I am working with it .

Pyti Infrastructure

Not been blogging in a while , but I guess I should blog more about what I am doing these days , mostly working on my Gsoc Project proposal .

Here is what I learnt after a lot discussions in the mailing list and talking to different people about the idea.

The idea goes somewhat like this :

Basically there are lot of packages in the PyPI (python packaging index) repository and it is open to everyone. So the community had decided to implement a PyTI (Python Testing Infrastructure) to test the packages which a user want to download .

The course of the project somewhat goes like this :

1) The user requests a test on a package which he wants to download.
2) Using a feed/notifier , we can schedule a init() call to a virtual manager (in this case Amazon EC2 is the most prefered option)
3) The virtual manager boots the os and then cleans up the environment for testing .
4) The packages are installed with their dependencies
5) Tests are conducted on these packages which include
1. Test suite (If it is already present )
2. pep8,pylint,maccabe
3. custom tests
6) The vm is shutdown after cleaning up the environment
7) A qa is done and the user is notified of the results

Input audio from microphone

Today I learnt how to input audio directly from the microphone
It requires two packages alsaaudio and audioop if its not already present .

import alsaaudio, time, audioop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples


while True:
	# Read data from device
	l,data =
	if l:
		print audioop.max(data, 2)

The code will print the audio as data on the screen . Try shouting and you will find the difference. You can probably store it in a .wav file .