Python - Creating a command line like interface for loading modules/functions

In my Python project I'm trying to make the interface somewhat like a command prompt where I can type the name of a function and it will be executed. Example:

Prompt >>> run.check
Running function check....
Prompt >>> run.get
Running function get

In the above example when I type run.check it should run a function named check and run.get should run function get and so on.

Right now I have a prompt using raw_input and I can execute commands by using a dictionary of function alias' and function names ie,

COMMANDS = {'exit': sys.exit,
 'hello': greet,
 'option3': function3,
 'option4': function4,
}
cmd = raw_input("Prompt >>> ")

COMMANDS.get(cmd, invalidFunction)()

But a lot of the functions in my programs needs arguments to be passed to it which I do not know how to do with this method. Another thing is that, the main purpose of my project is for modules (.py files) to be added to a folder and then executed dynamically with the main python program using the command prompt like interface and I would like to do this with minimum if possible no change to the main program.

I'm not sure of using the function exec as it has some drawbacks concerning security.

Thank You.

Answers


I have two solutions. one with exec and one with eval. You can use them as a basis to implement your own:

  1. This is a rough solution using exec to execute the commands and dynamically load the modules:

    >>> class MyDict(dict):
        def __getitem__(self, name):
            # overwrite __getitem__ for access of unknown variables
            print 'name in self:', name in self
            if not name in self:
                # TODO: handle ImportError
                module = __import__(name)
                return module
            return dict.__getitem__(self, name)
    
    
    >>> d = MyDict(x = 1)
    >>> exec 'print x' in d
    name in self: True
    1
    >>> exec 'print os' in d # this loads the os module because the variable os is not defined
    name in self: False
    <module 'os' from '/usr/lib64/python2.7/os.pyc'>
    
  2. If you do not want to use exec:

    >>> def exec_in_module(string):
        module, command = string.split('.', 1)
        module = __import__(module)
        try:
            return eval(command, module.__dict__)
        except SyntaxError:
            exec command in module.__dict__
            return None
    
    
    >>> exec_in_module('os.listdir(".")')
    ['README.md', ...]
    

Need Your Help

Horizontal Nested List using CSS

css list nested horizontallist

I'm trying to create a horizontal list from a nested list markup, as an example I have the current markup:

3 approaches to work with XML

c# xml

I need to use different approaches when working with XML - LINQ to XML, streaming, DOM.

how do you embed an interactive Google Map on a GAS standalone app?

google-maps gwt google-maps-api-3 google-apps-script

I want to create a GAS standalone web app that will have a google map embedded. Visitors will see their location, drag around and will be able to pin details that can be seen by other users. User c...