interp.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Python.Interpreter COM Server
  2. This module implements a very very simple COM server which
  3. exposes the Python interpreter.
  4. This is designed more as a demonstration than a full blown COM server.
  5. General functionality and Error handling are both limited.
  6. To use this object, ensure it is registered by running this module
  7. from Python.exe. Then, from Visual Basic, use "CreateObject('Python.Interpreter')",
  8. and call its methods!
  9. """
  10. from win32com.server.exception import Exception
  11. import winerror
  12. # Expose the Python interpreter.
  13. class Interpreter:
  14. """The interpreter object exposed via COM
  15. """
  16. _public_methods_ = [ 'Exec', 'Eval' ]
  17. # All registration stuff to support fully automatic register/unregister
  18. _reg_verprogid_ = "Python.Interpreter.2"
  19. _reg_progid_ = "Python.Interpreter"
  20. _reg_desc_ = "Python Interpreter"
  21. _reg_clsid_ = "{30BD3490-2632-11cf-AD5B-524153480001}"
  22. _reg_class_spec_ = "win32com.servers.interp.Interpreter"
  23. def __init__(self):
  24. self.dict = {}
  25. def Eval(self, exp):
  26. """Evaluate an expression.
  27. """
  28. if type(exp) != str:
  29. raise Exception(desc="Must be a string",scode=winerror.DISP_E_TYPEMISMATCH)
  30. return eval(str(exp), self.dict)
  31. def Exec(self, exp):
  32. """Execute a statement.
  33. """
  34. if type(exp) != str:
  35. raise Exception(desc="Must be a string",scode=winerror.DISP_E_TYPEMISMATCH)
  36. exec(str(exp), self.dict)
  37. def Register():
  38. import win32com.server.register
  39. return win32com.server.register.UseCommandLine(Interpreter)
  40. if __name__=='__main__':
  41. print("Registering COM server...")
  42. Register()