Category Archives: Python

Starting a New Project in wxPython

I’m starting a new project now. This time instead of pyGtk, i’m switching to wxPython, i’m giving a go on this as i’m getting bored on doing something on pyGtk.  Here I will post the development on the project.

This is a POS project that will be based on SqlSoup, Sqlite and wxPython.  I will post a github link later.

See you then everyone. Thanks.

Fixing ^M error on text file

A few weeks back, with my new job, I’ve been plunging deeply into the Xen environment and Perl programming, but of course I believe I wont abandon being a Pythonista. After all, its my fav. language and I still have an unfinished project hosted in Sourceforge site.

When I try to run my python program, I’ve encountered this kind of error :

bash: ./pytodolist.py: /usr/bin/python^M: bad interpreter: Permission denied

Googling the solution for this one..I’ve found the answer which tells me to use a small perl code which is : perl -i.bak -pe ‘s/r//g’ *.py

Running again my program..It now works 🙂

Toggling-on of VIm Syntax Higlighting

I’m using cream most of the time on my python development. As the site says – a modern configuration of VIm, it really is. What I like on Vim is that it has this tab editing, syntax highlighting and etc. Though most of those available text editors has this function, this is a software which I’m comfortable with. Occasionally, I have to use someones terminal when it is necessary, and found out that my fav syntax highligthing feature of vi is not available. I’ve searched on the net on how to toggle this kind of feature. I’ve found it and here it is:

There is a global configuration file of VIm called vimrc. On the case of my ubuntu the vimrc file is available at /etc/vim/vimrc.
To toggle the syntax highlighting, simply add the line : syntax on. Thats all 🙂 Feature activated!!

PySQLite Howto: Selecting Sql Column Names on SQLite Table

When somebody ask in the mailing list on how to extract a fieldname of a particular table of SQLite, the most common answer is that theres a specification of Python DBAPI2 on cursor object which has an attribute description.

In the Python Database API Specification v2.0 particularly on the cursor object, it states that:

.description

This read-only attribute is a sequence of 7-item
sequences. Each of these sequences contains information
describing one result column: (name, type_code,
display_size, internal_size, precision, scale,
null_ok). The first two items (name and type_code) are
mandatory, the other five are optional and must be set to
None if meaningfull values are not provided.

Below is my implemention on extracting fieldnames:

[python]
from pysqlite2 import dbapi2 as sqlite
#connecting to book.db
conn = sqlite.Connection(“book.db”)
#creating a cursor for book table
cursor = conn.execute(“select * from book”)
for i in cursor.description: print i[0]
# The table fieldnames will be be then displayed. [/python]

The only limitiation of the attribute description in pysqlite is that only fieldnames is displayed. You may notice in the PEP 249 document that it is mandatory to include name and typecode. There is a documentation which explains why this incompatibility to DBAPI specification happens but we hope that it would be rectified on the later revisions.

