Herramientas de usuario

Herramientas del sitio


wiki2:python:basic

¡Esta es una revisión vieja del documento!


Python basic recipes

Base lib

dicts

pop

>>> a = {'a': 1, 'b': 2}
>>> a.pop('a')
1
>>> a
{'b': 2}
>>> a.pop('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> a.pop('a', 0)
0

Custom parameters in logging

import logging
extra = {'app_name':'Super App'}

logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.setLevel(logging.INFO)
logger.addHandler(syslog)

logger = logging.LoggerAdapter(logger, extra)
logger.info('The sky is so blue')

logs (something like): 2013-07-09 17:39:33,596 Super App : The sky is so blue

Strings

Template

from string import Template
s = Template('$who is from $where')
 
d = {}
d['who'] = 'Bill'
d['where'] = 'Boston'
 
p = s.substitute(d)

Call several Python functions

#!/usr/bin/python
# -*- coding: utf-8 *-*
 
def funciona (a, b):
	return a + b
 
calls = [(funciona, {'a': 1, 'b': 3})]
 
for c in calls:
	print c[0](**c[1])
wiki2/python/basic.1484926015.txt.gz · Última modificación: 2020/05/09 09:24 (editor externo)