Difference between revisions of "Python"

From Tmplab
(Key, Values of dicts)
Line 15: Line 15:
  
 
== Key, Values of dicts ==
 
== Key, Values of dicts ==
 +
 +
ah iteritems() ...
  
 
  >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
 
  >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
 
  >>> for k, v in knights.iteritems():
 
  >>> for k, v in knights.iteritems():
 
  ...    print k, v
 
  ...    print k, v
 
  
 
= Debugging =
 
= Debugging =

Revision as of 01:35, 12 November 2009

Intro

This cheat sheet helps troubleshoot common problems...

Some good documentation source:

Tricks

content of objects

Finding what's in an object

>>> dir(obj)

Key, Values of dicts

ah iteritems() ...

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v

Debugging

See http://pythonconquerstheuniverse.wordpress.com/category/the-python-debugger/

import pdb
pdb.set_trace()


Editor tricks

Emacs

See http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm

  • C-c <: Shift the region to the left
  • C-c >: Shift the region to the right

HOW TO

Modules & Extensions: distutils

One mention, sometime you get this error message when building your extension under Mac OS X:

/usr/bin/ld: can't locate file for: -lnameofmylib

This seems to be a weird problem with Mac OS X where even if the library (here a dynamic library ending with .dylib) is in /usr/lib, it won't be "seen" by the ld linker. To mitigate this problem, create a link in /usr/local/lib/ to the /usr/lib/XXXX.dylib library and add the path in the setup.py file.

Here is a sample setup.py that fixes that:

"""
setup.py

Created by Philippe Langlois on 2009-11-02.
Copyright (c) 2009 Philippe Langlois. All rights reserved.
"""

from distutils.core import setup, Extension 

setup(name='pysctp',
     version='0.5',
     py_modules=['sctp'],
	  ext_modules=[Extension('pysctp', sources=['_sctp.c'],
	  						 include_dirs=['.', '/usr/include'],
	  						 libraries=['sctp'], 
	  						 library_dirs=['/usr/lib/', '/usr/local/lib/'],
							)
				  ],
	  data_files=['_sctp.h'],
	  author='Elvis Pfutzenreuter',
	  author_email='epx __AAAAATTTT_____ epx.com.br',
         maintainer='Philippe Langlois',
	  maintainer_email='Philippe.Langlois __AAAAATTT____ gmail.com',
     )


Problems

I installed some modules / packages and can't load them

echo $PYTHONPATH
$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) 
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
for i in sys.path: 
    print i

You can add a .pth file in one of the already loaded dir: see http://djangotricks.blogspot.com/2008/09/note-on-python-paths.html

like:

# cat > /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/others.pth
/Library/Python/2.5/site-packages/
^D