Calling C functions inside Python
January 25, 2009
In my current work, I’m developing new ways to test a Telecom framework. Firstly, I was building automation tests with cgreen to blackbox/unit test model. But the development stages were going a little more slow than I thought because write and debug C code is not so easy.
Suddenly, I though…”Hey, why do I not build these tests with python scripts ???”. And my response was: “Ctypes is your friend!”
Ctypes permits you call C functions inside python code. It’s wonderful. Let’s see how to do it in OpenSolaris environment:
First, download ctypes:
$ wget -c \ http://ufpr.dl.sourceforge.net/sourceforge/ctypes/ctypes-1.0.2.tar.gz
Install ctypes in a local path (as normal user):
$ tar -zxvf ctypes-1.0.2.tar.gz
$ cd ctypes-1.0.2
$ python setup.py install --prefix=$HOME/python
Export your PYTHONPATH environment variable:
$ export PYTHONPATH=$HOME/python/lib/python2.4/site-packages
Testing ctypes:
$ python
>>> import ctypes
OK ! Ctypes is there, but how do I use it ???
See a little example that I made to explain how to use ctypes:
- A file named test.c with a function (sum) that returns a sum of two values:
int sum (int a, int b)
{
return (a+b);
}
- Compile it as a shared library:
$ gcc -fPIC -c test.c
$ gcc -shared -o test.o libtest.so
- Make sure that our library will be found
$ cp test.so $HOME/example
$ export LD_LIBRARY_PATH=$HOME/example
- Let’s call the function sum through a Python script
$ python
>>> from ctypes import *
>>> cdll.LoadLibrary('libtest.so')
<CDLL 'libtest.so', handle fe7806e0 at 80dfcec>
>>> libc = CDLL('libtest.so')
>>> libc.sum()
112710980
>>> libc.sum(1,2)
3
I can see a smile in your face. Yeah! Ctypes is a great trick to C programmers
Enjoy it!
Useful links:
- http://docs.python.org/library/ctypes.html

