Python 交互式 Shell 类型应用程序

问题描述 投票:0回答:4

我想创建一个交互式 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
4个回答
16
投票

只是循环中的

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 使用它。


10
投票

构建此类交互式应用程序的另一种方法是使用 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
$

0
投票

您可以首先查看 argparse

它并不像您所要求的那样提供完整的交互式 shell,但它有助于创建与 PHP 示例类似的功能。


0
投票

如果您只想在网络浏览器中运行 python,您可以尝试 Python 交互式控制台

© www.soinside.com 2019 - 2024. All rights reserved.