[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

To open a connection to a remote (or local) FTP server, create an instance of the
ftplib.FTP object, passing in the string name (domain or IP style) of the machine you
wish to connect to:


connection = FTP(sitename) # connect to ftp site

Assuming this call doesn’t throw an exception, the resulting FTP object exports meth-
ods that correspond to the usual FTP operations. In fact, Python scripts act much like
typical FTP client programs—just replace commands you would normally type or select
with method calls:


connection.login(*userinfo) # default is anonymous login
connection.cwd(dirname) # xfer 1k at a time to localfile

Once connected, we log in and change to the remote directory from which we want to
fetch a file. The login method allows us to pass in a username and password as addi-
tional optional arguments to specify an account login; by default, it performs anony-
mous FTP. Notice the use of the nonpassive flag in this script:


if nonpassive: # force active FTP if server requires
connection.set_pasv(False)

If this flag is set to True, the script will transfer the file in active FTP mode rather than
the default passive mode. We’ll finesse the details of the difference here (it has to do
with which end of the dialog chooses port numbers for the transfer), but if you have
trouble doing transfers with any of the FTP scripts in this chapter, try using active mode
as a first step. In Python 2.1 and later, passive FTP mode is on by default. Now, open
a local file to receive the file’s content, and fetch the file:


localfile = open(filename, 'wb')
connection.retrbinary('RETR ' + filename, localfile.write, 1024)

Once we’re in the target remote directory, we simply call the retrbinary method to
download the target server file in binary mode. The retrbinary call will take a while to
complete, since it must download a big file. It gets three arguments:



  • An FTP command string; here, the string RETR filename, which is the standard
    format for FTP retrievals.

  • A function or method to which Python passes each chunk of the downloaded file’s
    bytes; here, the write method of a newly created and opened local file.

  • A size for those chunks of bytes; here, 1,024 bytes are downloaded at a time, but
    the default is reasonable if this argument is omitted.


Because this script creates a local file named localfile of the same name as the remote
file being fetched, and passes its write method to the FTP retrieval method, the remote
file’s contents will automatically appear in a local, client-side file after the download is
finished.


Observe how this file is opened in wb binary output mode. If this script is run on Win-
dows we want to avoid automatically expanding any \n bytes into \r\n byte sequences;


856 | Chapter 13: Client-Side Scripting

Free download pdf