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

(yzsuai) #1

site = 'ftp.rmi.net' # Monty Python theme song
dir = '.'
user = ('lutz', getpass('Pswd?'))


getfile(file, site, dir, user) # fetch audio file by FTP
playfile(file) # send it to audio player


import os


os.system('getone.py sousa.au') # equivalent command line


There’s not much to this script, because it really just combines two tools we’ve already
coded. We’re reusing Example 13-4’s getfile to download, and Chapter 6’s play
file module (Example 6-23) to play the audio sample after it is downloaded (turn back
to that example for more details on the player part of the task). Also notice the last two
lines in this file—we can achieve the same effect by passing in the audio filename as a
command-line argument to our original script, but it’s less direct.


As is, this script assumes my FTP server account; configure as desired (alas, this file
used to be at the ftp.python.org anonymous FTP site, but that site went dark for security
reasons between editions of this book). Once configured, this script will run on any
machine with Python, an Internet link, and a recognizable audio player; it works on
my Windows laptop with a broadband Internet connection, and it plays the music clip
in Windows Media Player (and if I could insert an audio file hyperlink here to show
what it sounds like, I would...):


C:\...\PP4E\Internet\Ftp> sousa.py
Pswd?
Downloading sousa.au
Download done.

C:\...\PP4E\Internet\Ftp> sousa.py
Pswd?
sousa.au already fetched

The getfile and putfile modules themselves can be used to move the sample file
around too. Both can either be imported by clients that wish to use their functions, or
run as top-level programs to trigger self-tests and command-line usage. For variety, let’s
run these scripts from a command line and the interactive prompt to see how they work.
When run standalone, the filename is passed in the command line to putfile and both
use password input and default site settings:


C:\...\PP4E\Internet\Ftp> putfile.py sousa.py
ftp.rmi.net pswd?
Uploading sousa.py
Upload done.

When imported, parameters are passed explicitly to functions:


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

866 | Chapter 13: Client-Side Scripting

Free download pdf