La librairie standard

les builtins

  • le module builtins, tout ce qui est accessible directement
>>> dir('__builtins__')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', '_formatter_field_name_split', '_formatter_parser',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
>>>
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)¶
>>> subprocess.call(["ls", "-l"])
0
>>> subprocess.call("exit 1", shell=True)
1
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)¶
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output("exit 1", shell=True)
Traceback (most recent call last):
   ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
  • le module sys, paramètres et fonctions systèmes
sys.argv

la ligne de commande

sys.exit()

terminer un programme

sys.path

ce qu’il y a dans le PYTHONPATH

  • le module optparse pour faire des outils ligne de commande

module plus récent : argparse

#!/usr/bin/env python

"""
Module docstring.
"""

import sys
import optparse

def process_command_line(argv):
    """
    Return a 2-tuple: (settings object, args list).
    `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
    """
    if argv is None:
        argv = sys.argv[1:]

    # initialize the parser object:
    parser = optparse.OptionParser(
        formatter=optparse.TitledHelpFormatter(width=78),
        add_help_option=None)

    # define options here:
    parser.add_option(      # customized description; put --help last
        '-h', '--help', action='help',
        help='Show this help message and exit.')

    settings, args = parser.parse_args(argv)

    # check number of arguments, verify values, etc.:
    if args:
        parser.error('program takes no command-line arguments; '
                     '"%s" ignored.' % (args,))

    # further process settings & args if necessary

    return settings, args

def main(argv=None):
    settings, args = process_command_line(argv)
    # application code here, like:
    # run(settings, args)
    return 0        # success

if __name__ == '__main__':
    status = main()
    sys.exit(status)
  • les modules de tests unitaires unittest et doctests
  • le module xml.etree pour parser du xml
tree = xml.parse("testFile.xml")
rootElement = tree.getroot()
bookList = rootElem.findall("Books")
if bookList != None:
    for book in bookList:
        #faire quelque chose avec les livres
  • le module urllib pour parser les urls et les manipuler (urllib2)
urllib.urlopen(url)

lit une url distante

  • time pour la manipulation de temps
t1 = time.clock()
# Do Stuff Here
t2 = time.clock()
print t2 - t1

now

import time
now = time.localtime(time.time())
dateStr = time.strftime("%A, %B %d, %Y,  %I:%M %p", now)
print dateStr
  • le module getpass pour gérer les motes de passe
>>> import getpass
>>> p = getpass.getpass()
Password:
>>> p
'toto'
>>>
  • linéarisation de données
>>> import shelve
>>> shelve.open("database", 'c')
{}
>>> s = shelve.open("database", 'c')
>>> s
{}
>>> s["o"] = ('a', 'b', 'c')
>>> s.cl
s.clear  s.close
>>> s.cl
s.clear  s.close
>>> s.close()
>>>
  • le module abc pour faire des interfaces propres
abc.register(subclass)

exemple

from abc import ABCMeta

class MyABC:
    __metaclass__ = ABCMeta

MyABC.register(tuple)

assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
import hotshot
prof = hotshot.Profile('toto.txt')
prof.runcall(make_description)
prof.close()
  • un exemple de librairie externe : IPy
sudo apt-get install python-ipy
from IPy import IP

try:
    ipy = IP('{0}/{1}'.format(ip, mask), make_net=True)
except ValueError:
    print "marche pas"
network = ipy.net()
broadcast = ipy.broadcast()
return broadcast, network