Python 交互式 Shell 类型应用程序

发布于 2025-01-07 04:55:40 字数 540 浏览 0 评论 0原文

我想创建一个交互式 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 控制台) 中,它们也允许您创建控制台命令例如,帮助设置 Web 应用程序。 Python中有类似的东西吗? (我使用的是Python 3)

I want to create an interactive shell type application. For example:

> ./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 
...

I could of course use an infinte loop getting user input, splitting the line to get the individual parts of the command, but is there a better way? Even in PHP (Symfony 2 Console) they allow you to create console commands to help setup web applications for example. Is there something like that in Python? (I am using Python 3)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幼儿园老大 2025-01-14 04:55:40

只需在循环中输入命令即可。

为了解析输入,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 使用它。

Just input the commands in a loop.

For parsing the input, shlex.split is a nice option. Or just go with plain 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))

The readline library adds history functionality (up arrow) and more. Python interactive shell uses it.

绻影浮沉 2025-01-14 04:55:40

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

Another approach to building interactive applications like this is by using the cmd module.

# 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`.')

And here is the output of running the above code (if the above code was in a file named 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
$
困倦 2025-01-14 04:55:40

您可以首先查看 argparse

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

You could start by having a look at argparse.

It does not provide a complete interactive shell, like you ask, but it helps in creating functionality similar to your PHP example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文