http://docs.python.org/tutorial/introduction.html
interpreter:
python (alias py)
location: /usr/bin/python
cli:
import sys
sys.argv[i]
io:
print
read: ok = raw_input(prompt)
execution:
python file.py
as script file:
file.py (chmod)
#! /usr/bin/env python
encoding: # -*- coding: iso-8859-15 -*-
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
compile:
python -O compiles imported modules (don't run faster, only load faster)
execute bash: http://linux.byexamples.com/archives/366/python-how-to-run-a-command-line-within-python/
import os
file = os.popen("ls -l")
fi,fo,fe = os.popen3("ls -l")
also check the subprocess module
boolean operators:
=, in, not in, is (compares objects), is not, and or, not
chainable, no assignment possible
startup file: $PYTHONSTARTUP=/home/nicolamr/.pythonrc.py
included only when python without arguments
variables:
a = 12, b = "asd", c = 'asd', d = """ multiline """
e = r"asdf\niasd" is raw, does not convert \n to new line
a = b = 1
a = complex(0,1), a.real, a.imag
abs(a), round(_,2)
must be defined
concat: +, string mult: *, string index: a[4] a[2:3] a[:3]
a[-1] a[-2:] a[:-2], len(a)
unicode: u'Hello\u0020World!' (other stuff in the tutorial)
strings:
strings are immutable
implode/join: ', '.join(['hello', 'world']);
explode: string.split(sep)
"string {0} {1} {other} {!r}".format(a,b,other=c,math.pi)
{i:10} makes field min 10 wide
{i[j]} accesses dictionaries
repr().rjust() zfill
integer to string: str(integer)
check type: type(var) == int
str_replace: s.replace(search, replace)
lists:
python's arrays
a = ['asd', 1]
a[index], 3*a+b
copy: a[:]
a[2:3] = [some other list], a[:] = []
length: len
a=[1, [2,3]], a[1][1]
append(1) extend(L) insert(i,x) remove(x) pop([i]) popleft()
index(x) sort() reverse()
count(x)
list comprehensions: [x+y for x in vec1 for y in vec2]
can be nested
dictionary:
d = {"key": "value"}
dict(key=value, key2=value2)
clear, copy, setdefault, update, pop, get, has_key, keys, values
control structures:
expressions:
a in ('a', 'b', 'c')
while expr:
code (pass, break)
if expr:
code
elif expr:
code
else
code
iteration/for loop:
for x in range(start, end[, step])
goes up to end-1
or range(len(a))
body: use pass, break
for x in list
for i,v in dict.iteritems():
for i, v in enumerate(list):
for q, a in zip(list1, list2):
for i in reversed(list):
for f in sorted(list):
else:
nobreakcode
functions:
def fcname(arg1, arg2=default):
"""documentationstring"""
help/function info: func.__doc__
code
return result or returns None
default can be expr, but evaluated only once (but mutables are not cloned)
can call fcname(val, arg1=val) !!!
dictionary: fnc(a, *args, **keywords):
unpack arguments: fnc(*[all args])
vars() returns dict with all local vars
lambda forms: return instant functions:
lambda x: x + n
limited to a single expression
coding style:
4-spaces no tabs
max 79 chars per line
blank lines to separate
comments on own line
use docstrings
spaces around operators and after commas
ClassNames function_names
first method argument: self
static:
static var:
define outside methods
static method:
@staticmethod
def mname(args)
class method:
@classmethod
def mname(class, args)
functional programming:
filter(func, sequence)
map(function,sequence)
reduce(function, sequence)
del a[i], del a
tuples: (a,b,c)
a = 1,2,3
empty = ()
oneelem = a,
x,y,z = 1,2,3 (packing/unpacking)
sets:
a=set(seq)
'x' in a is a boolean
a-b, a|b, a&b, a^b
modules:
import modname
modname.func
modname.__name__ normally modname, when executed: __main__
from mod.name or . or .. or ..modname import func, func2 or *
dir(module) returns defined names
sys (ps1, ps2, path)
packages: dotted.modules
files/open file:
f = open('path', 'w') or 'r' or 'r+' or 'a' for append
in some case file = codecs.open('path', 'w', 'utf-8')
get all contents: f.read()
readline() \n left .write(string) .write(str(nostring))
readlines()
iterate: for l in f.readlines()
seek(offset,from_what) .close()
closes file automatically
errors: syntax, exceptions
try:
code
break
except ValueError:
except (E1,E2,E3):
except Exception as inst:
pass
else
if no exception
finally:
always
raise Exception(args)
can make own exc classes
objects:
get all fields/get all functions: dir(obj)
classes:
class ClassName(BaseClass):
"""docstring"""
var = value
def __init__(self):
self.var =sth
def f(self):
return 'hello world'
instantiate/new: x = MyClass()
x = C.f
can call x()
isinstance(obj, ClassName)
issubclass(Class1, Class2)
can write to any field!
for iteration:
implement iter() which return iterator that defines next()
and raises StopIteration
def __iter__(self):
return self
def nex(self):
if self.index == 0:
raise StopIteration
self.index = self.index -1
return self.data[self.index]
generator: generates iterator
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
serialize: pickle
null: None
plone:
cms
sudo apt-get install libssl-dev
sudo install.sh --with-python=/usr/bin/python zeo
/usr/local/Plone
instance: zeocluster
user: plone
admin, q4o1YMIa /usr/local/Plone/zeocluster/adminPassword.txt
users: http://localhost:8080/acl_users/users/manage_users
/usr/local/Plone/zeocluster/buildout.cfg
update: sudo -u plone bin/buildout
start: sudo -u plone /usr/local/Plone/zeocluster/bin/plonectl start
stop: sudo -u plone /usr/local/Plone/zeocluster/bin/plonectl stop
http://localhost:8080/
gui: wxPython
ressources:
http://www.wxpython.org/
http://wiki.wxpython.org/How%20to%20Learn%20wxPython
http://wiki.wxpython.org/Getting%20Started
the demos are soo cool! http://sourceforge.net/projects/wxpython/files/wxPython/2.8.12.0/wxPython-demo-2.8.12.0.tar.bz2/download
installed python-wxgtk2.8
basic:
import wx
app = wx.App(<+ bool: redirect stdout to a window? +>)
frame = wx.Frame(<+Parent+>, <+ID:wx.ID_ANY+>, <+Title+>)
frame.Show(True)
app.MainLoop() # handles events
window: wx.Frame
inherit from it
__init__/parent:
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
# construct the frame here
content: self.control = <+widget+>
self.Show(True)
self.Close(True)
components/widgets: -> wx.Control -> wx.Window
text box: wx.TextCtrl(self, style=wx.TE_MULTILINE)
tb.SetValue(<+value+>)
static text: wx.StaticText
wx.TextCtrl
events: EVT_TEXT (text changes), EVT_CHAR (key pressed)
wx.ComboBox
event: EVT_COMBOBOX
wx.CheckBox
wx.RadioBox
panel: wx.Panel
container
menu:
m = wx.Menu()
menuitem = m.Append(<+id+>, <+name+>, <+descr+>)
standard ids: wx.ID_ABOUT, wx.ID_EXIT, ... http://docs.wxwidgets.org/stable/wx_stdevtid.html
names: "&About", ...
bind: frame.Bind(wx.EVT_MENU, frame.OnAbout, m)
m.AppendSeparator()
menu bar:
mb = wx.MenuBar()
mb.Appen(m,"&File")
frame.setMenuBar(<+MenuBar+>)
status bar:
frame.CreateStatusBar()
element layout:
possibilities: manual positoning via pixel coordinate, wx.LayoutConstraints, LayoutAnchors, wxSizer
sizers: wx.Sizer
sizers are not the parent windows
box: s = wx.BoxSizer(wx.VERTICAL/HORIZONTAL)
s.Add(<+control+>, <+weight+>, wx.EXPAND/SHAPED)
weight: proportion to others,
0: won't grow, third parameter can be wx.ALIGN_CENTER_HORIZONZAL/VERTICAL/CENTER/LEFT/TOP/RIGHT/BOTTOM (combinations with |)
grid: wx.GridSizer, wx.FlexGridSizer
frame sizer:
frame.SetSizer(s)
frame.SetAutoLayout(true)
s.Fit(frame)
event handling:
Frame::Bind(<+event+>, <+handler+>, <+object+>)
events: http://wiki.wxpython.org/ListOfEvents
handler: handler(self(::Frame), <+event:wx.Event+>)
call it OnEvent
skip: event.Skip()
shortcuts:
see demo/KeyEvents.py
http://www.blog.pythonlibrary.org/2010/12/02/wxpython-keyboard-shortcuts-accelerators/
dialogs:
message:
d = wx.MessageDialog(self, <+title+>, <+content+>, wx.OK)
d.ShowModal()
d.Destroy()
file open:
d = wx.FileDialog(self, <+title+>, self.dirname, "", "*.*", wx.OPEN)
if d.ShowModal() == wx.ID_OK:
self.filename = d.GetFilename()
self.dirname = d.GetDirectory()
f = open(os.path.join(self.dirname, self.filename), 'r')
self.control.SetValue(f.read())
f.close()
d.Destroy()
toolbars:
wx.ToolBar
drag and drop:
mdi:
tabs:
find/replace:
print:
macro:
validators: wx.Validator
notebook:
drawing
sliders
wxXmlResource
debugging:
redirect output with parameters redirect and filename
normal: MyApp()
to console: MyApp(0)
to file: MyApp(1, <+filename+>)
calendar:
wx.lib.calendar
http://www.wxpython.org/docs/api/wx.lib.calendar-module.html
date/time:
import time
import datetime
date:
datetime.date(year, month, day)
today() == date.fromtimestamp(time.time())
fromtimestamp(timestamp)
year/month/day
ops:
date +/- timedelta
timedelta = date1 - date2
date1 < date2
weekday() (mo=0)
isoformat
formatted date: strftime(format)
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
wday: %a, %A
mon: %b, %B, %m
datetime: %c
mday: %d
ms: %f
h: %H, %I
yday: %j
min: %M
am/pm: %p
s: %S
wnum: %W
date: %x
time: %X
year: %y, %Y
utc offset: %z
time zone: %Z
%: %%
time:
datetime:
parse utf
date = datetime.datetime.strptime("2004-06-03T00:44:35", "%Y-%m-%dT%H:%M:%S")
note: not necessary for data fetched via mysql as it is already a datetime object!
timedelta:
datetime.timedelta(days, ...)
tzinfo:
xml:
sax: import xml.sax
dom:
import xml.dom.minidom
read:
from xml.dom.minidom import Node
doc = xml.dom.minidom.parse("doc.xml")
or parseString
documentElement
for node in doc.getElementsByTagName(<+tagname+>):
node.getAttribute(<+attr+>)
node.childNodes
if node.nodeType == Node.TEXT_MODE
node.data
tagName
unlink
parentNode
write:
writexml(writer)
toxml()
toprettyxml()
doc = Document()
doc.createElement(name)
appendChild(element)
removeChild(child)
doc.createTextNode(data)
setAttribute(?)
mysql:
import MySQLdb
conn = MySQLdb.connect(host="localhost", user="user", passwd="pw", db="db", charset="utf8", use_unicode = True)
credits: http://www.harelmalka.com/?p=81
but not always necessary?! don't understand encodings...
c = conn.cursor()
c.execute(query)
last executed query: c._executed
for record in c.fetchall()
conn.commit() in the end!
injection: use execute("where bla=%s and asd=%s", (param1, param2))
flask: web framework
wrapper for werkzeug: http://werkzeug.pocoo.org
command line client:
http://www.doughellmann.com/PyMOTW/cmd/
http://docs.python.org/library/cmd.html
curl/pycurl:
http://pycurl.sourceforge.net/doc/curlobject.html
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
import pycurl
c = pycurl.Curl()
close()
setopt(opt, val)
perform()
getinfo(opt)
options:
c.setopt(POSTFIELDS, "key=value")
example
c.setopt(pycurl.URL, "http://www.python.org/")
c.setopt(pycurl.HTTPHEADER, ["Accept:"])
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.perform()
print b.getvalue()
md5:
import hashlib
hashlib.sha224('string').hexdigest()