使用Python脚本中的命令创建原始输入

发布于 2021-01-29 15:01:19

我正在尝试实现一个小的脚本,以便通过命令行并使用适当的“
ftplib”模块在Python中使用FTP连接管理本地主机。我想为用户创建某种原始输入,但是已经设置了一些命令。

我尝试更好地解释:

一旦我已经创建FTP连接,登录连接成功通过用户名和密码完成后,我会表现出一种“bash
shell的”与可能性的使用最有名的UNIX命令(例如cdls分别在目录中,并显示移动当前路径中的文件/文件夹)。

例如,我可以这样做:

> cd "path inside localhost"

因此显示目录或:

> ls

显示该特定路径中的所有文件和目录。我不知道如何执行此操作,所以请您提出一些建议。

我非常感谢您的帮助。

关注者
0
被浏览
54
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    听起来命令行界面就是您要询问的那部分。将用户输入映射到命令的一种好方法是使用字典,并且在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()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看