Archive for Python

[QN] How to convert month name to month number in Python

For a short script I was writing I needed to convert a string representation of the month (“month name”) into a numerical value (“month number”). A quick google led to many solutions to the inverse problem, which to me seems a lot easier. Here is a quick and dirty solution that uses the calendar module.

import calendar
list(calendar.month_name).index(month_name)

I chose to use the calendar module array month_name because I would rather not have to create a list of month names myself.

Comments (1)

wxPython on Linux (GTK) Annoyances

It is very fashionable to gripe about Windows short comings and brag that Linux solutions are always better, more bug-free, etc. I have come to the opposite conclusion in the case of wxPython and Windows/Linux development. Programming on Windows just works. Linux (or more accurately the GTK platform on Linux) is very frustrating because of the quirky behavior in a surprisingly wide variety of cases.

  • the File Browse Button widget (wx.lib.filebrowsebutton) had a bug that appears on GTK (but not Windows). If the value of the associated text control points to a directory or file that does not exist, clicking on the Browse button causes an assertion error. More info (and the fix) is here, summarized below:
    • This is the same error as discussed in
      http://trac.wxwidgets.org/ticket/4749 for 2.8.7.1 (I am using 2.8.9.1)
      but apparently the fix didn't carry over or fix this particular case.

      "Simple fix is to add a line that blanks out the file part when the
      directory is not found." is what it says but my 2.8.9.1 source for
      filebrowsebutton.py doesn't actually blank out the file part.

      adding:
      current = ''

      in the else clause around line 161 fixed it.

      else:
      directory = self.startDirectory
      current = ''
      dlg = wx.FileDialog(self, self.dialogTitle, directory, current,self.fileMask, self.fileMode)

  • Default fonts are sometimes (but not always!) larger than the encapsulating control. Pull down menus especially suffer from this on GTK, and I have to write special case code to check whether the program is being run under GTK, and size the fonts smaller so they are not clipped by the control. Very annoying!
  • StaticBitmap on GTK does not behave as on Windows, with the latter version being more feature full. There is a work around, by using a wx.lib.statbmp.GenStaticBitmap, but this leads to a performance hit, so I need to special case this as well for GTK.
  • More to come as I struggle with cross-platform programming.

Comments off

Statically Linking Python 2.5, wxPython, Numpy

  • These instructions still do not work (I get a seg fault) so this will be updated until I get a working setup.
  • Follow these instructions, but note the following caveats
    • Instead of –enable-static, use –disable-shared
    • Copy distrib/make_static_setup.py to the top level wxPython directory and save its output to Setup.local
    • Copy Setup.local to the Python src/Modules directory
    • On my setup, I had to edit Setup.local and delete all -pthread instances
    • After configuring Python, edit the Makefile so thatlib stdc++ is linked in.
    • If you get a libinstall error when you run make install, use make -i install
    • Copy the wx and wx_addons directories from the wxPython source directory
    • If you have trouble with import wx, edit the Setup file in the Python src/Modules directory and add _random operator, and other modules.

    Comments off

    QN: Linux: Shell Scripting

    I tried to run a few of my scripts on a linux machine, and kept getting weird errors like

    “: No such file or directory”

    I finally figured out that the files were in DOS formatted line separation (\n\r) which was confusing the shell. A quick

    dos2unix *.py

    fixed things.

    Comments off

    Invalid Status Bar Field Index in wxPython/Boa

    I had a very annoying bug in my wxPython application that I couldn’t figure out. In a GUI application that has a status bar and a context menu, any call to self.PopupMenu(mnu) would result in the following:

    wx._core.PyAssertionError: C++ assertion “(number>=0) && (number <m_nFields)” failed at ../src/generic/statusbr.cpp(142) in SetStatusText(): invalid status bar field index

    I use Boa Constructor to build my wxPython app, and in one of the generated code was the following:

    
    
     def _init_ctrls(self, prnt):
            # generated method, don't edit
            wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
                  pos=wx.Point(503, 180), size=wx.Size(988, 660),
                  style=wx.DEFAULT_FRAME_STYLE, title=u'')
            self._init_utils()
            ...
            self.SetStatusBarPane(3)

    setting SetStatusBarPane(-1) disables automatic help text printing to the status bar, but also stops this very annoying bug.

    
    				

    Comments off

    QN: Python: Looping through sequence and indices simultaneously

    I started programming in python from the days of 1.5.2, and have not kept up to date with some of the new features. Two features that caught me by surprise:

    enumerate()  # builtin function
    "...".format() # String method

    enumerate() takes a list an returns an interator tuple (index,value) as it goes along the sequence. Very handy and obviates the need for the very messy:

    for i in range(len(L)):
        print "I need the index {0} and the item {1} at the same time".format(i,L[i])

    This illustrates the second new feature I just realized, the .format() method. This apparently replaces the ‘%’ operator and allows formatted strings to include positional replacement strings using {idx} notation.

    Comments off

    Compiling Python 2.5.1 from scratch using MS Visual Studio 2005

    I usually use prepackaged binaries to install Python on Windows machines. Lately I have been trying to get back into using Intel’s open source vision library, OpenCV. To do that it appears I need to compile extension modules to be able to use Python, which in turn requires that I have the source and be able to build from it.

    The build process has been relatively smooth, the MSVS 2005 solution file is located in the PCBuild8 directory. The biggest hiccup has been to get the sqlite3 extension module compiled, the instructions say I need to download the source distribution for sqlite3 from the svn.python.org SVN repository, but it has not been available today so far. Building sqlite3 from sources available at the sqlite site is a hassle, as it appears to require Mingw. I can of course do this, but I don’t have the time I used to.

    A shortcut is to download the binary/DLL files from the sqlite website. This zip file contains both sqlite3.dll and the DEF file. However, the python solution requires a sqlite3.lib file, which is usually generated when one compiles and links the source files.

    A little bit of googling led me to the def2lib.exe tool which converts DEF files to LIB files. The tool is located here.

    Comments off