09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 17 ■ FTP<br />

In the listing, the cwd() function selects a new working directory on the remote system. Then the<br />

retrlines() function begins the transfer. Its first parameter specifies a command to run on the remote<br />

system, usually RETR, followed by a file name. Its second parameter is a function that is called, over and<br />

over again, as each line <strong>of</strong> the text file is retrieved; if omitted, the data is simply printed to standard<br />

output. The lines are passed with the end-<strong>of</strong>-line character stripped, so the homemade writeline()<br />

function simply appends your system’s standard line ending to each line as it is written out.<br />

Try running this program; there should be a file in your current directory named README after the<br />

program is done.<br />

Basic binary file transfers work in much the same way as text-file transfers; Listing 17–3 shows an<br />

example.<br />

Listing 17–3. Downloading a Binary File<br />

#!/usr/bin/env python<br />

# Binary upload - Chapter 17 - binarydl.py<br />

import os<br />

from ftplib import FTP<br />

if os.path.exists('patch8.gz'):<br />

» raise IOError('refusing to overwrite your patch8.gz file')<br />

f = FTP('ftp.kernel.org')<br />

f.login()<br />

f.cwd('/pub/linux/kernel/v1.0')<br />

fd = open('patch8.gz', 'wb')<br />

f.retrbinary('RETR patch8.gz', fd.write)<br />

fd.close()<br />

f.quit()<br />

When run, it deposits a file named patch8.gz in your current working directory. The retrbinary()<br />

function simply passes blocks <strong>of</strong> data to the specified function. This is convenient, since a file object’s<br />

write() function expects just such data—so in this case, no custom function is necessary.<br />

Advanced Binary Downloading<br />

The ftplib module provides a second function that can be used for binary downloading:<br />

ntransfercmd(). This command provides a lower-level interface, but can be useful if you want to know a<br />

little bit more about what’s going on during the download.<br />

In particular, this more advanced command lets you keep track <strong>of</strong> the number <strong>of</strong> bytes transferred,<br />

and you can use that information to display status updates for the user. Listing 17–4 shows a sample<br />

program that uses ntransfercmd().<br />

Listing 17–4. Binary Download with Status Updates<br />

#!/usr/bin/env python<br />

# Advanced binary download - Chapter 17 - advbinarydl.py<br />

import os, sys<br />

from ftplib import FTP<br />

295

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!