¡Esta es una revisión vieja del documento!
>>> 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
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
from string import Template s = Template('$who is from $where') d = {} d['who'] = 'Bill' d['where'] = 'Boston' p = s.substitute(d)
def decorator(cls):
class Wrapper(object):
def __init__(self,*args,**kwargs):
self.wrapper = cls(*args,**kwargs)
"""
def __getattr__(self, name, *args, **kwargs):
print('Getting the {} of {}, {}, {}'.format(name, self.wrapped, repr(args), repr(kwargs)))
return getattr(self.wrapped, name)
"""
def __getattr__(self, attr):
print attr
def wrapper(*args, **kw):
print('called with %r and %r' % (args, kw))
return getattr(self.wrapper, attr)(*args, **kw)
return wrapper
return Wrapper
@decorator
class C(object):
def method(self, x, y):
print 'b'
if __name__ == '__main__':
c = C()
c.method(1,2)
#!/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])
Path from where the script was called:
cwd = os.getcwd()
File name from a path:
os.path.basename(value)
class Saved():
def __init__(self, cr):
self.cr = cr
def __enter__(self):
self.cr.save()
return self.cr
def __exit__(self, type, value, traceback):
self.cr.restore()
cr.translate(68, 68)
for i in xrange(6):
with Saved(cr):
cr.rotate(2 * math.pi * i / 6)
cr.rectangle(-25, -60, 50, 40)
cr.stroke()
Crear un proceso y leer lo que sale por pantalla:
>>> a = subprocess.check_output('ls')
>>> a
b'alpine.tar\napps\nbin\nbuild\ncbf_git.txt\ncoma_git.txt\ndbcompare.venv\nDesktop\ndist\nDocuments\nDownloads\nexample.retry\nexample.yml\nfabfile.py\nflowRoot884.png\ngitea.dockerfiles\ngitea.tar\njenkins_home\nlogo2.png\nlogo2_small.png\nmanage.py\nMusic\nnew-repo\nPictures\n-proxy\nPublic\nREADME.md\nrema\nrequirements.txt\nresources\nscript.py\nTemplates\ntmp\nVideos\nvoid\nworkspace\nWorkspace\n'
The same but not using a bytestring:
>>> print(subprocess.check_output('ls', universal_newlines=True))
alpine.tar
apps
bin
build
cbf_git.txt
coma_git.txt
dbcompare.venv
Desktop
dist
...
Since running ls -l is that ls is the command, and -l is a flag to that command.
>>> print(subprocess.check_output(['ls', '-l'], universal_newlines=True)) total 103160 -rw------- 1 alfred alfred 5801472 Apr 8 14:46 alpine.tar drwxrwxr-x 9 alfred alfred 4096 Apr 29 15:49 apps drwxrwxr-x 3 alfred alfred 4096 Dec 18 14:33 bin drwxrwxr-x 4 alfred alfred 4096 Apr 29 15:49 build -rw-rw-r-- 1 alfred alfred 880 Jan 14 10:34 cbf_git.txt ...