(blog ‘lucindo)

um dia eu aprendo a programar

Arquivo da categoria ‘python’

Como tomar decisões

Agora pouco, no IM:

trajber: vou pedir ajuda ao meu querido PC
trajber: mauro@trajber:~$ python
Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49)
[GCC 4.3.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import random
>>> print random.randint(0,1)
trajber: 0 = ignorar
trajber: 1 = comer
trajber: ok ?
trajber: 0
>>>
trajber: foi justo…

Outro também fez algo parecido: http://twitter.com/igorrs/status/896944758

Sem comentários »

ACE_Task-like em Python

Nos últmos dias me reanimei a voltar a postar nesse blog.

Estou tentando mudar para Python como a minha principal linguagem de script, mas ainda preciso aprender a programar direito nessa linguagem. Enquanto isso não acontece, eu fico replicando código de outros lugares, como a cópia de pobre da ACE_Task abaixo:

import threading, Queue, signal

class Task(object):
    def __init__(self):
        self.queue = Queue.Queue(0)

    def __worker(self):
        while True:
            item = self.queue.get()
            self.process(item)
            self.queue.task_done()

    def __start(self):
        thread = threading.Thread(target=self.__worker)
        thread.setDaemon(True)
        thread.start()

    def activate(self, threads):
        for thread in xrange(threads):
            self.__start()
        signal.signal(signal.SIGINT, signal.SIG_DFL)

    def put(self, item):
        self.queue.put(item)

    def wait(self):
        self.queue.join()

    def process(self, item):
        pass

class task(Task):
    def __init__(self, func):
        Task.__init__(self)
        self.process = func

A única coisa pytônica do código é o decorator do final.

Bom, um exemplo de uso: digamos que você é um spammer e quer mandar vários emails. Você tem um arquivo em que cada linha tem as seguintes informações: servidor; email; subject; mensagem. Tudo separado por ponto e vírgula.

Usando o decorator acima o código ficaria mais ou menos assim (usando 100 threads):

from __future__ import with_statement
from task import task
import smtplib, sys

@task
def send_spam(item):
    server, toaddr, subject, msg = item.strip().split(‘;’)
    fromaddr = ’spammer@evil.org’
    message = (“From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s”
               % (fromaddr, toaddr, subject, msg))
    try:
        smtp = smtplib.SMTP(server)
        smtp.sendmail(fromaddr, toaddr, message)
    except Exception:
        pass

def process_file(filename):
    send_spam.activate(100)
    with open(filename) as file:
        map(lambda line: send_spam.put(line), file.readlines())
    send_spam.wait()

if __name__ == ‘__main__’:
    process_file(sys.argv[1])

Coloquei esse exemplo porque não tinha um melhor… é apenas um exemplo, não um programa de verdade, ok? :-P

Download: task.py

To do: reescrever em Python 2.6 usando Multiprocessos

2 comentários »

The Zen of Python

marvin:~ lucindo$ python
Python 2.5.2 (r252:60911, Apr 26 2008, 14:32:15)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>>
Sem comentários »

Mudança de planos

python - python

Sem comentários »