Linki

Snippety

  1. class
    class Akcja:
    def __init__(self, par_bSkipInserts, par_nClearField):
    self.bSkipInserts = par_bSkipInserts
    self.nClearField = par_nClearField

    akcja = Akcja(True, None)

    #getting type name (typename)
    print type(akcja).__name__ # worse: akcja.__class__.__name__
  2. command line
    sys.argv[1] - first command line argument
  3. datetime
    from datetime import date
    date.today().strftime("%Y%m%d")
  4. environment

    pip: run python get-pip.py

    d:\lang\python2\Scripts\pip.exe search lxml
    pip.exe install lxml
    pip instal downloaded-file.whl
  5. error handling
    exit(1)

    try:
    print(1/0)
    except ZeroDivisionError:
    print("error")
  6. file
    # -*- coding: utf-8 -*-

    import io
    import sys

    i = 0
    fin = open("test.txt")
    fin = io.open("testutf.txt", encoding='utf8')
    fout = open("wynik.txt", "w+t")
    # fout = io.open("wynik.txt", mode="w+t", encofing='utf8')
    sLinia = "start"
    while sLinia:
    sLinia = sys.stdin.readline()
    i = i + 1
    print(`i` + ": " + sLinia, end='', file=fout)
    fout.write(u'text w unicode')

    import glob
    for name in glob.glob('testing*08-05.txt'):
    print name
    fout.close()

    print name.encode(encoding="utf-8", errors="replace") #ignore
  7. for
    for i in range(3):
    print "a"+`(i+1)`
  8. goto
    class skip(Exception): pass

    try:
    if s1=="NAZWA KOLUMNY": raise skip
    doSomething()
    except skip:
    pass
    y += 1
  9. listy i inne
    constants: True, False, None
    lista = []
    lista.append("element")
    mapa = dict()
    mapa["klucz"] = 444.3
    print(len(mapa))
    for keyValue in mapa.keys():
    slowo = list("jarek")
    slowo[0] = 'J' # string is immutable, but the list may be modified
    print "".join(slowo) # convert list to string
    "{0:02d}".format(i)

    if type(o) is str:
    if isintance(o, str):
  10. messages
    import tkSimpleDialog
    test = tkSimpleDialog.askstring('Address', 'Where do we get the pictures from?'

    python3:
    from tkinter import *
    import tkinter.simpledialog
    import tkinter.messagebox

    Tk() #inicjalizacja
    tkinter.simpledialog.askstring("test", "test")
    tkinter.messagebox.showinfo("tytuł", "treść")

  11. regex
    import re

    s = re.sub(r"[0-9]", "X", s)

    m = re.search("^create table\s`(.*)`", sLinia, re.I)
    if m!=None: sCurTable = m.group(1)
    print(m.string)
    patField = re.compile(sRegField, re.I)
    m = patField.search(sLinia, nPos)
    nPos = m.end()
    sLinia = sLinia[:m.start(0)] + "''" + sLinia[m.end(0)-1:]
  12. timer
    def timerFun(timerApp):
    if timerApp.pbStop["state"]=="normal":
    timerApp.showTime()
    timerApp.timer = threading.Timer(1, timerFun, [timerApp])
    timerApp.timer.start()
  13. tkinter
    from tkinter import *

    class TimerApp(Frame):
    def __init__(self, master=None):
    Frame.__init__(self, master)
    self.pbAddProj=Button(self, text="add project", underline="0", command=self.addProj)
    self.pbAddProj.pack(pady=5)
    self.lbProj = Listbox(self)
    self.lbProj.bind("<<ListboxSelect>>", self.projChanged)
    self.lbProj.pack(pady=5)
    frame = Frame(self)
    self.pbStart = Button(frame, text="start", underline="0", command=self.start)
    self.pbStart.pack(pady=5, padx=5, side="left")
    frame.pack()
    self.master.minsize(300, 0)
    self.master.title("ProjectTimer")
    self.master.iconbitmap("C:\Bonanza\www\joomla\\bswww\\b.ico")
    self.pack(pady=5)

    app = TimerApp()
    app.mainloop()
  14. uppercase / lowercase
    import locale
    locale.setlocale(locale.LC_ALL, 'pl_PL.utf8')
    sTekst = sTekst.upper() # lower(), title()
  15. url
    import urllib
    urllib.quote("address?asdf=45&x=y")
  16. xml
      def saveSettings(self):
    self.xml = xml.dom.getDOMImplementation().createDocument(None, None, None)
    eMain = self.xml.appendChild(self.xml.createElement("TimerProj"))
    eMain.appendChild(self.xml.createTextNode("\n"))
    for p in self.projects:
    proj = self.projects[p]
    eProj = self.xml.createElement("project")
    eProj.attributes["name"] = proj.sName
    eProj.attributes["time"] = str(proj.fTime)
    eMain.appendChild(eProj)
    eMain.appendChild(self.xml.createTextNode("\n"))
    self.xml.writexml(open(self.settingsFile(), "w"))

    def loadSettings(self):
    self.projects.clear()
    doc = xml.dom.minidom.parse(self.settingsFile())
    eMain = doc.getElementsByTagName("TimerProj")[0] #doc.firstchild()
    for eProj in eMain.getElementsByTagName("project"):
    proj = Project(eProj.attributes["name"].value, float(eProj.attributes["time"].value))
    self.projects[proj.sName] = proj
    self.lbProj.insert("end", proj.sName)

    def getElemStr(parent, sName):
    s = ""
    for node in parent.getElementsByTagName(sName):
    for ch in node.childNodes:
    if ch.nodeType == node.TEXT_NODE:
    s += ch.nodeValue
    return s