1

コマンドラインからPythonでFTP接続を使用してローカルホストを管理し、適切な「ftplib」モジュールを使用する小さなスクリプトを実装しようとしています。ユーザー用の生の入力のようなものを作成したいのですが、いくつかのコマンドが既に設定されています。

私はよりよく説明しようとします:

FTP 接続を作成し、ユーザー名とパスワードを使用してログイン接続が正常に完了すると、一種の「bash シェル」が表示され、最も有名な UNIX コマンドを使用できる可能性があります (たとえばcdlsそれぞれディレクトリに移動して表示する現在のパスのファイル/フォルダー)。

たとえば、私はこれを行うことができます:

> cd "path inside localhost"

したがって、ディレクトリまたは次を表示します。

> ls

その特定のパスにあるすべてのファイルとディレクトリを表示します。これを実装する方法がわからないので、アドバイスをお願いします。

助けてくれてありがとう。

4

1 に答える 1

3

コマンドラインインターフェースは、あなたが求めている部分のようです。ユーザー入力をコマンドにマップする 1 つの良い方法は、辞書を使用することです。Python では、名前の後に () を付けることで関数への参照を実行できます。これが私の言いたいことを示す簡単な例です

def firstThing():  # this could be your 'cd' task
    print 'ran first task'

def secondThing(): # another task you would want to run
    print 'ran second task'

def showCommands(): # a task to show available commands
    print functionDict.keys()

# a dictionary mapping commands to functions (you could do the same with classes)
functionDict = {'f1': firstThing, 'f2': secondThing, 'help': showCommands}

# the actual function that gets the input
def main():
    cont = True
    while(cont):
        selection = raw_input('enter your selection ')
        if selection == 'q': # quick and dirty way to give the user a way out
            cont = False
        elif selection in functionDict.keys():
            functionDict[selection]()
        else:
            print 'my friend, you do not know me. enter help to see VALID commands'

if __name__ == '__main__':
    main()
于 2013-04-06T20:04:49.180 に答える