Wilduck
Wilduck

Reputation: 14096

Correct way to create a shell like environment in python?

I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exec".

Is there a more correct way of doing this?

Upvotes: 2

Views: 303

Answers (2)

Mike Graham
Mike Graham

Reputation: 76683

If it is a Python interactive interpreter you are making, check out the code module.

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375564

The standard library module cmd is specifically for this.

If you do end up rolling your own solution, there's no need to involve exec. Your dictionary mapping commands to code should map strings to strings. It can map strings to actual functions. In fact, a class is a mapping of strings to code (method names to method definitions).

Upvotes: 6

Related Questions