runscript.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """Execute code from an editor.
  2. Check module: do a full syntax check of the current module.
  3. Also run the tabnanny to catch any inconsistent tabs.
  4. Run module: also execute the module's code in the __main__ namespace.
  5. The window must have been saved previously. The module is added to
  6. sys.modules, and is also added to the __main__ namespace.
  7. TODO: Specify command line arguments in a dialog box.
  8. """
  9. import os
  10. import tabnanny
  11. import tokenize
  12. import tkinter.messagebox as tkMessageBox
  13. from idlelib.config import idleConf
  14. from idlelib import macosx
  15. from idlelib import pyshell
  16. from idlelib.query import CustomRun
  17. from idlelib import outwin
  18. indent_message = """Error: Inconsistent indentation detected!
  19. 1) Your indentation is outright incorrect (easy to fix), OR
  20. 2) Your indentation mixes tabs and spaces.
  21. To fix case 2, change all tabs to spaces by using Edit->Select All followed \
  22. by Format->Untabify Region and specify the number of columns used by each tab.
  23. """
  24. class ScriptBinding:
  25. def __init__(self, editwin):
  26. self.editwin = editwin
  27. # Provide instance variables referenced by debugger
  28. # XXX This should be done differently
  29. self.flist = self.editwin.flist
  30. self.root = self.editwin.root
  31. # cli_args is list of strings that extends sys.argv
  32. self.cli_args = []
  33. if macosx.isCocoaTk():
  34. self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
  35. def check_module_event(self, event):
  36. if isinstance(self.editwin, outwin.OutputWindow):
  37. self.editwin.text.bell()
  38. return 'break'
  39. filename = self.getfilename()
  40. if not filename:
  41. return 'break'
  42. if not self.checksyntax(filename):
  43. return 'break'
  44. if not self.tabnanny(filename):
  45. return 'break'
  46. return "break"
  47. def tabnanny(self, filename):
  48. # XXX: tabnanny should work on binary files as well
  49. with tokenize.open(filename) as f:
  50. try:
  51. tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
  52. except tokenize.TokenError as msg:
  53. msgtxt, (lineno, start) = msg.args
  54. self.editwin.gotoline(lineno)
  55. self.errorbox("Tabnanny Tokenizing Error",
  56. "Token Error: %s" % msgtxt)
  57. return False
  58. except tabnanny.NannyNag as nag:
  59. # The error messages from tabnanny are too confusing...
  60. self.editwin.gotoline(nag.get_lineno())
  61. self.errorbox("Tab/space error", indent_message)
  62. return False
  63. return True
  64. def checksyntax(self, filename):
  65. self.shell = shell = self.flist.open_shell()
  66. saved_stream = shell.get_warning_stream()
  67. shell.set_warning_stream(shell.stderr)
  68. with open(filename, 'rb') as f:
  69. source = f.read()
  70. if b'\r' in source:
  71. source = source.replace(b'\r\n', b'\n')
  72. source = source.replace(b'\r', b'\n')
  73. if source and source[-1] != ord(b'\n'):
  74. source = source + b'\n'
  75. editwin = self.editwin
  76. text = editwin.text
  77. text.tag_remove("ERROR", "1.0", "end")
  78. try:
  79. # If successful, return the compiled code
  80. return compile(source, filename, "exec")
  81. except (SyntaxError, OverflowError, ValueError) as value:
  82. msg = getattr(value, 'msg', '') or value or "<no detail available>"
  83. lineno = getattr(value, 'lineno', '') or 1
  84. offset = getattr(value, 'offset', '') or 0
  85. if offset == 0:
  86. lineno += 1 #mark end of offending line
  87. pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
  88. editwin.colorize_syntax_error(text, pos)
  89. self.errorbox("SyntaxError", "%-20s" % msg)
  90. return False
  91. finally:
  92. shell.set_warning_stream(saved_stream)
  93. def run_module_event(self, event):
  94. if macosx.isCocoaTk():
  95. # Tk-Cocoa in MacOSX is broken until at least
  96. # Tk 8.5.9, and without this rather
  97. # crude workaround IDLE would hang when a user
  98. # tries to run a module using the keyboard shortcut
  99. # (the menu item works fine).
  100. self.editwin.text_frame.after(200,
  101. lambda: self.editwin.text_frame.event_generate(
  102. '<<run-module-event-2>>'))
  103. return 'break'
  104. else:
  105. return self._run_module_event(event)
  106. def run_custom_event(self, event):
  107. return self._run_module_event(event, customize=True)
  108. def _run_module_event(self, event, *, customize=False):
  109. """Run the module after setting up the environment.
  110. First check the syntax. Next get customization. If OK, make
  111. sure the shell is active and then transfer the arguments, set
  112. the run environment's working directory to the directory of the
  113. module being executed and also add that directory to its
  114. sys.path if not already included.
  115. """
  116. if isinstance(self.editwin, outwin.OutputWindow):
  117. self.editwin.text.bell()
  118. return 'break'
  119. filename = self.getfilename()
  120. if not filename:
  121. return 'break'
  122. code = self.checksyntax(filename)
  123. if not code:
  124. return 'break'
  125. if not self.tabnanny(filename):
  126. return 'break'
  127. if customize:
  128. title = f"Customize {self.editwin.short_title()} Run"
  129. run_args = CustomRun(self.shell.text, title,
  130. cli_args=self.cli_args).result
  131. if not run_args: # User cancelled.
  132. return 'break'
  133. self.cli_args, restart = run_args if customize else ([], True)
  134. interp = self.shell.interp
  135. if pyshell.use_subprocess and restart:
  136. interp.restart_subprocess(
  137. with_cwd=False, filename=filename)
  138. dirname = os.path.dirname(filename)
  139. argv = [filename]
  140. if self.cli_args:
  141. argv += self.cli_args
  142. interp.runcommand(f"""if 1:
  143. __file__ = {filename!r}
  144. import sys as _sys
  145. from os.path import basename as _basename
  146. argv = {argv!r}
  147. if (not _sys.argv or
  148. _basename(_sys.argv[0]) != _basename(__file__) or
  149. len(argv) > 1):
  150. _sys.argv = argv
  151. import os as _os
  152. _os.chdir({dirname!r})
  153. del _sys, argv, _basename, _os
  154. \n""")
  155. interp.prepend_syspath(filename)
  156. # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
  157. # go to __stderr__. With subprocess, they go to the shell.
  158. # Need to change streams in pyshell.ModifiedInterpreter.
  159. interp.runcode(code)
  160. return 'break'
  161. def getfilename(self):
  162. """Get source filename. If not saved, offer to save (or create) file
  163. The debugger requires a source file. Make sure there is one, and that
  164. the current version of the source buffer has been saved. If the user
  165. declines to save or cancels the Save As dialog, return None.
  166. If the user has configured IDLE for Autosave, the file will be
  167. silently saved if it already exists and is dirty.
  168. """
  169. filename = self.editwin.io.filename
  170. if not self.editwin.get_saved():
  171. autosave = idleConf.GetOption('main', 'General',
  172. 'autosave', type='bool')
  173. if autosave and filename:
  174. self.editwin.io.save(None)
  175. else:
  176. confirm = self.ask_save_dialog()
  177. self.editwin.text.focus_set()
  178. if confirm:
  179. self.editwin.io.save(None)
  180. filename = self.editwin.io.filename
  181. else:
  182. filename = None
  183. return filename
  184. def ask_save_dialog(self):
  185. msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
  186. confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
  187. message=msg,
  188. default=tkMessageBox.OK,
  189. parent=self.editwin.text)
  190. return confirm
  191. def errorbox(self, title, message):
  192. # XXX This should really be a function of EditorWindow...
  193. tkMessageBox.showerror(title, message, parent=self.editwin.text)
  194. self.editwin.text.focus_set()
  195. if __name__ == "__main__":
  196. from unittest import main
  197. main('idlelib.idle_test.test_runscript', verbosity=2,)