python

Simple and quick command line argument handling in Python

17 January, 2012 - 00:08

When creating a command line tool, you quickly are faced with the burden of handling command line arguments (parsing options, arguments, flags, etc).
In Python, the optparse module or, its newer version, the argparse module are very nice solutions to build powerful command line interfaces, completely with automatically generated help.

Sometimes however, you just want a quick, simple and small way to get from A to B without a lot of overhead and overkill. Below I'll show you a quick and simple Python trick for command line handling by directly mapping the command line arguments to function arguments.

Read more...

Handy Python profiling analysis with pstats' interactive browser

21 January, 2010 - 18:45
Categories:

If you want to profile a Python applictation, you can get some basic functionality with the cProfile and pstats modules, as described in the Python Profilers documentation. After some curious experimenting, I discovered that the pstats module provides a handy interactive mode. To my surprising, I didn't found any substantial documentation about this time saver, so let me entertain you with a dump of my findings.

Read more...

Python: hiding attribute getters and setters behind standard attribute access

22 September, 2009 - 15:41
Categories:

Look at this small snippet of Python code:

x = TooMuchAlcohol()
 
x.value = 10
print x.value
 
x.value = 'foo'
print x.value
 
x.value = [1,2,3]
print x.value

Seems like pretty boring stuff, but look what it spits out:

20
foofoo
[1, 2, 3, 1, 2, 3]

Oh my god, I see everythin' double!

Read more...

Jython and PYTHONPATH

9 September, 2009 - 11:07
Categories:

For some small tools or jobs I use Jython so I can (re)use some existing Java code, while still writing in Python. I also have various custom Python modules, of which I put the paths in my PYTHONPATH environment variable, so those modules are easily available in Python scripts and interactive sessions.

However, Jython does not automatically pick up the PYTHONPATH information, for reasons that seem to be discussed in this Jython development mailing list thread.

Jython 2.5 introduced the JYTHONPATH environmental variable as Jython-equivalent of PYTHONPATH, so setting both to the same value should do the trick for most use cases (unless you're working in a setup with incompatible Python an Jython versions).

For Jython versions prior to 2.5 (like 2.2.1 in my case), there is an easy "workaround", by invoking Jython with the appropriate -Dpython.path=foo/path:bar/path option. For example as follows:

Read more...

Bar plots and legends in pylab/matplotlib

13 June, 2009 - 09:41

I like working with Matplotlib aka Pylab for my plotting needs in Python, but today I stumbled on a weird issue when creating a mixed bar + line plot with legend. Take the following snippet:

pylab.bar(x, yr, color='#88aa33', align='center', label='histogram')
pylab.plot(x, yc, 'bo-', label='cumulative')
pylab.legend()

This generates something like (note the entry overload in the legend):

Legend entry overload.

[Update: this issue seems to be solved. The issue described here occurred with Matplotlib version 0.91.2. With Matplotlib 0.99.0 I don't have this problem anymore.]

Read more...

Date tick control in pylab/matplotlib

18 May, 2009 - 14:05

Today I struggled a bit with pylab's plot_date function and overlapping date tick labels:

overlapping plot_date xticks

Read more...

Script for easier adding subversion ignore rules

4 July, 2008 - 11:16
Categories:

It's possible to make Subversion ignore unversioned files, so they don't show up in the status overview and you get a better signal to noise ratio. The command line interface to add ignore rules this is however a bit clunky. First, you need to remember following command:

svn propedit svn:ignore .

(which can be quite confusing, especially with the slightly similar looking but different propset command).
Then you get a file editor where you have to add the rule (make sure you remembered the file name or pattern you want to ignore), save the file and exit the editor.
A bit too much hoops to jump through for something that could be just one command like svn-ignore filename.

Read more...

Parsing the subversion Id keyword with python

19 February, 2008 - 11:07

Another one for the category 'remainder-to-self' or 'write-it-on-a-sticky-note-somewhere'.
Parsing a subversion Id keyword is just a matter of some regular expression magic:

# use the built in regular expression library
import re
 
# the subversion Id keyword
svnid = '$Id: svnidparse.py 1234 2008-02-19 09:59:27Z joske $'
 
# bow for the mighty regular expression
svnidrep = r'^\$Id: (?P<filename>.+) (?P<revision>\d+) (?P<date>\d{4}-\d{2}-\d{1,2}) (?P<time>\d{2}:\d{2}:\d{2})Z (?P<user>\w+) \$$'
 
# parse the svn Id
mo = re.match(svnidrep, svnid)
 
# use it, like for example:
print 'this is %s - revision %s (%s)' % mo.group('filename', 'revision', 'date')

hmm, calling it "black magic" would be better, probably.

Get name of current function and caller with Python

11 January, 2007 - 15:22
Categories:

With the python module inspect, one can inspect (no kidding) the run-time python stack. Among other things, this makes it possible to get the name of the current function or callers. Handy for logging or debugging purposes. A simple script to illustrate:

import inspect
# functions
def whoami():
    return inspect.stack()[1][3]
def whosdaddy():
    return inspect.stack()[2][3]
def foo():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
    bar()
def bar():
    print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy())
johny = bar
# call them!
foo()
bar()
johny()

output:

hello, I'm foo, daddy is ?
hello, I'm bar, daddy is foo
hello, I'm bar, daddy is ?
hello, I'm bar, daddy is ?
Read more...

get working directory in python

2 June, 2006 - 16:14
Categories:

This is mainly a remainder to myself, because I always forget it and spend to much time to find it again. It's so simple/basic that it is almost embarrassing.
To get the current working directory of in a python script, like you have pwd (print working directory) on a Linux/Unix command line:

import os
print os.getcwd()