tags:

views:

100

answers:

2

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?

+6  A: 

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

Ned Batchelder
I'm not sure if I understand you... How does the code get executed if not by exec?
Wilduck
`cmd2` can be used as drop-in replacement that provides additional features http://pypi.python.org/pypi/cmd2
J.F. Sebastian
@Wilduck: In Python, a function is a first class object, and can be stored in dictionaries, assigned to variables, and invoked. def foo(): pass; d = {'xyz': foo}; d['xyz']()
Ned Batchelder
@Ned I had mulled over this for a bit, and ended up discovering that little bit of code on my own. I'll probably end up using cmd, but I'm glad I learned this as well.
Wilduck
A: 

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

Mike Graham