Home arrow Python Tips
Python Tips
Using Cython to write C and C++ Extentions to Python PDF
Thursday, 23 February 2012
If you want to easyly write C and C++ extensions (to Python) that incorporate Python syntax, C and C++ functions you can use Cython.

To install Cython from FreeBSD ports:

  cd /usr/ports/lang/cython
  make install clean

Then let's see a simple example that display numbers from 1 to n, where n is a given parameter to a function we will define.

First we define the pyx source file:


def display_numbers(upper):
    for i in range(1,upper+1):
      print i

Then we define setup.py file that will build the C source code for our extension:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("myfunc", ["myfunc.pyx"])]

  name = 'myfunc',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules

And then will build the binary extension to Python (run next command from shell command line):

  python setup.py build_ext --inplace

Then we could run Python and from command prompt:

>>> from myfunc import display_numbers
>>> display_numbers(7)

Or we could write a small Python script that uses myfunc module/extenstion (run next example from command line):


import myfunc


Note: Cython is also usefull if you want to build an application but you do not want to share all source code. By using only Python code, the app can be reverse engineered but using Cython this will not be possible, at least to get the same source code.

Last Updated ( Thursday, 23 February 2012 )
Creating Window Based GUI Apps with wxPython PDF
Thursday, 23 February 2012
If you want to create window based GUI app with Python there's a library for that called wxPython, based on (wrapper to) xwWidgets  C++ library.

First we will install xwPython from FreeBSD Ports:

  cd /usr/ports/x11-toolkits/py-wxPython28
  make install clean

Then to create an simple window app we could use the following code:


import wx

window = wx.App()

window_frame = wx.Frame(None, -1, 'Window Title')



To move the window to a specific location (instead of centering it) we could use (before showing the window):


Last Updated ( Thursday, 23 February 2012 )
Run a UNIX Shell Command from Python and Display it's Output PDF
Thursday, 23 February 2012
To run a system UNIX shell command from a Python script and then to display it's output (it's result) we will use the following example which will run ls -la / and then display it's output:


import os

line_content = " "

line = os.popen("ls -la /")

while (line_content != ""):
    line_content = line.readline()
    print line_content,

Note that the comma ( , ) after line_content will make print command to display the value on the screen without a newline.

Last Updated ( Thursday, 23 February 2012 )
Generate 1000 values from Python and add them to SQLITE database PDF
Thursday, 23 February 2012
Let's say we want to generate 1000 values of a string and an int and add them to a Python database.

To accomplish that we will use os, binascii and random module.

See next example, it's self explanatory:


str_length = 5

import os, binascii, random

os.popen("sqlite3 example.db \"create table person(name TEXT, age integer);\"")

for i in range(1,1001):
    rand_name = binascii.hexlify(os.urandom(str_length))
    print rand_name
    rand_age = random.randint(15,40)
    print rand_age

    str = "sqlite3 example.db \"insert into person(name, age) values(\'%s\',\'%d\');\"" % (rand_name , rand_age)
    print str

Of course this can be done also by using sqlite3 python module. But I am just lazy.

Create a range of directories in Python PDF
Saturday, 18 February 2012
If you want to create directories from 01 to 12 using python here is a variant to do that:


import os

for i in range(1,13):
    if len(str(i)) == 1:
        print 'i = 0%s' % (i)
        os.mkdir('0%s' % (i))
        print 'i = %s' % (i)
        os.mkdir('%s' % (i))

Last Updated ( Saturday, 18 February 2012 )
Python Power of Math Function PDF
Wednesday, 08 February 2012
If we want to calculate power of a number in Python we can use math.pow function:

>>> import math
>>> math.pow(2,8)

Previous example calculate 2 to the power of 8.

Define Lists and Tuples in Python PDF
Wednesday, 08 February 2012

To define a list of elements in Python we use:

>>>  list = ['element1', 'element2', ;element3']

Then we can print the list:

>>> print list
['element1', 'element2', 'element3']

or, we can print an element of the list:

>>> print list[1];

To print a range of elements we use:

>>> print list[0:2];
['element1', 'element2']


To define a tuple:

>>> tuple = ('elem1', 100, 'elem2', 200, 'elem3', 300)

To print the tuple:
>>> print tuple
('elem1', 100, 'elem2', 200, 'elem3', 300)

>>> print tuple[0]

To define a dictionary (key, value pair):

>>> dict = {'cat': 'gato', 'mouse':'raton', 'dog':'perro', 'chicken':'pollo'}

To print a value:

>>> print dict['cat']

Last Updated ( Wednesday, 08 February 2012 )
Calculate Logarithm with Python math module PDF
Wednesday, 08 February 2012
To calculate logarithm using Python we will use math module:

Python 2.7.2 (default, Feb  7 2012, 13:30:22)
[GCC 4.2.1 Compatible FreeBSD Clang 3.0 (branches/release_30 142614)] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> print math
<module 'math' from '/usr/local/lib/python2.7/lib-dynload/math.so'>
>>> print math.log
<built-in function log>
>>> math.log(10,5)

In previous example first parameter (10) to math.log is the value to calculate, and second parameter is the base (which is 5 in our example).

Last Updated ( Wednesday, 08 February 2012 )
First post for Python Tips PDF
Tuesday, 07 February 2012
You will find Python a nice scripting languages, very usefull and easy to learn. And very powerfull. You'll see its syntax is simple and clean. You can use it from small script to complex apps. Exporting data from apps like Blender can be done easely with Python. Web apps can be quickly created. Even sysadmin task can be simplified with Python. Or working with graphic files.

Welcome to Python world!

Last Updated ( Tuesday, 07 February 2012 )

Other BSD Systems





Best BSD firewall?