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

(yzsuai) #1

filename = 'monkeys.jpg' # remote/local filename
password = getpass.getpass('Pswd?')


remoteaddr = 'ftp://lutz:%[email protected]/%s;type=i' % (password, filename)
print('Downloading', remoteaddr)


this works too:


urllib.request.urlretrieve(remoteaddr, filename)


remotefile = urlopen(remoteaddr) # returns input file-like object
localfile = open(filename, 'wb') # where to store data locally
localfile.write(remotefile.read())
localfile.close()
remotefile.close()


Note how we use a binary mode output file again; urllib fetches return byte strings,
even for HTTP web pages. Don’t sweat the details of the URL string used here; it is
fairly complex, and we’ll explain its structure and that of URLs in general in Chap-
ter 15. We’ll also use urllib again in this and later chapters to fetch web pages, format
generated URL strings, and get the output of remote scripts on the Web.


Technically speaking, urllib.request supports a variety of Internet protocols (HTTP,
FTP, and local files). Unlike ftplib, urllib.request is generally used for reading remote
objects, not for writing or uploading them (though the HTTP and FTP protocols sup-
port file uploads too). As with ftplib, retrievals must generally be run in threads if
blocking is a concern. But the basic interface shown in this script is straightforward.
The call:


remotefile = urllib.request.urlopen(remoteaddr) # returns input file-like object

contacts the server named in the remoteaddr URL string and returns a file-like object
connected to its download stream (here, an FTP-based socket). Calling this file’s
read method pulls down the file’s contents, which are written to a local client-side file.
An even simpler interface:


urllib.request.urlretrieve(remoteaddr, filename)

also does the work of opening a local file and writing the downloaded bytes into it—
things we do manually in the script as coded. This comes in handy if we want to down-
load a file, but it is less useful if we want to process its data immediately.


Either way, the end result is the same: the desired server file shows up on the client
machine. The output is similar to the original version, but we don’t try to automatically
open this time (I’ve changed the password in the URL here to protect the innocent):


C:\...\PP4E\Internet\Ftp> getone-urllib.py
Pswd?
Downloading ftp://lutz:[email protected]/monkeys.jpg;type=i

C:\...\PP4E\Internet\Ftp> fc monkeys.jpg test\monkeys.jpg
FC: no differences encountered

C:\...\PP4E\Internet\Ftp> start monkeys.jpg

Transferring Files with ftplib | 859
Free download pdf