Tag Archives: python

Fixing PySide UI Code-Generator Error

Today while coding a program I’m working on I got this ImportError exception. It says it cannot find a module. It is one of those modules that supposed to be created automatically every time I hit the magic make button.

So this shift my curiosity to the build process: what went wrong in the building process?

This is the message that got my attention:

An unexpected error occurred.make[1]: *** [../../sekolah/app/qt/inputasalpendidikandlg_ui.py] Error 1
make: *** [qtappres] Error 2

This message must be the clue to the ImportError exception thrown by Python interpreter. So basically Python can’t import it because the build unable to create it in the first place.


The next logical thing is to try creating the UI module by hand, with debug message, so:

$ pyside-uic -d resources/qt/ui/inputasalpendidikandlg.ui

gave me:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'resources/qt/ui/inputasalpendidikandlg.ui'
# Created: Tue Jan 14 23:33:06 2011
#      by: PySide uic UI code generator
# WARNING! All changes made in this file will be lost!

Traceback (most recent call last):
  File "/usr/bin/pyside-uic", line 75, in main
  File "/usr/bin/pyside-uic", line 39, in generateUi
    pysideuic.compileUi(uifname, pyfile, execute, indent)
  File "/usr/lib/pymodules/python2.6/pysideuic/__init__.py", line 73, in compileUi
    winfo = compiler.UICompiler().compileUi(uifile, pyfile)
  File "/usr/lib/pymodules/python2.6/pysideuic/Compiler/compiler.py", line 37, in __init__
  File "/usr/lib/pymodules/python2.6/pysideuic/uiparser.py", line 104, in __init__
    self.factory = QObjectCreator(creatorPolicy)
  File "/usr/lib/pymodules/python2.6/pysideuic/objcreator.py", line 79, in __init__
    raise WidgetPluginError, "%s: %s" % (e.__class__, str(e))
WidgetPluginError: : 'pluginType'

Hmm.. this is far more complicated than I thought. It seems, the faulty went straight to the PySide code. Because when I tried the same ui file with PyQt4’s pyuic4 it generate the module just fine.

Solving It

After reading the code on /usr/lib/pymodules/python2.6/pysideuic/objcreator.py and comparing it to PyQt4’s I found, semantically, they are doing the same thing. So the code is good, unless I missed something, which is hardly possible because both code are written nicely.

Now I know that this thing load plug-ins, by means of reading Python modules in a certain path. Putting some default variables and taking it back from the plug-in and basically do something against that. Nothing uncanny here, so what’s the big deal?

So I browse to the directory where it load its plug-ins: /usr/lib/pymodules/python2.6/pysideuic/widget-plugins/.

This is what I found:

$ ls
__init__.py	__init__.pyc	qtwebkit.py	qtwebkit.pyc

Aha! The __init__.py module being nothing more than a empty module (with its “compiled” __init__.pyc) is the culprit here. The objcreator.py executes __init__.py causing exception because the loader code expect variable pluginType to be defined by the plug-in, which in this case is an empty file.

So the easiest solution is to remove __init__.py and __init__.pyc from widget-plugins directory. At first I move the two to /tmp/ just in case something break badly I can put it back in, but after seeing make working as intended I delete them immediately.

Another alternative is to modify objcreator.py to remove __init__.py from “plugins” after enumerating files from the widget-plugins directory.


Leave a comment

Filed under Ilmu, Orang bego punya kegiatan

Multiple Items Existence Check in Python

This is new for me, sometimes I want to do this:

aList = [1, 2, 3, 5, 7];

if (2, 3) in aList:   # I want to check whether 2 and 3 is in aList
    doSomethingCool( );

that code right there is a logical error, I thought the interpreter will search aList for items inside the tuple while the truth is that it will look for the existence of a tuple with 2 and 3 in it inside aList.

Thanks to some guy’s code which I happened to stumble upon, now I know that I can use all( ) function to do that. A leaner solution than the tedious enumeration of all items and checking it one by one. Here’s a demonstration:

# instead of this ..
allFound = True;
for num in (2, 3):
    if not (num in aList):
        allFound = False;
if allFound:
    doSomethingCool( );

# now I can use this ...
if all(num in aList for num in (2, 3)):
    doSomethingCool( );

wow, look at that! It makes perfect sense because most of the gist in that sample is a list comprehension and all( ) made up the invisible AND between the list items. Another similar function to all( ) is the appropriately-named any( ) which having the effect of OR instead of AND.

Leave a comment

Filed under Ilmu

Analytic Hierarchy Processs (AHP) in Python

One day I have to implement AHP in Python, so this is what I came up with: a decision.py and a test unit called decision_test.py to demonstrate its usage.

Due to this WordPress.com account limitation I have to upload as ODT files, but you can rename them by replacing “-py.odt” into “.py” in the filename. Sorry for the inconvenience.

1 Comment

Filed under Ilmu


A Python script to update links under a path to use new prefix.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys, getopt;
options = {'start': None, 'oprefix': None, 'nprefix': None, 'simulate': True};

