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

(yzsuai) #1

from ftplib import FTP # socket-based FTP tools
from os.path import exists # file existence test


def getfile(file, site, dir, user=(), , verbose=True, refetch=False):
"""
fetch a file by ftp from a site/directory
anonymous or real login, binary transfer
"""
if exists(file) and not refetch:
if verbose: print(file, 'already fetched')
else:
if verbose: print('Downloading', file)
local = open(file, 'wb') # local file of same name
try:
remote = FTP(site) # connect to FTP site
remote.login(
user) # anonymous=() or (name, pswd)
remote.cwd(dir)
remote.retrbinary('RETR ' + file, local.write, 1024)
remote.quit()
finally:
local.close() # close file no matter what
if verbose: print('Download done.') # caller handles exceptions


if name == 'main':
from getpass import getpass
file = 'monkeys.jpg'
dir = '.'
site = 'ftp.rmi.net'
user = ('lutz', getpass('Pswd?'))
getfile(file, site, dir, user)


This module is mostly just a repackaging of the FTP code we used to fetch the image
file earlier, to make it simpler and reusable. Because it is a callable function, the exported
getfile.getfile here tries to be as robust and generally useful as possible, but even a
function this small implies some design decisions. Here are a few usage notes:


FTP mode
The getfile function in this script runs in anonymous FTP mode by default, but
a two-item tuple containing a username and password string may be passed to the
user argument in order to log in to the remote server in nonanonymous mode. To
use anonymous FTP, either don’t pass the user argument or pass it an empty tuple,
(). The FTP object login method allows two optional arguments to denote a user-
name and password, and the function(*args) call syntax in Example 13-4 sends
it whatever argument tuple you pass to user as individual arguments.


Processing modes
If passed, the last two arguments (verbose, refetch) allow us to turn off status
messages printed to the stdout stream (perhaps undesirable in a GUI context) and
to force downloads to happen even if the file already exists locally (the download
overwrites the existing local file).


862 | Chapter 13: Client-Side Scripting

Free download pdf