ExecCode.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class ExecUtil:
  2. tmpMap = {}
  3. @classmethod
  4. def exec_code(cls, function_str, call_str, param_dict):
  5. """
  6. 动态执行函数,必须按照示例的函数传入,设计到提取函数方法和参数
  7. :param function_str: 函数代码
  8. :param call_str:
  9. :param param_dict: 入参
  10. :return:
  11. """
  12. result = {}
  13. tmp_key = "tmp_result_625d7c4c3daa411f9cf8b14441e65539"
  14. function_str += f"\n{tmp_key}['res']={call_str}"
  15. if function_str in cls.tmpMap:
  16. cmp_code = cls.tmpMap[function_str]
  17. else:
  18. cmp_code = compile(function_str, '', 'exec')
  19. cls.tmpMap[function_str] = cmp_code
  20. exec(cmp_code, {}, {**param_dict, tmp_key: result})
  21. return result['res']
  22. # cmd_str = """
  23. # def factorial(num):
  24. # fact=1
  25. # for i in range(1,num+1):
  26. # fact = fact*i
  27. # return fact
  28. # """
  29. #
  30. # start = time.time()
  31. # for x in range(10000):
  32. # ExecUtil.exec_code(cmd_str, 'factorial(num)', {"num": 3})
  33. # print(time.time() - start)
  34. class User:
  35. def __init__(self):
  36. self.dic = {}
  37. self.a = 0
  38. def test1(self, b):
  39. print(ExecUtil.exec_code("""
  40. def test2(self, b):
  41. import time
  42. print(time.time())
  43. self.dic['c'] = b+1
  44. self.a = b
  45. return b+2
  46. """, "test2(self, b)", {"self": self, "b": b}))
  47. user = User()
  48. user.test1(3)
  49. print(user.dic)