Monday, July 25, 2011

Python Module Not Found

Ways to debug when a python code can't find a module:

Open a terminal and start python. Enter:

from imp import *
find_module(module)


See if the path name corresponds with where your module was supposed to be installed or if the path name directs to a __init__.py file


For Example, we were trying to install pyfacebook and our code won't load the module.


find_module(module) was resulting in the following output:
(<open file 'facebook.py', mode 'U' at 0xb752d4f0>, 'facebook.py', ('.py', 'U', 1))


However, the module was installed at (found using a find command):
/usr/lib/python2.7/site-packages/pyfacebook-1.0a2-py2.7.egg


Clearly, when the code was calling from facebook import *, the code was unable to locate __init__.py file and was crashing. To solve the problem, move the files to /usr/lib/python2.7/site-packages/ and see if a further run of find_module points to the required directory.

Friday, July 8, 2011

python sequence float vs int

Python has a nifty little way to generate a sequence of numbers:

sequence = range(0, 10, 1)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

However, this doesn't work when the step value is float. For that purpose, use numpy's arange function:

import numpy as np
sequence = np.arange(0,1,0.1)

array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

For more interesting ways, including using generators, check: http://stackoverflow.com/questions/477486/python-decimal-range-step-value

Thursday, July 7, 2011

Python Non-ASCII character '\xc3'

During a python script execution, if you get the following error:

SyntaxError: Non-ASCII character '\xc3' in file text2term_topia.py on line 21, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

Add the following statement right at the begining, before all import statements.

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

Similar approach for errors with the term '\xe2'.