Posted by: silkenpy | March 16, 2009

Wrap a C class for python with swig and distutils

In many cases we need to use C class in our Python program. This is a very simple way to link it to Python.

swig class.zip

//ali.cxx——————————————————

#include<stdio.h>
#include”ali.h”

Ali::Ali(){
    al=29;
    }

int Ali::a(int x){
    return 29*x;
   
    }

//————————————————

 

//ali.h—————————————

class Ali{
    int al;
    int x;
public:
   Ali();
      int a(int x);

    };

//——————————————————

//ali.i—————————————————–

%module ali

%{
#include “ali.h”
%}
class Ali{
    int al;
       
public:
    Ali();
    int a(int x);

    };

//——————————————————

# setup.py
import distutils
from distutils.core import setup ,Extension
setup(name = “Simple example from the SWIG website”,
         version = “2.2″,
           ext_modules = [Extension("_ali", ["ali.i","ali.cxx"],
                          swig_opts=['-c++'])])

then in command line type:

setup.py build -cmingw32

or check make.txt file .

Posted by: silkenpy | March 12, 2009

Wrap a simple C function for Python by SWIG

In this post , I want to show how we can use C function in python by use of SWIG.

Before starting you need to install mingw and swig.

simple swig.zip

first we define simple function in C.

//myfunc.c   ——————————————–

double myfun(double x){

return x*29.0;
}
///    ——————————————————-

and then we need to define an interface file for this C function.

// myfunc.i

%module myfunc

%inline %{
extern double myfun(double x);

%}

for compiling this file, I use a setup file like this.

# setup.py
import distutils
from distutils.core import setup ,Extension
setup(name = “Simple example from the SWIG website”,
         version = “2.2″,
           ext_modules = [Extension("_myfunc", ["myfunc.i","myfunc.c"])])

 

then in command line type:

setup.py build -cmingw32

then in build folder you can see two folders: lib.win32-2.5 and temp.win32-2.5

in  lib.win32-2.5 folder you can see _myfunc.pyd or _myfunc.so

now you can check in simple test like this.

from _myfunc import *

print myfun(2)

you should receive 58.0

Posted by: silkenpy | February 27, 2009

Build a stand alone program with py2exe

In this session we have some examples of usage py2exe to convert your python script to a executable file.

1. very simple console.

 py2exe.zip

# helloworld.py
n=29
print ” In the Name of God \n”
print ” %i is My Love Number “%29
#——————————————-

#setup.py
import sys, os
from distutils.core import setup
##import glob
import py2exe
setup(console=["helloworld.py"],
     
      options = {“py2exe”:{“compressed”: 1, # Now compress level is 1 if you choose greater than 1 you can not use UPX.
                          “optimize”: 2,
                          “ascii”: 1,
                          “bundle_files”: 1,
                          “packages”: []  #sometimes you need add the name of module which called in the program.
                           }},
         zipfile = None, # the zip file is’nt created and your program is a single .exe file.
                 # optimize may break pylab docstring handling
                
      )

 
Then in DOS Command type

setup.py py2exe

Now you can find helloworld.exe in dist folder. this is a standalone file that you can run it in any windows system without of python. In this program we asked py2exe to not build zipfile, actually zip file contains compiled python .pyc or .pyo. These files can be decompiled to python by depython.net so it is up to you to select which type is better for your case.
2. GUI to exe.

This is a complete example of usage py2exe that you define the icon file, compress level and also manifest . Sometimes after generation, a GUI works god but it looks so bad for example the buttons are not XP type by adding this manifest , you have a program with XP features.

 py2exe2.zip
#frame2.py
import wx

 

class MainWindow(wx.Frame):
         
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,wx.ID_ANY, title, size = (300,300),
                style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)

        page1 = wx.Panel(self,1)
        self.bot=wx.Button(page1, -1, “Start”, pos=(0, 0))
        self.Bind(wx.EVT_BUTTON, self.printo, self.bot)
    def printo(self,event):
        wx.MessageBox(“Hello !”)
app = wx.PySimpleApp()
frame1= MainWindow(None, 1,”It is a sample Frame “)
frame1.Show(1)
app.MainLoop()
#——————————————-
#—setup.py—————————-
import sys, os
from distutils.core import setup
import glob
import py2exe

##data = glob.glob(r’d:\Python23\share\matplotlib\*’)

py2exe_options = {“packages”: “encodings,somethingelse”}

manifest = “”"
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<assembly xmlns=”urn:schemas-microsoft-com:asm.v1″
manifestVersion=”1.0″>
<assemblyIdentity
    version=”0.64.1.0″
    processorArchitecture=”x86″
    name=”Controls”
    type=”win32″
/>
<description>myProgram</description>
<dependency>
    <dependentAssembly>
        <assemblyIdentity
            type=”win32″
            name=”Microsoft.Windows.Common-Controls”
            version=”6.0.0.0″
            processorArchitecture=”X86″
            publicKeyToken=”6595b64144ccf1df”
            language=”*”
        />
    </dependentAssembly>
</dependency>
</assembly>
“”"

“”"
installs manifest and icon into the .exe
but icon is still needed as we open it
for the window icon (not just the .exe)
changelog and logo are included in dist
“”"
setup(windows=[{"script": "frame2.py","icon_resources": [(0, "16.ico")],”other_resources”: [(24,1,manifest)]}],
     
      options = {“py2exe”:{
                   
                          “compressed”: 1,
                          “optimize”: 2,
                   
##                          “ascii”: 1,
                          “bundle_files”: 1,
                          “packages”: []}},
     
         zipfile = None , # or none
                 # optimize may break pylab docstring handling
                
      )

Posted by: silkenpy | February 27, 2009

Build a python module Package

After building your program you need to create a setup package Python can build do it.
For example you have simple program like this.

pythonpackage.zip

#——————module.py———————————
# simple test for building a python package
from math import pow,sqrt
def hello():
       print ” In the Name of God”

def calculate(x,y):
       z= sqrt(pow(x,2)+pow(y,2))
       return z
#————-setup.py————————————–

# simple test for building a python package

from distutils.core import setup
setup(name=’module’,
      version=’1.0′,
      py_modules=['module'],
      )

#———————————————–

 

Then in DOS Command type

setup.py bdist_wininst

Now you have a windows installer for your module in dist folder(module-1.0.win32.exe) and also you can build a source distribution by run this.

setup.py sdist

you can find module-1.0.zip in dist folder.

Categories

Follow

Get every new post delivered to your Inbox.