Decompiling Python Bytecodes
October 16, 2008
Oh no ! I lost my python source code !!! And now ?
You can use an online Python Bytecode Decompiler (DePython) made by Team509, a chinese group (I guess).
Recently, I received this tip/trick site by Python-Brasil mailing list.
Online Decompiler: http://www.depython.net/
Author(s): http://www.team509.com/
Viewing your Net-Vírtua Consumption
September 6, 2008
Last month, I received an email saying that I had consumed 80% of my link quota 2 weeks earlier to end the month.
It’s boring to have to access the page at Net-Vírtua site to view your monthly consumption. To facilitate this work, I made a simple Python script:
#!/usr/bin/python
import urllib
import urllib2
import datetime
import re
class Virtua():
__virtua_url = "http://consumo.virtua.com.br/"
__virtua_action = "consumo.php"
def __init__(self):
pass
def __prettyfy(self,html):
separator = '\n ------------- ------ '
preformatted = separator + '\n'
preformatted += '| date | GB |'
preformatted += separator
regex_space = re.compile('\s+')
regex_date = re.compile('<TD CLASS="bg_azulT azul b onze" nowrap>')
regex_cons = re.compile('<TD CLASS="bg_cinza azulE onze">')
regex_cell = re.compile('</TD>')
# <TD CLASS="bg_cinza azulE onze">1.04</TD> --> GB received
# <TD CLASS="bg_cinza azulE onze">0.06</TD> --> GB sended
# <TD CLASS="bg_cinza azulE onze">1.10</TD> --> GB consumed
# <TD CLASS="bg_cinza azulE onze">1.10</TD> --> Total
# when count == 3, it's signifies the daily consum
count = 0
seq = 0
date = ''
cons = ''
# html is a log phrase (all text in one line, it's bad)
html_formatted = html.split('\n')
for line in html_formatted:
if re.findall(regex_date,line): # get date
date = re.sub(regex_date,'',line)
date = date[:-5]
date = re.sub(regex_space,'',date) # take off blank spaces
if re.findall(regex_cons,line): # get daily consum
count += 1
cons = re.sub(regex_cons,'',line)
cons = re.sub(regex_cell,'',cons)
cons = re.sub(regex_space,'',cons) # take off blank spaces
if ( count % 4 == 0 ): # completes a sequence (one seq == 4 TD's)
seq += 1
if (count == (3 + 4 * seq)): # daily consum
preformatted += '\n| %s | %s |' % (date,cons)
preformatted += separator
preformatted += '\n\nTotal: %s GB' % cons
return preformatted
def getConsum(self,mac="cc0044bbcc99",month="",year=""):
target = self.__virtua_url + self.__virtua_action
month = datetime.date.today().month
year = datetime.date.today().year
data = {
'macadd':mac,
'mes':month,
'ano':year
}
input = urllib.urlencode(data)
req = urllib2.Request(target,input)
res = urllib2.urlopen(req)
print self.__prettyfy(res.read())
if __name__ == "__main__":
Virtua().getConsum()
Let’s turn {on|off} TV
August 1, 2008
I am not a TV addicted, but sometimes I like to watch movies on TV. As I don’t have money to spend with Pay-per-view or Cable TV, so before turn on mine TV and tune on some channel, I search at Folha Ilustrada for good films.
I think the Folha Ilustrada is better to consult, because in there all movies are classified as good, bad, not so bad, etc..
Yesterday, I was already bored to put the URL in my Firefox browser to go Folha Ilustrada and find something intersting. Then, I make a python script to bring to me the informations, look:
#!/usr/bin/python
import urllib2
import datetime
import re
from textwrap import TextWrapper
from BeautifulSoup import BeautifulSoup
class Films():
_url = 'http://www1.folha.uol.com.br/folha/ilustrada/filmes/'
_today = datetime.date.today().strftime('%A')
_days_of_week = { 'Monday':'segunda',
'Tuesday':'terca',
'Wednesday':'quarta',
'Thursday':'quinta',
'Friday':'sexta',
'Saturday':'sabado',
'Sunday':'domingo'
}
def __init__(self):
self.view_films()
def view_films(self):
regex = re.compile('localItem*')
clean_tags = re.compile('<(/|)(div|p|h1|h3|b|i)(| class=".*")>')
text_wrapper = TextWrapper()
text_wrapper.width = 72
page = self._url + self._days_of_week[self._today] + '.shtml'
resp = urllib2.urlopen(page)
html = resp.read()
resp.close()
for i in BeautifulSoup(''.join(html)).findAll('div'):
try:
if re.match(regex,i['class']):
formatted = text_wrapper.wrap(re.sub(clean_tags,'',i.__str__()))
for paragraph in formatted:
print paragraph.decode('utf8')
print '\n'
except:
pass
if __name__ == "__main__":
Films()
Bye.
Ubuntu Contributor
July 31, 2008
As a eventual contributor to Ubuntu [1] at Launchpad [2][4], sometimes I contribute with English->Portuguese translations. Well, sometimes I use a good tool known as Open-Tran [3], written by Jacek Sliwerski, to help me with technical or language specificities on translation.
The beautiful of this tool (open-tran) is the Python xml-rpc support. Then, translation can be done in this way:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from xmlrpclib import ServerProxy
lang = "pt_br"
server = ServerProxy("http://open-tran.eu/RPC2")
if __name__ == "__main__":
if sys.argv.__len__() == 2:
for sugg in server.suggest(sys.argv[1],lang):
print sugg
else:
print "Usage: %s <words_to_translate>" % sys.argv[0]
sys.exit(1)
sys.exit(0)
Now, I can translate a text:
translate.py "I feel happy"
Easily, yeah ?!
If you are a Brazilian and wants to help Ubuntu and Open Source cause, you can do it through Launchpad. Visit the Brazilian community at http://launchpad.net/~ubuntu-l10n-pt-br
Meet at https://launchpad.net/~n1ghtcr4wler
Useful links:







