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?

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

I'm not sure if I understand you... How does the code get executed if not by exec?
cmd2 can be used as drop-in replacement that provides additional features pypi.python.org/pypi/cmd2
@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']()
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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.