Foundations of Python Network Programming

(WallPaper) #1
Chapter 17 ■ Ftp

325

ftp = FTP('ftp.kernel.org')
ftp.login()
ftp.cwd('/pub/linux/kernel/v1.0')
ftp.voidcmd("TYPE I")


socket, size = ftp.ntransfercmd("RETR linux-1.0.tar.gz")
nbytes = 0


f = open('linux-1.0.tar.gz', 'wb')


while True:
data = socket.recv(2048)
if not data:
break
f.write(data)
nbytes += len(data)
print("\rReceived", nbytes, end=' ')
if size:
print("of %d total bytes (%.1f%%)"
% (size, 100 * nbytes / float(size)), end=' ')
else:
print("bytes", end=' ')
sys.stdout.flush()


print()
f.close()
socket.close()
ftp.voidresp()
ftp.quit()


if name == 'main':
main()


Note that the first thing you do when finished with the transfer is to call datasock.close(). When uploading
data, closing the socket is the signal to the server that the upload is complete! If you fail to close the data socket after
uploading all of your data, the server will keep waiting for the rest of the data to arrive.
Now you can perform an upload that continuously displays its status as it progresses:


$ python binaryul.py localhost brandon patch8.gz /tmp
Enter password for brandon on localhost:
Sent 6408 of 6408 bytes (100.0%)


Handling Errors

Like most Python modules, ftplib will raise an exception when an error occurs. It defines several exceptions of its
own, and it can also raise socket.error and IOError. As a convenience, it offers a tuple, named ftplib.all_errors,
which lists all of the exceptions that can possibly be raised by ftplib. This is often a useful shortcut for writing a
try...except clause.

Free download pdf