Python - 创建一个命令行,如接口,用于加载模块/函数

时间:2013-05-02 11:55:55

标签: python command-line interface module

在我的Python项目中,我试图使界面有点像命令提示符,我可以在其中键入函数的名称,它将被执行。 例如:

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

在上面的示例中,当我键入run.check时,它应该运行一个名为check的函数,run.get应该运行函数get等等。

现在我有一个使用raw_input的提示,我可以通过使用函数别名和函数名称的字典来执行命令,即

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

COMMANDS.get(cmd, invalidFunction)()

但我的程序中的很多函数需要传递给它的参数,我不知道如何处理这个方法。 另一件事是,我的项目的主要目的是将模块(.py文件)添加到文件夹,然后使用命令提示符(如接口)使用主python程序动态执行,我希望以最小的方式执行此操作可能没有改变主程序。

我不确定使用exec函数,因为它在安全方面有一些缺点。

谢谢。

1 个答案:

答案 0 :(得分:1)

我有两个解决方案。一个exec,一个eval。您可以将它们作为实现自己的基础:

  1. 这是一个粗略的解决方案,使用exec执行命令并动态加载模块:

    >>> 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. 如果您不想使用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', ...]