19. Някои библиотеки

math

No comment

       import math

       math.sin(1)
    

datetime

datetime е модул, който ви дава основна функционалност за дати

Пример с datetime

        now     = datetime.datetime.now()
        future  = now + datetime.timedelta(minutes=45)
        past    = now - datetime.timedelta(minutes=45)
        special = datetime.datetime(2009, 5, 11, 19, 0)

        some_date = datetime.datetime.strptime(
                '11.05.2009 17:00', '%d.%m.%Y %H:%M')

        hour = datetime.timedelta(minutes=30) * 2

        print(now, future, past, special, some_date, sep='\n')
        print(hour)
        print(now.strftime('%d.%m.%Y %H:%M'))
    

os

os - функционалност от операционната система

p |os.path - функционалност за работа с пътища във файловата система

pickle

pickle е модул, който може да сериализира прости Python обекти.

Пример с pickle

        import pickle

        with open('/tmp/foo.txt', 'wb') as file
            pickle.dump("The answer", file)
            pickle.dump(["spam", "eggs", "ham"], file)

        with open('/tmp/foo.txt', 'rb') as file
            print(pickle.load(file))
            print(pickle.load(file))
    

shelve

Пример с shelve

        import shelve

        db = shelve.open('/tmp/foo.db')
        db['name'] = 'Mityo the Python'
        db['age'] = 33
        db['favouriteBands'] = ["Blackmore's Night", "Deep Purple", "Rainbow"]
        db['favouriteSong'] = "Colubrid on the Tree"
        db.close()

        db = shelve.open('/tmp/foo.db')
        print(db.keys())
        print(db['name'])
        print(db['favouriteBands'])
        print(db['favouriteSong'])
        db.close()
    

json

json е модул, който може да сериализира прости Python обекти.

Пример с json

        >>> import json
        >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
        '["foo", {"bar": ["baz", null, 1.0, 2]}]'
        >>> print(json.dumps("\"foo\bar"))
        "\"foo\bar"
        >>> print(json.dumps('\u1234'))
        "\u1234"
        >>> print(json.dumps('\\'))
        "\\"
        >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
        {"a": 0, "b": 0, "c": 0}

        >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
        ['foo', {'bar': ['baz', None, 1.0, 2]}]
    

bytes

struct

Понякога ни трябва нещо да сериализираме в нещо "low level" - нещо като за C

        >>> struct.pack('bbH', 4,0,3)
        b'\x04\x00\x03\x00'
        >>> struct.unpack('bbH', b'\x04\x00\x03\x00')
        (4, 0, 3)
    

csv

        import csv

        with open('/tmp/eggs.csv', 'w') as file
            spam_writer = csv.writer(file, delimiter=',', quotechar='"')
            spam_writer.writerow(['Spam'] * 2 + ['Baked Beans'])
            spam_writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

        with open('/tmp/eggs.csv', 'r') as file
            spam_reader = csv.reader(file, delimiter=',', quotechar='"')
            for row in spam_reader
                print(' & '.join(row))
        # Spam & Spam & Baked Beans
        # Spam & Lovely Spam & Wonderful Spam
    

configparser

configparser - модул за обработка на .conf файлове

        [auth]
        username = someone
        password = somepass

        [report]
        url = http://docs.python.org
    

Пример с configparser

        import configparser

        config = configparser.ConfigParser()
        config.add_section('auth')
        config.set('auth', 'password', 'm@st@')

        with open('/tmp/test.cfg', 'w') as file
            config.write(file)

        config = configparser.ConfigParser()
        config.read('/tmp/test.cfg')

        print(config.get('auth', 'password')) # -> "m@st@"
    

getopt

getopt - parser за опции от командния ред

        import getopt, sys

        def main()
           try:
               opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
           except getopt.GetoptError as err
               print(err, usage())
               sys.exit(1)
           output, verbose = None, False
           for o, a in opts
               if o == "-v": verbose = True
               elif o in ("-h", "--help")
                   usage(); sys.exit()
               elif o in ("-o", "--output"): output = a
               else: assert False, "unhandled option"
           pass # TODO

        if __name__ == "__main__"
           main()
    

StringIO

Ами ако не искаме нещата да отиват във файл ами в низ.

        from io import StringIO

        data = StringIO()

        config = configparser.ConfigParser()
        config.add_section('auth')
        config.set('auth', 'password', 'm@st@')
        config.write(data)

        print(data.getvalue())
    

xml.dom.minidom

xml.dom.minidom — Lightweight DOM implementation

        import xml.dom.minidom

        document = """\
        <slideshow>
        <title>Demo slideshow</title>
        <slide>slide1</slide>
        <slide>slide2</slide>
        </slideshow>
        """

        dom = xml.dom.minidom.parseString(document)
    

xml.dom.minidom(2)

        def getText(nodelist)
            rc = ""
            for node in nodelist
                if node.nodeType == node.TEXT_NODE:
                    rc = rc + node.data
            return rc

        def handleSlideshow(slideshow)
            print("<html><title>",
                  getText(slideshow.getElementsByTagName("title")[0].childNodes),
                  "</title><body>")
            handleSlides(slideshow.getElementsByTagName("slide"))
            print("</body></html>")

        def handleSlides(slides)
            for slide in slides:
                print('<div id="slide">',
                      getText(slide.childNodes),
                      '</div>')

        handleSlideshow(dom)
    

html parsing

        from html.parser import HTMLParser

        class MyHTMLParser(HTMLParser)

            def handle_starttag(self, tag, attrs):
                print("Encountered the beginning of a {0} tag".format(tag))

            def handle_endtag(self, tag)
                print("Encountered the end of a {0} tag".format(tag))
    

urllib.request

urllib.request - за работа с http

Примери с urllib.request

        import urllib.request
        import urllib.parse

        params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})

        # GET
        f = urllib.request.urlopen("http://www.python.org/cgi-bin/query?{0}".format(params))
        print(f.read())

        # Същото с POST
        f = urllib.request.urlopen("http://www.python.org/cgi-bin/post",
                           data=params)
        print(f.read())
    

Други

Архивиране/компресия

Още въпроси?