class PathError (Exception):

def ShowUsage():
  progname = os.path.split(sys.argv[0])[1];
  print progname;
  print '-'*len(progname)
  print " Usage: %s [-w] [-s startpath] -o oldprefix -n newprefix\n" % progname;
  print " Parameters: "
  print " -w, --write       Dont run the program run in simulation mode.\n";
  print " -s, --start-path  Use custom starting directory.\n";
  print " -o, --old-prefix  Find link(s) with prefix as specified by this parameter.\n";
  print " -n, --new-prefix  New prefix for the offending link(s) to use.\n";
def GetOptions():
  global options;
  ret = 0;
  arguments = sys.argv[1:];
    wnt, dummy = getopt.getopt(arguments, "o:n:s:w", ["old-prefix=",
                    "new-prefix=", "start-path=", "write"]);
    for name, val in wnt:
      if name in ('-o', '--old-prefix'):
        options['oprefix'] = val;
      elif name in ('-n', '--new-prefix'):
        options['nprefix'] = val;
      elif name in ('-s', '--start-path'):
        options['start'] = val;
      elif name in ('-w', '--write'):
        options['simulate'] = False;
    if options['start'] == None:
      options['start'] = os.getcwd();
  except getopt.GetoptError:
    ret = -1;
  if (options['oprefix'] == None) or (options['nprefix'] == None): ret = -1;  
  if ret != -1:
    print "Start      : %s" % options['start'];
    print "Old prefix : %s" % options['oprefix'];
    print "New prefix : %s" % options['nprefix'];
    if options['simulate'] == False:  print "WARNING    : This program may change links.";
  return ret;

def ProcessPath(curPath, recursive):
  proccount = 0;
  files = os.listdir(curPath);
  if len(files) > 0:
    print "Examining %s" % curPath;

  for entry in files:
    curFile = os.path.join(curPath, entry);
    if os.path.islink(curFile):
      linkPath = os.readlink(curFile);
      if linkPath.find(options['oprefix']) == 0:
        # we need to update this one
        newLinkPath = linkPath.replace(options['oprefix'], options['nprefix'], 
        print "Fixing %s\n   Old path: %s\n   New path: %s" % (curFile, 
          linkPath, newLinkPath);
        if options['simulate'] == False:         
          # these two lines will modify/regenerate the symbolic link        
          os.symlink(newLinkPath, curFile);
          proccount += 1;
        # good link, skip it
    elif os.path.isdir( curFile ) and recursive:
      proccount += ProcessPath(curFile, recursive);
  return proccount;

def main():   
    if GetOptions() == 0:
      i = ProcessPath(options['start'], True);
      print ["Nothing processed by this program", \
             "There are %s link(s) processed" % i][i > 0] + '.';

if __name__ == '__main__':

Leave a comment

Filed under Ilmu


Because I got ICO files and I want them in PNG.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, glob

# location of the files
sourceDir = "/media/yamazaki/Work/Pictures/Icons/KidsXP/"
# output directory
targetDir = "/tmp/kidsxp_png/"
# the real processor of this script: imagemagick 
convertCmd = "convert %s[9] -resize %s %s"
# which categories to process? all of 'em?
processDirs = ("actions", "apps", "devices", "filesystems", "mimetypes")
# extract it and move into known usable sizes 
knownSizes = ('16x16', '22x22', '32x32', '48x48', '64x64', '96x96', '128x128')

def processDir(path, thissize):
  print "Processing source path : %s" % path
  dummy, category = os.path.split(path)

  for item in glob.glob(path + '/*.ico'):
    dummy, itemName = os.path.split(item)
    tgtDir = os.path.join(targetDir, thissize, category, '')
    tgtName = itemName[:-3] + 'png' # "xyz.ico" filename to "xyz.png"
    print "Writing %20s -> %s" % (itemName, tgtDir + tgtName)
    if not os.path.exists(tgtDir):
    cmd = convertCmd % (item, thissize, tgtDir + tgtName)
    # execute
    os.system(cmd)  # ooh! the horror!!

for item in processDirs:
  s = sourceDir + item
  if os.path.isdir(s):
    for size in knownSizes:
      processDir(s, size)
    print "Skipping %s" % (s)

Leave a comment

Filed under Ilmu

wxPrintPreview HTML on my own frame (w/o wxPreviewFrame)

I’m in the mood to dump a few code. Here’s a small code to use user’s frame, for some reason, to preview a printout.

import wx
import wx.html

sHTML = \
    <h1>Hello world!</h1>

class PrintPreviewFrame (wx.Frame):

  def __init__(self, *args, **kwds):
    global sHTML
    wx.Frame.__init__(self, *args, **kwds)

    self.PO = wx.html.HtmlPrintout()

    self.PPreview = wx.PyPrintPreview(self.PO, self.PO)
    self.PreviewC = wx.PreviewCanvas(self.PPreview, self)


app = wx.PySimpleApp()
frm = PrintPreviewFrame(None)


Leave a comment

Filed under Ilmu