Python - Creating a command line like interface for loading modules/functions -
in python project i'm trying make interface command prompt can type name of function , executed. example:
prompt >>> run.check running function check.... prompt >>> run.get running function
in above example when type run.check should run function named check , run.get should run function , on.
right have prompt using raw_input , can execute commands using dictionary of function alias' , function names ie,
commands = {'exit': sys.exit, 'hello': greet, 'option3': function3, 'option4': function4, } cmd = raw_input("prompt >>> ") commands.get(cmd, invalidfunction)()
but lot of functions in programs needs arguments passed not know how method. thing that, main purpose of project modules (.py files) added folder , executed dynamically main python program using command prompt interface , minimum if possible no change main program.
i'm not sure of using function exec has drawbacks concerning security.
thank you.
i have 2 solutions. 1 exec
, 1 eval
. can use them basis implement own:
this rough solution using exec execute commands , dynamically load modules:
>>> class mydict(dict): def __getitem__(self, name): # overwrite __getitem__ 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 # loads os module because variable os not defined name in self: false <module 'os' '/usr/lib64/python2.7/os.pyc'>
if not want 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', ...]
Comments
Post a Comment