假设我有一个 python 程序,它是一个黑匣子,它的作用就像一个处理器。它读取带有一些指令名称的文本文件,解析该文件并从类 Instructions 调用函数。我想要的是允许用户在另一个文件中创建新函数,并允许处理器通过指令类调用这些函数。
示例处理器代码(无法更改):
from instructions import *
instr = Instructions()
code = []
with open('program.txt') as f:
code = f.readlines()
for line in code:
command, args = line.split()
# reads "command arg" and calls "instr.command(arg)"
string_exec = 'instr.{}({})'.format(command, args)
eval(string_exec)
示例说明.py:
class Instructions:
def show(self, arg):
print(arg, end='')
处理器读取以打印“Hello”的“program.txt”示例:
show 'H'
show 'e'
show 'l'
show 'l'
show 'o'
show '\n'
我希望能够使用新指令从用户读取文件并能够在处理器中执行它们。
也使用指令的用户函数示例:
def print_line(self, args):
for arg in args:
instr.show(arg)
instr.show('\n')
我想以某种方式将用户函数合并到类 Intructions 中,以便处理器能够运行以下“program.txt”:
print_line 'Hello'
简而言之,我想将指令功能分为两个文件,一个是一些基本的“固定”指令,另一个是用户定义的“动态”功能。最后,我想在类说明中加载这两个函数。
像这样的指令.py:
class Instructions:
def __init__(self):
self._add_user_function()
def add(self, a, b):
return a + b
def _add_user_function(self):
import os
if not os.path.exists('user_instructions.py'):
return
from user_instructions import UserInstructions
self._user_instrucs = UserInstructions(self)
for prop in dir(self._user_instrucs):
if prop.startswith('_'):
continue
prop_type = type(eval("UserInstructions.%s" % prop))
if str(prop_type).find("instancemethod") < 0:
continue
func_str = "def instr_custom_%s(self, *args, **kwargs):\n return self._user_instrucs.%s(*args, **kwargs)\n " % (prop, prop)
exec(func_str)
setattr(Instructions, prop, eval("instr_custom_%s" % prop))
def show(self, arg):
print(arg)
user_instructions.py 如下所示:
class UserInstructions:
def __init__(self, instr):
self.__instr = instr
def print_line(self, args):
print(args)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句