Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Interactive Shell Type Application

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 a 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)

like image 886
Jiew Meng Avatar asked Feb 18 '12 10:02

Jiew Meng


People also ask

What is interactive Python shell?

Python interactive shell is also known as Integrated Development Environment (IDLE). With the Python installer, two interactive shells are provided: one is IDLE (Python GUI) and the other is Python (command line). Both can be used for running simple programs.

How do I get interactive shell in Python?

To start the Python language shell (the interactive shell), first open a terminal or command prompt. Then type the command python and press enter. Type "help", "copyright", "credits" or "license" for more information. After the symbols >>> you can type a line of Python code, or a command.

Why is Python called as the interactive shell?

Python offers a comfortable command line interface with the Python Shell, which is also known as the "Python Interactive Shell". It looks like the term "Interactive Shell" is a tautology, because "shell" is interactive on its own, at least the kind of shells we have described in the previous paragraphs.

How do you make an interactive program in Python?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.


1 Answers

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.

like image 169
Oleh Prypin Avatar answered Sep 22 '22 19:09

Oleh Prypin