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

(yzsuai) #1
C:\...\PP4E\Internet\Ftp> del sousa.au

C:\...\PP4E\Internet\Ftp> python
>>> from getfile import getfile
>>> getfile(file='sousa.au', site='ftp.rmi.net', dir='.', user=('lutz', 'XXX'))
Downloading sousa.au
Download done.

>>> from PP4E.System.Media.playfile import playfile
>>> playfile('sousa.au')

Although Python’s ftplib already automates the underlying socket and message for-
matting chores of FTP, tools of our own like these can make the process even simpler.


Adding a User Interface


If you read the preceding chapter, you’ll recall that it concluded with a quick look at
scripts that added a user interface to a socket-based getfile script—one that transferred
files over a proprietary socket dialog, instead of over FTP. At the end of that presenta-
tion, I mentioned that FTP is a much more generally useful way to move files around
because FTP servers are so widely available on the Net. For illustration purposes,
Example 13-7 shows a simple mutation of the prior chapter’s user interface, imple-
mented as a new subclass of the preceding chapter’s general form builder, form.py of
Example 12-20.


Example 13-7. PP4E\Internet\Ftp\getfilegui.py


"""
#################################################################################
launch FTP getfile function with a reusable form GUI class; uses os.chdir to
goto target local dir (getfile currently assumes that filename has no local
directory path prefix); runs getfile.getfile in thread to allow more than one
to be running at once and avoid blocking GUI during downloads; this differs
from socket-based getfilegui, but reuses Form GUI builder tool; supports both
user and anonymous FTP as currently coded;


caveats: the password field is not displayed as stars here, errors are printed
to the console instead of shown in the GUI (threads can't generally update the
GUI on Windows), this isn't 100% thread safe (there is a slight delay between
os.chdir here and opening the local output file in getfile) and we could
display both a save-as popup for picking the local dir, and a remote directory
listing for picking the file to get; suggested exercises: improve me;
#################################################################################
"""


from tkinter import Tk, mainloop
from tkinter.messagebox import showinfo
import getfile, os, sys, _thread # FTP getfile here, not socket
from PP4E.Internet.Sockets.form import Form # reuse form tool in socket dir


class FtpForm(Form):
def init(self):
root = Tk()


Transferring Files with ftplib | 867
Free download pdf