1
\$\begingroup\$

I'm learning Python and decided to rewrite my FTP tool from Perl to Python. The program is able to up/download files, change the directory and list the files of the current directory.

Is there anything I can improve?

#!/usr/bin/python

import time
import sys 
import os
from ftplib import FTP
import getpass

def menue():
    print "1) Verzeichnisse auflisten"
    print "2) Verzeichnis wechseln"
    print "3) Datei hochladen"
    print "4) Datei runterladen"
    print "9) Programm beenden"
    choice = raw_input("Was wollen Sie tun? ")
    return choice

def connect(counter):
    user = raw_input("User: ")
    password = getpass.getpass()
    ftp = FTP('xxxxxx') 
    ftp.login(user, password)
    counter += 1
    return ftp, counter

def list_dir( ftp ):
    ftp.retrlines('LIST')

def chd_dir( ftp ):
    change_choice = raw_input("In welches Verzeichnis moechten Sie wechseln? ")
    if change_choice not in ftp.nlst():
        print "Das angegebene Verzeichnis existiert nicht!"
    else:
        ftp.cwd(change_choice)

def upl_file( ftp ):
    file_upl = raw_input("Bitte geben Sie den Dateinamen an: ")
    curr_dir = os.curdir
    if file_upl not in os.listdir(curr_dir):
        print "Die angegebene Datei existiert nicht!"
    else:
        ftp.storbinary('STOR ' +file_upl, open(file_upl, 'rb'))


def dwl_file( ftp ):
    file_dwl = raw_input("Bitte geben Sie den Dateinamen an: ")
    if file_dwl not in ftp.nlst():
        print "Die angegebene Datei existiert nicht!"
    else:
        ftp.retrbinary('RETR ' +file_dwl, open(file_dwl, 'wb').write)

counter = 0
while True:
    choice = menue()
    if choice == "9":
        print "Programm wird beendet..."
        time.sleep(1)
        sys.exit()
    if counter == 0:
        ftp, counter = connect(counter)
    if choice == "1":
        list_dir(ftp)
    elif choice == "2":
        chd_dir(ftp)
    elif choice == "3":
        upl_file(ftp)
    elif choice == "4":
        dwl_file(ftp)
    else:
        print "Falsche Eingabe!"

Python version 2.6.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You aren't doing proper error handling. For example, changing the directory could fail due to a permission problem. In addition to pre-screening each commands, you need to check the status returned by the server. In RFC 959, linked from the ftplib documentation, you'll see that status codes ≥ 400 indicate an error. (You'll need to include an English-to-German translation table for the errors listed in Section 4.2.2 of the RFC. Unfortunately, the errors aren't very specific as to the exact cause.)

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.