【问题标题】:Python Interactive Shell Type ApplicationPython 交互式 Shell 类型应用程序
【发布时间】:2012-02-18 10:28:01
【问题描述】:

我想创建一个交互式 shell 类型的应用程序。例如:

> ./app.py

Enter a command to do something. eg `create name price`. 
For to get help, enter "help" (without quotes)

> create item1 10
Created "item1", cost $10

> del item1
Deleted item1

> exit 
...

我当然可以使用无限循环来获取用户输入,拆分行来获取命令的各个部分,但是有更好的方法吗?即使在PHP (Symfony 2 Console) 中,它们也允许您创建控制台命令来帮助设置 Web 应用程序。 Python中是否有类似的东西(我使用的是Python 3)

【问题讨论】:

    标签: python-3.x console-application


    【解决方案1】:

    只需input 循环中的命令。

    对于解析输入,shlex.split 是一个不错的选择。或者直接使用简单的str.split

    import readline
    import shlex
    
    print('Enter a command to do something, e.g. `create name price`.')
    print('To get help, enter `help`.')
    
    while True:
        cmd, *args = shlex.split(input('> '))
    
        if cmd=='exit':
            break
    
        elif cmd=='help':
            print('...')
    
        elif cmd=='create':
            name, cost = args
            cost = int(cost)
            # ...
            print('Created "{}", cost ${}'.format(name, cost))
    
        # ...
    
        else:
            print('Unknown command: {}'.format(cmd))
    

    readline 库添加了历史记录功能(向上箭头)等。 Python 交互式 shell 使用它。

    【讨论】:

    • 我认为您不会愿意注释您的答案以表明它是 Python 3。我知道问题是这样说的,但是我们中的一些人在阅读了问题的标题后跳到了答案.因为 *args 和 input vs raw_input 功能对我来说都是新的,所以我只是对此有所了解。
    • @sage 使用旧版本的 Python 是您的问题。我认为不应该表明我使用了新版本的东西,而不是你想的反之亦然。此外,甚至还有标签 [python-3.x]。此外,为 Python 2.7 修改它相当简单。
    • 我完全同意你没有义务评论你没有使用旧版本。修改它很容易。这些事情都没有改变,小评论会使您的答案对更多人更有用;在这一点上,我们的 cmets 做同样的事情。搜索最近的新闻,我很惊讶有多少人没有迁移——事实上,我更惊讶地发现 Python 3 已经推出了多长时间。我想我迟到了迁移...
    【解决方案2】:

    另一种构建此类交互式应用程序的方法是使用cmd 模块。

    # app.py
    from cmd import Cmd
    
    class MyCmd(Cmd):
    
        prompt = "> "
    
        def do_create(self, args):
            name, cost = args.rsplit(" ", 1) # args is string of input after create
            print('Created "{}", cost ${}'.format(name, cost))
    
        def do_del(self, name):
            print('Deleted {}'.format(name))
    
        def do_exit(self, args):
            raise SystemExit()
    
    if __name__ == "__main__":
    
        app = MyCmd()
        app.cmdloop('Enter a command to do something. eg `create name price`.')
    

    这是运行上面代码的输出(如果上面的代码在一个名为app.py的文件中):

    $ python app.py
    Enter a command to do something. eg `create name price`.
    > create item1 10
    Created "item1", cost $10
    > del item1
    Deleted item1
    > exit
    $
    

    【讨论】:

      【解决方案3】:

      您可以先查看argparse

      它没有像你问的那样提供完整的交互式 shell,但它有助于创建类似于你的 PHP 示例的功能。

      【讨论】:

      • 是的,我看到了,主要问题是它运行一次然后退出。我需要一些“交互式”的东西。不过谢谢
      猜你喜欢
      • 2012-08-17
      • 2013-03-28
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 2012-06-09
      • 2011-09-01
      • 2017-09-19
      • 1970-01-01
      相关资源
      最近更新 更多