PyGTK and Py2Exe HowTo

    1. Overview
      This is a simple howto on generating stand-alone executables for pygtk programs using py2exe-0.6.5 & PyGtk 2.10.3.
    2. Initial Installation (Windows OS)
      1) Install the latest version of python. You may need to add the install location to your PATH environment variable…
      e.g. c:python24
      2) Install the latest version of GTK+ for windows.
      3) Install the latest version of pygtk for windows.
      4) Install py2exe 0.5.x or later.
      You may install the installer of Alberto Ruiz (arc) : http://osl.ulpgc.es/~arc/gnome/pygtk-setup.exe
      This is all in one installer though still there is a need for refinement on this.

      5) Install the installer NSIS.
    3. Configure py2exe for your project
      1) Build a setup.py file.
      I’m using this on my project – the pytodolist
      [python]
      # setup.py
      from distutils.core import setup
      import py2exe
      import glob

      opts = {
      “py2exe”: {
      “excludes”: “pango,atk,gobject”,
      “dll_excludes”: [
      “iconv.dll”,”intl.dll”,”libatk-1.0-0.dll”,
      “libgdk_pixbuf-2.0-0.dll”,”libgdk-win32-2.0-0.dll”,
      “libglib-2.0-0.dll”,”libgmodule-2.0-0.dll”,
      “libgobject-2.0-0.dll”,”libgthread-2.0-0.dll”,
      “libgtk-win32-2.0-0.dll”,”libpango-1.0-0.dll”,
      “libpangowin32-1.0-0.dll”],
      }
      }

      setup(
      name = “PyToDoList”,
      description = “A simple ToDoList Program”,
      version = “0.61”,
      windows = [
      {“script”: “todo.py”,
      “icon_resources”: [(1, “checker1.ico”)]
      }
      ],
      options=opts,
      data_files=[(“todo.db”),(“jojopix.png”),(“checker1.ico”)],
      )
      [/python]

    4. Build the executable
      From a command prompt in your project_name folder, run:
      python setup.py py2exe
      This should create a dist folder in your project folder.
    5. GTK+ Runtime files
      A GTK+ runtime for windows will also need to be installed for the standalone executable. Get that from here.
      If you happened to used the installer of Alberto Ruiz (arc). You dont have to install this one.
    6. Compiling the Installer using NSIS.

      Usually the file extension of the NSI script is .nsi. For more information on NSIS scripting, there’s a tutorial available at sourceforge site. Below is my sample NSIS script:

      [actionscript]
      ;——————————–
      ;Include Modern UI

      !include “MUI.nsh”

      ;——————————–
      ;General

      ;Name and file
      Name “PyToDoList”
      OutFile “PyToDoList.exe”

      ;Default installation folder
      InstallDir “$PROGRAMFILESPyToDoList”

      ;Get installation folder from registry if available
      InstallDirRegKey HKCU “SoftwarePyToDoList” “”

      ;——————————–
      ;Interface Settings

      !define MUI_ABORTWARNING

      ;——————————–
      ;Pages

      !insertmacro MUI_PAGE_WELCOME
      !insertmacro MUI_PAGE_LICENSE “..License.txt”
      !insertmacro MUI_PAGE_COMPONENTS
      !insertmacro MUI_PAGE_DIRECTORY
      !insertmacro MUI_PAGE_INSTFILES

      !insertmacro MUI_UNPAGE_WELCOME
      !insertmacro MUI_UNPAGE_CONFIRM
      !insertmacro MUI_UNPAGE_INSTFILES
      !insertmacro MUI_UNPAGE_FINISH
      ;——————————–
      ;Languages

      !insertmacro MUI_LANGUAGE “English”

      ;——————————–
      ;Installer Sections

      Section “Package” SecDummy

      SetOutPath “$INSTDIR”

      File “..dist*.*”

      ;Store installation folder
      WriteRegStr HKCU “SoftwarePyToDoList” “” $INSTDIR

      ;Create uninstaller
      WriteUninstaller “$INSTDIRUninstall.exe”

      CreateShortCut “$INSTDIRPyToDoList.lnk” “$INSTDIRtodo.exe”

      SetOutPath “$SMPROGRAMSMegSoft Solutions”
      CopyFiles “$INSTDIRPyToDoList.lnk” “$SMPROGRAMSMegSoft Solutions”
      CopyFiles “$INSTDIRPyToDoList.lnk” “$DESKTOP”
      Delete “$INSTDIRPyToDoList.lnk”
      CreateShortCut “$SMPROGRAMSGemSoft SolutionsUninstall.lnk” “$INSTDIRUninstall.exe”

      SectionEnd

      Section “GTK+” SecDummy2

      SetOutPath “$INSTDIR”
      File “….gtklib*.dll”

      SetOutPath “$INSTDIRetcfonts”
      File “….gtklibetcfonts*.*”

      SetOutPath “$INSTDIRetcgtk-2.0”
      File “….gtklibetcgtk-2.0*.*”

      SetOutPath “$INSTDIRetcpango”
      File “….gtklibetcpango*.*”

      SetOutPath “$INSTDIRlibgtk-2.02.4.0loaders”
      File “….gtkliblibgtk-2.02.4.0loaders*.*”

      SetOutPath “$INSTDIRlibgtk-2.02.4.0engines”
      File “….gtkliblibgtk-2.02.4.0engines*.*”

      SetOutPath “$INSTDIRlibgtk-2.02.4.0immodules”
      File “….gtkliblibgtk-2.02.4.0immodules*.*”

      SetOutPath “$INSTDIRlibpango1.4.0modules”
      File “….gtkliblibpango1.4.0modules*.*”

      SetOutPath “$INSTDIRsharethemesDefaultgtk-2.0”
      File “….gtklibsharethemesDefaultgtk-2.0*.*”

      SetOutPath “$INSTDIRsharethemesMS-Windowsgtk-2.0”
      File “….gtklibsharethemesMS-Windowsgtk-2.0*.*”

      SectionEnd

      ;——————————–
      ;Descriptions

      ;Language strings
      LangString DESC_SecDummy ${LANG_ENGLISH} “Main Package”
      LangString DESC_SecDummy2 ${LANG_ENGLISH} “GTK+ Package. To be installed if you dont have pre installed GTK+”

      ;Assign language strings to sections
      !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
      !insertmacro MUI_DESCRIPTION_TEXT ${SecDummy} $(DESC_SecDummy)
      !insertmacro MUI_DESCRIPTION_TEXT ${SecDummy2} $(DESC_SecDummy2)
      !insertmacro MUI_FUNCTION_DESCRIPTION_END

      ;——————————–
      ;Uninstaller Section

      Section “Uninstall”

      Delete “$INSTDIR*.*”

      Delete “$DESKTOPPyToDoList.lnk”
      Delete “$SMPROGRAMSGemSoft SolutionsPyToDoList.lnk”
      Delete “$SMPROGRAMSGemSoft SolutionsUninstall.lnk”

      RMDir “$SMPROGRAMSGemSoft Solutions”

      RMDir /r “$INSTDIRetc”
      RMDir /r “$INSTDIRlib”
      RMDir /r “$INSTDIRshare”

      RMDir “$INSTDIR”

      DeleteRegKey /ifempty HKCU “SoftwarePyToDoList”

      SectionEnd
      [/actionscript]

      There are two options for compiling .nsi file.

      • Compile the .nsi file by right clicking it and select the Compile NSIS. The
        output exe is the installer of the file.
      • Issue the command makensis . This will then generate the output exe file.

