PageRenderTime 25ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/IronPython_2_0/Src/Scripts/run_interactive.py

#
Python | 139 lines | 97 code | 22 blank | 20 comment | 18 complexity | 824e8ad45b4f9534feb7e559c12b4843 MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Microsoft Public License. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Microsoft Public License, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Microsoft Public License.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. import sys
  16. import clr
  17. sys.path.append(sys.exec_prefix)
  18. clr.AddReference("Microsoft.Scripting.dll")
  19. clr.AddReference("Microsoft.Scripting.Core.dll")
  20. clr.AddReference("IronPython.dll")
  21. clr.AddReference("IronPython.Modules.dll")
  22. from Microsoft.Scripting import SourceCodeKind, ErrorSink
  23. from Microsoft.Scripting.Hosting import ScriptRuntime
  24. from Microsoft.Scripting.Hosting.Providers import HostingHelpers
  25. from Microsoft.Scripting.Runtime import CompilerContext
  26. from IronPython import PythonOptions
  27. from IronPython.Hosting import Python
  28. from IronPython.Runtime import PythonContext, ModuleOptions, Symbols
  29. from IronPython.Compiler import Parser, PythonCompilerOptions
  30. from IronPython.Compiler.Ast import SuiteStatement, FunctionDefinition
  31. from System import Type, Array, UriBuilder
  32. from System.Reflection import Assembly
  33. from System.IO import Directory, Path, File
  34. #--------------------------------------------------------------------------------------
  35. # Class that takes a file and runs it in interactive mode using the hosting APIs
  36. class FileConsole(object):
  37. def __init__(self, fileName):
  38. scriptEnv = Python.CreateRuntime()
  39. self.fileName = fileName
  40. self.engine = scriptEnv.GetEngine("python")
  41. self.context = HostingHelpers.GetLanguageContext(self.engine)
  42. scriptEnv.LoadAssembly(Type.GetType("System.String").Assembly) #mscorlib.dll
  43. scriptEnv.LoadAssembly(UriBuilder().GetType().Assembly) #System.dll
  44. self.InitializePath()
  45. executable = Assembly.GetEntryAssembly().Location
  46. prefix = Path.GetDirectoryName(executable)
  47. self.context.SystemState.Dict["executable"] = executable
  48. self.context.SystemState.Dict["exec_prefix"] = self.context.SystemState.Dict["prefix"] = prefix
  49. module = self.context.CreateModule(ModuleOptions.ModuleBuiltins)
  50. self.context.PublishModule("__main__", module)
  51. module.Scope.SetName(Symbols.Doc, None)
  52. module.Scope.SetName(Symbols.File, fileName)
  53. module.Scope.SetName(Symbols.Name, "__main__")
  54. self.mainScope = self.engine.CreateScope(module.Scope.Dict)
  55. def InitializePath(self):
  56. searchPath = []
  57. currentDir = Directory.GetCurrentDirectory()
  58. searchPath.append(currentDir)
  59. filePathDir = Path.GetDirectoryName(Path.Combine(currentDir, self.fileName))
  60. searchPath.append(filePathDir)
  61. entryDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
  62. searchPath.append(entryDir)
  63. siteDir = Path.Combine(entryDir, "Lib")
  64. searchPath.append(siteDir)
  65. dllsDir = Path.Combine(entryDir, "DLLs")
  66. if Directory.Exists(dllsDir):
  67. searchPath.append(dllsDir)
  68. self.engine.SetSearchPaths(Array[str](searchPath))
  69. def CreateASTFromFile(self, fileName):
  70. completeCode = self.engine.CreateScriptSourceFromFile(fileName)
  71. sourceUnit = HostingHelpers.GetSourceUnit(completeCode)
  72. cc = CompilerContext(sourceUnit, PythonCompilerOptions(), ErrorSink.Default)
  73. parser = Parser.CreateParser(cc, PythonOptions())
  74. return parser.ParseFile(False), sourceUnit.GetCode()
  75. def GetCodeForStatement(self, codeText, statement):
  76. decoratorStart, decoratorLength = -1, 0
  77. if isinstance(statement, FunctionDefinition):
  78. if (statement.Decorators != None and statement.Decorators.Count != 0):
  79. decoratorStart = min([x.Start.Index for x in statement.Decorators])
  80. decoratorLength = statement.Start.Index - decoratorStart
  81. return codeText.Substring( statement.Start.Index if decoratorStart == -1 else decoratorStart, statement.Span.Length + decoratorLength)
  82. def Run(self):
  83. ast, codeText = self.CreateASTFromFile(self.fileName)
  84. if isinstance(ast.Body, SuiteStatement):
  85. suiteStatement = ast.Body
  86. for statement in suiteStatement.Statements:
  87. code = self.GetCodeForStatement(codeText, statement)
  88. codeUnit = self.engine.CreateScriptSourceFromString(code, SourceCodeKind.InteractiveCode)
  89. codeProps = codeUnit.GetCodeProperties()
  90. codeUnit.Execute(self.mainScope)
  91. #--------------------------------------------------------------------------------------
  92. def run_interactive_main():
  93. #if the commandline was invoked so: ipy run_interactive.py test_x.py then run just that one test.
  94. testName = sys.argv[1] if len(sys.argv) > 1 else None
  95. if testName:
  96. testsToRun = Directory.GetFiles(Directory.GetCurrentDirectory() , testName)
  97. else:
  98. print "No test name provided"
  99. sys.exit(-1)
  100. allErrors = []
  101. for test in testsToRun:
  102. try:
  103. print "\nRunning test in interactive mode - ", test
  104. con = FileConsole(test)
  105. con.Run()
  106. except:
  107. allErrors.append((test, sys.exc_info()[0], sys.exc_info()[1]))
  108. if(allErrors):
  109. print "\n##################################################################################"
  110. print "Summary of all errors"
  111. for file, type, message in allErrors:
  112. print file, type, message
  113. sys.exit(len(allErrors))
  114. #--------------------------------------------------------------------------------------
  115. if __name__ == "__main__":
  116. run_interactive_main()
  117. #--------------------------------------------------------------------------------------