Almighty Bus Error

Blog about computer science, code snippets and tips.

GitHub repository with examples here.
Currently a Computer Engineering student at FCT/UNL.
August 25, 2009 at 8:06pm
Tags: FTP  Python 

Comments (View)

FTP in Python

In Python, to create and maintain a FTP communication, the ftplib or urllib (explained in a future post) can be used.

Creating a FTP connection

from ftplib import FTP
try:
    conn = FTP('almightybuserror.com')
except:
    print "Could not connect to almightybuserror.com."
    return

Logging in…

For anonymous log in: try: conn.login() except: print "No anonymous connections allowed." return

Otherwise:

try:
    conn.login(user, passwd)
    print conn.getwelcome()
except:
    print "Wrong username or password."
    return

Sending commands and handling response.

To send commands (or requests) to the server there is a method for each command which can be consulted here, however I will show an example of an binary file download request.

try:
    conn.cwd('/stuff/more/misc/stuff/')
except:
    print "No such folder!"
    return
file = open('stuff', 'w')
try:
    conn.retrbinary('RETR stuff', file.write) 
    # file.write acts as a function pointer
except:
    print "Couldn't download stuff..."
finally:
    file.close()

Check downloader.py in github for a more complete example.

August 22, 2009 at 5:51pm
Tags: HTTP  Python 

Comments (View)

HTTP in Python

To create and HTTP connection we use the httplib module which provides some simple yet effective methods to create a connection and send requests to an HTTP server. The module urllib can also be used and is easier, does, however only perform GET requests (explained in a future post).

Creating a connection

To create a connection, the method HTTPConnection does the job. For example:

import httplib
try:
    http = httplib.HTTPConnection('almightybuserror.com')
except:
    print 'Could not connect...'
    return

Sending a request

To send a request, a connection object is needed (we’ll use http from the previous example):

http.request("GET", "/")

Getting a response

To obtain a response, the getResponse() method is used. From this method we get a HTTPResponse object.

response = http.getResponse()
if response.status == httplib.OK:
    file = open('example.html', 'w')
    file.write(response.read())
    file.close()
else:
    print 'Error: %s %s' % (response.status, response.reason)
    return

For a more complete example check downloader.py in github.

August 3, 2009 at 9:49pm

Comments (View)

Snippet.Py: Getting an image resolution

Using PIL (Python Image Library) it is possible to get the width and height of a image using the property size.

The following example will take an undefined number of arguments and print all the resolutions:

import Image
import sys

def main():
    argv = sys.argv[1:]
    if (len(argv) == 0):
        print "No file given!"
    else:
        for name in argv:
            img = Image.open(name)
            print name + ": %d %d" % img.size

if __name__ == "__main__":
    main()

Credit for the snippet goes to meqif. The code can also be found at git.

April 17, 2009 at 8:26pm
Tags: Snippet  Python 

Comments (View)

Snippet.Py: Showing all the filenames in a directory

The following Python code prints the name of the chosen directory and all the files in it and then proceeds to print all the files in the other nested directories one nested directory at a time. This method is recursive for nested directories.

def print_dir(loc):
    print loc + "\n"
    for root, dirs, files in os.walk(loc):
        for f in files:
           print f + "\n"
        for d in dirs:
           print_dir(os.path.join(loc, d))
    return