PyGTK Context Menu Problem

Somebody posted in the Pygtk mailing list and said he found a bug on the context menu of pygtk. The test code really confirms the alleged bug but someone also replied that that particular problem didn’t occur when he test the code.
.
Below is the problem:

When creating a context menu with a submenu, the submenu doesn’t get focus until the menu item it’s attached to is clicked (even though the submenu appears when the mouse is over the menu item.)

The upshot is that items in the sub menu don’t emit the activate signal unless the parent menu item is clicked first.

Here is some test code demonstrating this problem:

[python]
import pygtk
pygtk.require(‘2.0’)
import gtk

class bugtest:
def hello(self, widget, data=None):
print “hello”
return False

def contextMenu(self, widget, event, data=None):
menu = gtk.Menu()

one = gtk.MenuItem(“One”)
menu.append(one)

submenu = gtk.Menu()
two = gtk.MenuItem(“Two”)
two.connect(“activate”, self.hello)
submenu.append(two)
one.set_submenu(submenu)

three = gtk.MenuItem(“Three”)
three.connect(“activate”, self.hello)
menu.append(three)

menu.show_all()

menu.popup(None, None, None, event.button, event.get_time())
return True

def __init__(self):
win = gtk.Window()
label = gtk.Label(‘Submenu bug test’)
evbox = gtk.EventBox()
evbox.add(label)
win.add(evbox)
win.resize(200,200)
evbox.connect(‘button-release-event’, self.contextMenu)
win.show_all()

def main(self):
gtk.main()

if __name__ == “__main__”:
a = bugtest()
a.main()
[/python]

My proposed workaround on that particular problem is that i’ve just changed that “activate” signal to “button-press-event” signal.

[python]
submenu = gtk.Menu()
two = gtk.MenuItem(“Two”)
two.connect(“button-press-event”, self.hello)
submenu.append(two)
one.set_submenu(submenu)
[/python]