Debugging
http://docs.python.org/library/pdb.htmlpython -m pdb my.py # launch pdb after a crash. import pdb; pdb.set_trace() # compile without executing it python -m py_compile test.py
Lib Path
export PYTHONPATH=/home/python $ python Python 2.4.3 (#1, May 24 2008, 13:47:28) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path ['', '/home/python', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/gtk-2.0']
Useful
help(int) dir(int) locals() globals()
Variables
everything in python is an object.
All python variables hold value of references to objects.
parameter passing is by value.
String, numbers, tuples are immutable.
Integers, floats, complex numbers, booleans
x = 5 y = 6 print `x`; print "x is %i y is %i" % (x, y)
Lists
a=[1,4,5,6] b=[1,"two",3,["a","b"],4]
Tuples
Same as lists but not changeablea=(1,2) b=(1,"two",3,["a","b"],4)
Dictionaries
a={1:"one", 2:"two"} a["first"]="one"; list(a.keys()) a.get(1, "not availabe)
Sets
unorder collection of objects.>>> x=set([1,2,3,2,4,1]) >>> x set([1, 2, 3, 4]) >>> 1 in x True >>> 6 in x False
Conditionals
if x < 10: y = 1 elif x > 12: y = 2 else: y = 3
Loops
Forfor x in [1,2,3,4,5]: print x;While
x=5 while x < 10: print x x=x+1
Functions
def func(x, y, z): print (x, y, z) print x, y, z func(1,2,3) mult=lambda x,y: x * y # return is implicit map( lambda x: x*x, [1,2,3,4]) filter(lambda x: x > 3, [ 1,2,3,4,5,6])
Class
class X: "Sample class" x=5 def setVal(self,val): self.x=val
External Commands
os.systemimport os res=os.system("ls myfile"); if res>>8 != 0: print "err"commands
import commands >>> res, output = commands.getstatusoutput('ls /bin/ls') >>> res 0 >>> output '/bin/ls' >>> commands.getoutput('ls /bin/ls') '/bin/ls' >>> commands.getstatus('/bin/ls') '-rwxr-xr-x. 1 root root 105112 Feb 8 2011 /bin/ls'
No comments:
Post a Comment