【问题标题】:Create a raw input with commands inside a Python script在 Python 脚本中使用命令创建原始输入
【发布时间】:2013-03-29 02:56:05
【问题描述】:

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

我试着解释得更好:

一旦我创建了 FTP 连接并通过用户名和密码成功完成登录连接,我将展示一种“bash shell”,可以使用最著名的 UNIX 命令(例如 cd 和 @987654325 @分别在目录中移动并显示当前路径中的文件/文件夹)。

例如我可以这样做:

> cd "path inside localhost"

因此显示目录或:

> ls

显示该特定路径中的所有文件和目录。我不知道如何实现这一点,所以我问你一些建议。

非常感谢您的帮助。

【问题讨论】:

  • 看看curses模块,你可以使用subprocess模块执行shell命令。
  • 或者os 模块?它有 listdir() 和 chdir() 函数。
  • @AshwiniChaudhary 我正在寻找 NotNamedDwayne 解决方案,但无论如何感谢您的宝贵建议。

标签: python raw-input ftplib


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-31
    • 2011-07-20
    • 2015-01-18
    • 2021-03-23
    • 1970-01-01
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多