An application like Interactive Shell Python

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

> ./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 the infinte loop, getting user input, breaking 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, for example, to configure web applications. Is there something similar in Python (I am using Python 3)

+4
source share
3 answers

Just input commands in a loop.

For parsing input, shlex.split is a good option. Or just go with a simple str.split .

 import readline import shlex print('Enter a command to do something, eg `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 features (up arrow) and more. Python's interactive shell uses it.

+9
source

Another approach to creating interactive applications like this is 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 result of running the above code (if the above code was in a file called 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 $ 
+1
source

You can start by looking at argparse .

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

0
source

Source: https://habr.com/ru/post/1397175/


All Articles