Because the Python FTP interface is so easy to use, let’s jump right into a realistic example. The script in Example 13-1 automatically fetches (a.k.a. “downloads”) and opens a remote file with Python. More specifically, this Python script does the following:
The download portion will run on any machine with Python and an Internet connection, though you’ll probably want to change the script’s settings so it accesses a server and file of your own. The opening part works if your playfile.py supports your platform; see Chapter 6 for details, and change as needed.
Example 13-1. PP4E\Internet\Ftp\getone.py
#!/usr/local/bin/python """ A Python script to download and play a media file by FTP. Uses ftplib, the ftp protocol handler which uses sockets. Ftp runs on 2 sockets (one for data, one for control--on ports 20 and 21) and imposes message text formats, but Python's ftplib module hides most of this protocol's details. Change for your site/file. """ import os, sys from getpass import getpass # hidden password input from ftplib import FTP # socket-based FTP tools nonpassive = False # force active mode FTP for server? filename = 'monkeys.jpg' # file to be downloaded dirname = '.' # remote directory to fetch from sitename = 'ftp.rmi.net' # FTP site to contact userinfo = ('lutz', getpass('Pswd?')) # use () for anonymous if len(sys.argv) ...