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.
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.
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.
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