8
Standardní knihovna

>>> dir([])                              # atributy seznamů
[..., 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> dir(())                              # ntice nemají metody
[...]
>>> dir(sys.stdin)                       # atributy souborů
[..., 'buffer', 'isatty', 'read', 'readline', 'readlines', 'real_file']

>>> type(sys.version)                    # typ obj. sys.version
<type 'str'>
>>> print sys.version                    #  a jeho hodnota 
2.2a2+ (#22, Sep  5 2001, 14:10:41) [MSC 32 bit (Intel)]

% python neco.py a x=3 neco

sys.stdout = open('log.out', 'w')

### Standardní funkce

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 
'EnvironmentError', 'Exception', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 
'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 
'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'RuntimeError', 'RuntimeWarning', 
'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 
'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 
'ZeroDivisionError', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'buffer', 'callable', 'chr', 
'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dictionary', 'dir', 'divmod', 'eval', 
'execfile', 'exit', 'filter', 'float', 'getattr', 'getset', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 
'pow', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'super', 'tuple', 
'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

>>> int(1.0), int(1.4), int(1.9), round(1.9), int(round(1.9))
(1, 1, 1, 2.0, 2)

>>> int("1")
1

>>> int("1.2")  # nefunfuje – nejedná se o platné celé číslo
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 1.2

>>> int("1.0")  # POZOR: opět nefunguje
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): 1.0

>>> hex(1000), oct(1000), complex(1000), long(1000)
('0x3e8', '01750', (1000+0j), 1000L)

>>> def muj_int(cislo):
...     import math
...     oriznute = math.floor(float(cislo))
...     if oriznute == float(cislo): return int(oriznute)
...     else: raise ValueError, "bylo by nutné číslo oříznout"
...

>>> muj_int(3.0)
3
>>> muj_int("3.0")
3
>>> muj_int(3.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in muj_int
ValueError: bylo by nutné oříznout

>>> abs(-1), abs(-1.2), abs(-3+4j)  # sqrt(3*3 + 4*4) = 5
(1, 1.2, 5.0)

>>> map(ord, "test")               # řetězce jsou posloupnosti
[116, 101, 115, 116] 
>>> chr(64)                        #  a můžeme tedy použít map
'@'
>>> ord('@')
64
>>> map(chr, (99, 111, 115, 105))  # map vrací seznam znaků
['c', 'o', 's', 'i']
>>> import string                  # ty musíme spojit v řetězec
>>> string.join(map(chr, (99, 111, 115, 105)), '')
'cosi'

>>> min("pif", "paf", "pof")
'paf'
>>> min("abeceda"), max("abeceda")
('a', 'e')

>>> def vytvorCiZvys(obj, atribut):
...    if not hasattr(obj, atribut): 
...        setattr(obj, atribut, 1)
...    else:
...        setattr(obj, atribut, getattr(obj, atribut) + 1)
...
>>> class Test: pass
...
>>> jmeno = 'neco'
>>> vytvorCiZvys(Test, jmeno)  # vytvoří Test.neco
>>> vytvorCiZvys(Test, jmeno)  # zvýší hodn. Test.neco
Test.neco

def vytvorCiZvys(obj, atribut):
    setattr(obj, atribut, getattr(obj, atribut, 0) + 1)

exec kod [in global [, lokal]]

>>> kod = "x = 'Cosi'"
>>> x = "Nic"           # nastaví x
>>> exec kod            # změní x
>>> print x
'Cosi'

import sys
for argument in sys.argv[1:]:  # bez tohoto skriptu!
    execfile(argument)

>>> z = eval("'xo'*10")
>>> print z
'xoxoxoxoxoxoxoxoxoxo'

>>> z = eval("x = 3")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<string>", line 1
    x = 3
      ^
SyntaxError: invalid syntax

>>> callable(sys.exit), type(sys.exit)
(1, <type 'builtin_function_or_method'>)
>>> callable(sys.version), type(sys.version)
(0, <type 'string'>)

### Standardní moduly

s = string.strip(string.join(string.split(s)))

This is a paragraph that mentions bell peppers multiple times. For one, here is a red pepper and dried tomato 
salad recipe. I don't like to use green peppers in my salads as much because they have a harsher flavor.

This second paragraph mentions red peppers and green peppers but not the "s" word (s-a-l-a-d), so no bells 
should show up.

This third paragraph mentions red peppercorns and green peppercorns, which aren't vegetables but spices (by the 
way, bell peppers really aren't peppers, they're chilies, but would you rather have a good cook or a good botanist 
prepare your salad?).

soub = open('pepper.txt')
text = soub.read()

import string
odstavce = string.split(text, '\n\n')

import re
vzor = re.compile(
    r"""\b(red|green)         # začínající 'red' nebo 'green'
        (\s+                  #  následované prázdným místem
         pepper               #  a (přímo) slovem 'pepper'
         (?!corn)             #  a ne (přímo) 'corn'
         (?=.*salad))""",     #  ale (i nepřímo) 'salad''
      re.IGNORECASE |         # pepper, Pepper i PEPPER
      re.DOTALL |             # nevadí zalomení řádku
      re.VERBOSE)             # povolí tyto komentáře atp. 

for odstavec in odstavce:
    opraveny = vzor.sub(r'bell\2', odstavec)
    print opraveny+'\n'

vzor = re.compile \
(r"\b(red|green)(\s+pepper(?!corn)(?=.*salad))", re.I. | re.S)

opraveny = vzor.sub(r'bell\2', odstavec)

/home/David/book$ python pepper.py

This is a paragraph that mentions bell peppers multiple times. For one, here is a bell pepper and dried tomato 
salad recipe. I dont like to use bell peppers in my salads as much because they have a harsher flavor.

This second paragraph mentions red peppers and green peppers but not the "s" word (s-a-l-a-d), so no bells 
should show up.

This third paragraph mentions red peppercorns and green peppercorns, which arent vegetables but spices (by the 
way, bell peppers really arent peppers, theyre chilies, but would you rather have a good cook or a good botanist 
prepare your salad?).

>>> os.rmdir('neexistuje') 
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
OSError: [Errno 2] No such file or directory: 'neexistuje'

>>> try:
...     os.rmdir('neexistuje')
... except os.error, value:
...     print value[0], value[1]
...
2 No such file or directory

>>> print os.environ['SHELL']
/bin/sh

>>> os.environ['KDESI'] = 'cosi'
>>> os.system('echo $KDESI')  #  
cosi
0

import struct
data = open('bindat.dat').read()
od, do = 0, struct.calcsize('fl')
verze, pocetBytu = struct.unpack('fl', data[od:do])
od, do = do, od + struct.calcsize('B' * pocetBytu)
byty = struct.unpack('B'*pocetBytu, data[od:do])

znaky = struct.unpack(str(pocetBytu) + 's', data[od:do]

>>> import pocitadlo  # modul, který chceme ladit
>>> import pdb        # pdb a metoda run (předáme laděný kód)
>>> pdb.run('instance = pocitadlo.Pocitadlo()')
> C:\<string>(0)?()
(Pdb) break pocitadlo.Pocitadlo.__init__
Breakpoint 1 at C:\Python22\pocitadlo.py:4
(Pdb) next            # nastavili jsme breakpoint, pokračujeme
> C:\<string>(1)?()
(Pdb) n               # 'n' je zkratka pro 'next'
> C:\Python22\pocitadlo.py(4)__init__()
-> Pocitadlo.pocet += 1
(Pdb) list            # výpis zdrojového kódu, B je breakpoint
  1     class Pocitadlo:
  2         pocet = 0
  3         def __init__(self):
  4 B->         Pocitadlo.pocet += 1
  5         def vypisPocet():
  6             print "Počet instancí třídy Pocitadlo:",
        Pocitadlo.pocet [EOF]
(Pdb) where           # šipka je na “následující” řádce
  C:\<string>(1)?()
> C:\Python22\pocitadlo.py(4)__init__()
-> Pocitadlo.pocet += 1
(Pdb) Pocitadlo.pocet = 10   # můžeme měnit hodnoty proměnných
(Pdb) print Pocitadlo.pocet
10
(Pdb) continue        # pokračuje až k dalšímu breakpointu
--Return--
> C:\<string>(1)?()->None
(Pdb) c               # ten zřejmě nenejde a my pdb ukončíme
>>> instance.pocet    # hodnotu jsme nastavili před zvýšením o 1
11

% cat nuly.py

def sAppend():
    nuly = []
    for i in range(10000):
        nuly.append(0)

def sOpakovanim():
    nuly = [0] * 10000

% cat mereni.py

import time, nuly

def mer(pocet, *arg):
    celkem = {}
    for fce in arg: celkem[fce] = 0.0
    for x in range(pocet):
        for fce in arg:
            zacatek = time.time()
            apply(fce)
            konec = time.time()
            celkem[fce] += konec  zacatek
    for fce in arg:
        print "Funkce %s spuštěna %dx za %.3f sekund" \
             % (fce.__name__, pocet, celkem[fce])

if __name__ == "__main__":
    # 10000 (ve funkcich) * 100 (spusteni fce) = 1 milion
    mer(100, nuly.sAppend, nuly.sOpakovanim)

% python mereni.py

Funkce sAppend spuštěna 100x za 6.008 sekund
Funkce sOpakovanim spuštěna 100x za 0.100 sekund

>>> import profile
>>> from mereni import mer
>>> from nuly import sAppend, sOpakovanim
>>> profile.run('mer(100, sAppend, sOpakovanim)')

Funkce sAppend spuštěna 100x za 5.076 sekund
Funkce sOpakovanim spuštěna 100x za 0.301 sekund

      203 function calls in 5.622 CPU seconds

   Ordered by: standard name
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    5.291    5.291
<string>:1(?)
        1    0.214    0.214    5.291    5.291
mereni.py:3(mer)
      100    4.859    0.049    4.859    0.049
nuly.py:1(sAppend)
      100    0.218    0.002    0.218    0.002
nuly.py:6(sOpakovanim)
        1    0.331    0.331    5.622    5.622
profile:0(mer(100, sAppend, sOpakovanim))
        0    0.000             0.000         
profile:0(profiler)

### Cvičení