imaplib - Ejemplo muy básico

23 de July de 2007, a las 21:29  

Programación, Python No hay comentarios »

Estoy de vuelta con python, que desde antes de examenes no había tocado nada. Y como estoy llegando al final del Learning Python, donde he visto que existe la librería poplib, me ha dado por probar imaplib.

Dejo aquí un sencillo ejemplo que muestra todos los mensajes de un buzón IMAP.

 
#!/usr/bin/python
 
import imaplib, getpass
 
if __name__ == '__main__':
 
	host = raw_input('Host: ')
	user = raw_input('User: ')
	passw = getpass.getpass('Password: ')
 
	mail = imaplib.IMAP4(host)
	mail.login(user,passw)
	mail.select()
 
	typ, data = mail.search(None, 'ALL')
	for num in data[0].split():
		typ, data = mail.fetch(num, '(RFC822)')
		print '\\n----------------------------------\\n',
		print 'Message %s' % num,
		print '\\n----------------------------------\\n',
		print '\\n%s\\n' % data[0][1]
		raw_input('Next message...')
 
	mail.close()
	mail.logout()
 

Argument parsing with OptionParser

5 de March de 2007, a las 0:31  es

Programación, Python No hay comentarios »

From Python 2.3 we've the module optparse on standard library, which serve us for parse options and arguments passed to our programs, doing it easy and handy.

Here's an example:

 
from optparse import OptionParser
 
if __name__ == '__main__':
    usage = "%prog [options] arg1 arg2"
 
    parser = OptionParser(usage=usage, version="%prog 1.0")
    parser.add_option('-v','--verbose', action='store_true',
                      dest='verbose', help='shows detailed information')
    parser.add_option('-q','--quiet', action='store_false',
                      dest='verbose', help='hides detailed information')
    parser.add_option('-f','--filename', action='store',
                      dest='filename', help='name of the file to load')
 
    (options, args) = parser.parse_args()
 
    if options.verbose:
        print "Extra info enabled"
    else:
        print "Extra info disabled"
    if options.filename:
        print "I'll open", options.filename, "file."
    if args > 0:
        print "\nArguments:"
        for x in args:
            print "  ",x
 

Let's see some results depending on arguments passed:

$ python option.py

Extra info disabled
$ python option.py -v

Extra info enabled
$ python option.py -h

usage: option.py [options] arg1 arg2

options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         shows detailed information
  -q, --quiet           hides detailed information
  -f FILENAME, --filename=FILENAME
                        name of the file to load
$ python option.py -f fichero.txt "First" "Second" "Last argument"

Extra info disabled
I'll open fichero.txt file.

Arguments:
   First
   Second
   Last argument

Notice it knows options from arguments, as you can see in the last example.

HTML parsing with BeautifulSoup

28 de February de 2007, a las 19:54  es

Programación, Python No hay comentarios »

I'm gonna put an example using BeautifulSoup, a Python module which we can parse HTML.

First we've to download the library from here. Once installed, let's see the simple example:

 
from BeautifulSoup import BeautifulSoup
 
html = '''<html><head><title>Titulo de la pagina</title></head>
  <body>
<div id="cabecera">
<h1>Cabecera</h1>
</div>
<div id="contenido">
    Vamos a poner una lista.
 
    Lista:
<ul id="lista1">
<li>Elemento 1</li>
<li>Elemento 2</li>
<li>Elemento 3</li>
<li>Elemento 4</li>
</ul></div>
 
  </body>
  </html>'''
 
soup = BeautifulSoup(html)
 
# Mostramos el titulo de la pagina
print soup.head.title.string
 
# Mostramos la cabecera
print soup.find("div",{"id":"cabecera"}).contents
 
# Mostramos el contenido
contenido = soup.find("div",{"id":"contenido"})
print contenido.contents
 
# Ahora mostramos todos los elementos de lista1
lista = contenido.find("ul",{"id":"lista1"})
for x in lista:
    print x.string
 

Instead of a string with html code we can read from an URL on this way:

 
...
import urllib2
 
sock = urllib2.urlopen("http://servidor/documento.html")
soup = BeautifulSoup(sock.read())
...
 

It's a very simple sample, for details read the BeautifulSoup documentation.

Twitter Updater

20 de January de 2007, a las 13:37  es

Programación, Python, Utiles 1 comentario »

After I saw the script made by felipe, for twitting basecamp TODOs, I made another one (more simpler) in Python, it's just for twitt from console. So, for instance, I just can do Alt+F2 in KDE (or directly in a console) and write twupdater "Exams are out!".

Not an existential thing, but it has give me some phreak time. And while I had the chance to trying http in python.

Here is:

twupdater_v02.tar.gz

Update: Now the script ask user and pass if them is not configured.
Last update: Furthermore, now checks user and pass before send status.

New book received

3 de January de 2007, a las 21:49  es

Libros, Personal, Python 2 comentarios »

I was sleeping this morning when a ring has waked up me. It's made me quite angry, but all turned different when I've opened the door, "Hi I've a book for you" WOW. The Programming Python 3rd Edition book that I ordered on 13th december has arrived to me. I got really surprised.

The book is on quite good state, only two small scratches. It's big, almost double size of Programming Perl. At all it has brigthen up me today.

RSS entradas RSS Comentarios Log in