runscript.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 time
  12. import tokenize
  13. from tkinter import messagebox
  14. from idlelib.config import idleConf
  15. from idlelib import macosx
  16. from idlelib import pyshell
  17. from idlelib.query import CustomRun
  18. from idlelib import outwin
  19. indent_message = """Error: Inconsistent indentation detected!
  20. 1) Your indentation is outright incorrect (easy to fix), OR
  21. 2) Your indentation mixes tabs and spaces.
  22. To fix case 2, change all tabs to spaces by using Edit->Select All followed \
  23. by Format->Untabify Region and specify the number of columns used by each tab.
  24. """
  25. class ScriptBinding:
  26. def __init__(self, editwin):
  27. self.editwin = editwin
  28. # Provide instance variables referenced by debugger
  29. # XXX This should be done differently
  30. self.flist = self.editwin.flist
  31. self.root = self.editwin.root
  32. # cli_args is list of strings that extends sys.argv
  33. self.cli_args = []
  34. self.perf = 0.0 # Workaround for macOS 11 Uni2; see bpo-42508.
  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_custom_event(self, event):
  94. return self.run_module_event(event, customize=True)
  95. def run_module_event(self, event, *, customize=False):
  96. """Run the module after setting up the environment.
  97. First check the syntax. Next get customization. If OK, make
  98. sure the shell is active and then transfer the arguments, set
  99. the run environment's working directory to the directory of the
  100. module being executed and also add that directory to its
  101. sys.path if not already included.
  102. """
  103. if macosx.isCocoaTk() and (time.perf_counter() - self.perf < .05):
  104. return 'break'
  105. if isinstance(self.editwin, outwin.OutputWindow):
  106. self.editwin.text.bell()
  107. return 'break'
  108. filename = self.getfilename()
  109. if not filename:
  110. return 'break'
  111. code = self.checksyntax(filename)
  112. if not code:
  113. return 'break'
  114. if not self.tabnanny(filename):
  115. return 'break'
  116. if customize:
  117. title = f"Customize {self.editwin.short_title()} Run"
  118. run_args = CustomRun(self.shell.text, title,
  119. cli_args=self.cli_args).result
  120. if not run_args: # User cancelled.
  121. return 'break'
  122. self.cli_args, restart = run_args if customize else ([], True)
  123. interp = self.shell.interp
  124. if pyshell.use_subprocess and restart:
  125. interp.restart_subprocess(
  126. with_cwd=False, filename=filename)
  127. dirname = os.path.dirname(filename)
  128. argv = [filename]
  129. if self.cli_args:
  130. argv += self.cli_args
  131. interp.runcommand(f"""if 1:
  132. __file__ = {filename!r}
  133. import sys as _sys
  134. from os.path import basename as _basename
  135. argv = {argv!r}
  136. if (not _sys.argv or
  137. _basename(_sys.argv[0]) != _basename(__file__) or
  138. len(argv) > 1):
  139. _sys.argv = argv
  140. import os as _os
  141. _os.chdir({dirname!r})
  142. del _sys, argv, _basename, _os
  143. \n""")
  144. interp.prepend_syspath(filename)
  145. # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
  146. # go to __stderr__. With subprocess, they go to the shell.
  147. # Need to change streams in pyshell.ModifiedInterpreter.
  148. interp.runcode(code)
  149. return 'break'
  150. def getfilename(self):
  151. """Get source filename. If not saved, offer to save (or create) file
  152. The debugger requires a source file. Make sure there is one, and that
  153. the current version of the source buffer has been saved. If the user
  154. declines to save or cancels the Save As dialog, return None.
  155. If the user has configured IDLE for Autosave, the file will be
  156. silently saved if it already exists and is dirty.
  157. """
  158. filename = self.editwin.io.filename
  159. if not self.editwin.get_saved():
  160. autosave = idleConf.GetOption('main', 'General',
  161. 'autosave', type='bool')
  162. if autosave and filename:
  163. self.editwin.io.save(None)
  164. else:
  165. confirm = self.ask_save_dialog()
  166. self.editwin.text.focus_set()
  167. if confirm:
  168. self.editwin.io.save(None)
  169. filename = self.editwin.io.filename
  170. else:
  171. filename = None
  172. return filename
  173. def ask_save_dialog(self):
  174. msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
  175. confirm = messagebox.askokcancel(title="Save Before Run or Check",
  176. message=msg,
  177. default=messagebox.OK,
  178. parent=self.editwin.text)
  179. return confirm
  180. def errorbox(self, title, message):
  181. # XXX This should really be a function of EditorWindow...
  182. messagebox.showerror(title, message, parent=self.editwin.text)
  183. self.editwin.text.focus_set()
  184. self.perf = time.perf_counter()
  185. if __name__ == "__main__":
  186. from unittest import main
  187. main('idlelib.idle_test.test_runscript', verbosity=2,)