Python Interactive Shell Type Application

风流意气都作罢 提交于 2019-12-05 08:38:28

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.

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
$

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!