PageRenderTime 69ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/idlelib/PyShell.py

https://bitbucket.org/quangquach/pypy
Python | 1464 lines | 1343 code | 54 blank | 67 comment | 98 complexity | 0a1434b2023859f5893cb70345bbd707 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. #! /usr/bin/env python
  2. import os
  3. import os.path
  4. import sys
  5. import string
  6. import getopt
  7. import re
  8. import socket
  9. import time
  10. import threading
  11. import traceback
  12. import types
  13. import linecache
  14. from code import InteractiveInterpreter
  15. try:
  16. from Tkinter import *
  17. except ImportError:
  18. print>>sys.__stderr__, "** IDLE can't import Tkinter. " \
  19. "Your Python may not be configured for Tk. **"
  20. sys.exit(1)
  21. import tkMessageBox
  22. from idlelib.EditorWindow import EditorWindow, fixwordbreaks
  23. from idlelib.FileList import FileList
  24. from idlelib.ColorDelegator import ColorDelegator
  25. from idlelib.UndoDelegator import UndoDelegator
  26. from idlelib.OutputWindow import OutputWindow
  27. from idlelib.configHandler import idleConf
  28. from idlelib import idlever
  29. from idlelib import rpc
  30. from idlelib import Debugger
  31. from idlelib import RemoteDebugger
  32. from idlelib import macosxSupport
  33. IDENTCHARS = string.ascii_letters + string.digits + "_"
  34. HOST = '127.0.0.1' # python execution server on localhost loopback
  35. PORT = 0 # someday pass in host, port for remote debug capability
  36. try:
  37. from signal import SIGTERM
  38. except ImportError:
  39. SIGTERM = 15
  40. # Override warnings module to write to warning_stream. Initialize to send IDLE
  41. # internal warnings to the console. ScriptBinding.check_syntax() will
  42. # temporarily redirect the stream to the shell window to display warnings when
  43. # checking user's code.
  44. global warning_stream
  45. warning_stream = sys.__stderr__
  46. try:
  47. import warnings
  48. except ImportError:
  49. pass
  50. else:
  51. def idle_showwarning(message, category, filename, lineno,
  52. file=None, line=None):
  53. if file is None:
  54. file = warning_stream
  55. try:
  56. file.write(warnings.formatwarning(message, category, filename,
  57. lineno, line=line))
  58. except IOError:
  59. pass ## file (probably __stderr__) is invalid, warning dropped.
  60. warnings.showwarning = idle_showwarning
  61. def idle_formatwarning(message, category, filename, lineno, line=None):
  62. """Format warnings the IDLE way"""
  63. s = "\nWarning (from warnings module):\n"
  64. s += ' File \"%s\", line %s\n' % (filename, lineno)
  65. if line is None:
  66. line = linecache.getline(filename, lineno)
  67. line = line.strip()
  68. if line:
  69. s += " %s\n" % line
  70. s += "%s: %s\n>>> " % (category.__name__, message)
  71. return s
  72. warnings.formatwarning = idle_formatwarning
  73. def extended_linecache_checkcache(filename=None,
  74. orig_checkcache=linecache.checkcache):
  75. """Extend linecache.checkcache to preserve the <pyshell#...> entries
  76. Rather than repeating the linecache code, patch it to save the
  77. <pyshell#...> entries, call the original linecache.checkcache()
  78. (skipping them), and then restore the saved entries.
  79. orig_checkcache is bound at definition time to the original
  80. method, allowing it to be patched.
  81. """
  82. cache = linecache.cache
  83. save = {}
  84. for key in list(cache):
  85. if key[:1] + key[-1:] == '<>':
  86. save[key] = cache.pop(key)
  87. orig_checkcache(filename)
  88. cache.update(save)
  89. # Patch linecache.checkcache():
  90. linecache.checkcache = extended_linecache_checkcache
  91. class PyShellEditorWindow(EditorWindow):
  92. "Regular text edit window in IDLE, supports breakpoints"
  93. def __init__(self, *args):
  94. self.breakpoints = []
  95. EditorWindow.__init__(self, *args)
  96. self.text.bind("<<set-breakpoint-here>>", self.set_breakpoint_here)
  97. self.text.bind("<<clear-breakpoint-here>>", self.clear_breakpoint_here)
  98. self.text.bind("<<open-python-shell>>", self.flist.open_shell)
  99. self.breakpointPath = os.path.join(idleConf.GetUserCfgDir(),
  100. 'breakpoints.lst')
  101. # whenever a file is changed, restore breakpoints
  102. if self.io.filename: self.restore_file_breaks()
  103. def filename_changed_hook(old_hook=self.io.filename_change_hook,
  104. self=self):
  105. self.restore_file_breaks()
  106. old_hook()
  107. self.io.set_filename_change_hook(filename_changed_hook)
  108. rmenu_specs = [("Set Breakpoint", "<<set-breakpoint-here>>"),
  109. ("Clear Breakpoint", "<<clear-breakpoint-here>>")]
  110. def set_breakpoint(self, lineno):
  111. text = self.text
  112. filename = self.io.filename
  113. text.tag_add("BREAK", "%d.0" % lineno, "%d.0" % (lineno+1))
  114. try:
  115. i = self.breakpoints.index(lineno)
  116. except ValueError: # only add if missing, i.e. do once
  117. self.breakpoints.append(lineno)
  118. try: # update the subprocess debugger
  119. debug = self.flist.pyshell.interp.debugger
  120. debug.set_breakpoint_here(filename, lineno)
  121. except: # but debugger may not be active right now....
  122. pass
  123. def set_breakpoint_here(self, event=None):
  124. text = self.text
  125. filename = self.io.filename
  126. if not filename:
  127. text.bell()
  128. return
  129. lineno = int(float(text.index("insert")))
  130. self.set_breakpoint(lineno)
  131. def clear_breakpoint_here(self, event=None):
  132. text = self.text
  133. filename = self.io.filename
  134. if not filename:
  135. text.bell()
  136. return
  137. lineno = int(float(text.index("insert")))
  138. try:
  139. self.breakpoints.remove(lineno)
  140. except:
  141. pass
  142. text.tag_remove("BREAK", "insert linestart",\
  143. "insert lineend +1char")
  144. try:
  145. debug = self.flist.pyshell.interp.debugger
  146. debug.clear_breakpoint_here(filename, lineno)
  147. except:
  148. pass
  149. def clear_file_breaks(self):
  150. if self.breakpoints:
  151. text = self.text
  152. filename = self.io.filename
  153. if not filename:
  154. text.bell()
  155. return
  156. self.breakpoints = []
  157. text.tag_remove("BREAK", "1.0", END)
  158. try:
  159. debug = self.flist.pyshell.interp.debugger
  160. debug.clear_file_breaks(filename)
  161. except:
  162. pass
  163. def store_file_breaks(self):
  164. "Save breakpoints when file is saved"
  165. # XXX 13 Dec 2002 KBK Currently the file must be saved before it can
  166. # be run. The breaks are saved at that time. If we introduce
  167. # a temporary file save feature the save breaks functionality
  168. # needs to be re-verified, since the breaks at the time the
  169. # temp file is created may differ from the breaks at the last
  170. # permanent save of the file. Currently, a break introduced
  171. # after a save will be effective, but not persistent.
  172. # This is necessary to keep the saved breaks synched with the
  173. # saved file.
  174. #
  175. # Breakpoints are set as tagged ranges in the text. Certain
  176. # kinds of edits cause these ranges to be deleted: Inserting
  177. # or deleting a line just before a breakpoint, and certain
  178. # deletions prior to a breakpoint. These issues need to be
  179. # investigated and understood. It's not clear if they are
  180. # Tk issues or IDLE issues, or whether they can actually
  181. # be fixed. Since a modified file has to be saved before it is
  182. # run, and since self.breakpoints (from which the subprocess
  183. # debugger is loaded) is updated during the save, the visible
  184. # breaks stay synched with the subprocess even if one of these
  185. # unexpected breakpoint deletions occurs.
  186. breaks = self.breakpoints
  187. filename = self.io.filename
  188. try:
  189. with open(self.breakpointPath,"r") as old_file:
  190. lines = old_file.readlines()
  191. except IOError:
  192. lines = []
  193. try:
  194. with open(self.breakpointPath,"w") as new_file:
  195. for line in lines:
  196. if not line.startswith(filename + '='):
  197. new_file.write(line)
  198. self.update_breakpoints()
  199. breaks = self.breakpoints
  200. if breaks:
  201. new_file.write(filename + '=' + str(breaks) + '\n')
  202. except IOError as err:
  203. if not getattr(self.root, "breakpoint_error_displayed", False):
  204. self.root.breakpoint_error_displayed = True
  205. tkMessageBox.showerror(title='IDLE Error',
  206. message='Unable to update breakpoint list:\n%s'
  207. % str(err),
  208. parent=self.text)
  209. def restore_file_breaks(self):
  210. self.text.update() # this enables setting "BREAK" tags to be visible
  211. filename = self.io.filename
  212. if filename is None:
  213. return
  214. if os.path.isfile(self.breakpointPath):
  215. lines = open(self.breakpointPath,"r").readlines()
  216. for line in lines:
  217. if line.startswith(filename + '='):
  218. breakpoint_linenumbers = eval(line[len(filename)+1:])
  219. for breakpoint_linenumber in breakpoint_linenumbers:
  220. self.set_breakpoint(breakpoint_linenumber)
  221. def update_breakpoints(self):
  222. "Retrieves all the breakpoints in the current window"
  223. text = self.text
  224. ranges = text.tag_ranges("BREAK")
  225. linenumber_list = self.ranges_to_linenumbers(ranges)
  226. self.breakpoints = linenumber_list
  227. def ranges_to_linenumbers(self, ranges):
  228. lines = []
  229. for index in range(0, len(ranges), 2):
  230. lineno = int(float(ranges[index]))
  231. end = int(float(ranges[index+1]))
  232. while lineno < end:
  233. lines.append(lineno)
  234. lineno += 1
  235. return lines
  236. # XXX 13 Dec 2002 KBK Not used currently
  237. # def saved_change_hook(self):
  238. # "Extend base method - clear breaks if module is modified"
  239. # if not self.get_saved():
  240. # self.clear_file_breaks()
  241. # EditorWindow.saved_change_hook(self)
  242. def _close(self):
  243. "Extend base method - clear breaks when module is closed"
  244. self.clear_file_breaks()
  245. EditorWindow._close(self)
  246. class PyShellFileList(FileList):
  247. "Extend base class: IDLE supports a shell and breakpoints"
  248. # override FileList's class variable, instances return PyShellEditorWindow
  249. # instead of EditorWindow when new edit windows are created.
  250. EditorWindow = PyShellEditorWindow
  251. pyshell = None
  252. def open_shell(self, event=None):
  253. if self.pyshell:
  254. self.pyshell.top.wakeup()
  255. else:
  256. self.pyshell = PyShell(self)
  257. if self.pyshell:
  258. if not self.pyshell.begin():
  259. return None
  260. return self.pyshell
  261. class ModifiedColorDelegator(ColorDelegator):
  262. "Extend base class: colorizer for the shell window itself"
  263. def __init__(self):
  264. ColorDelegator.__init__(self)
  265. self.LoadTagDefs()
  266. def recolorize_main(self):
  267. self.tag_remove("TODO", "1.0", "iomark")
  268. self.tag_add("SYNC", "1.0", "iomark")
  269. ColorDelegator.recolorize_main(self)
  270. def LoadTagDefs(self):
  271. ColorDelegator.LoadTagDefs(self)
  272. theme = idleConf.GetOption('main','Theme','name')
  273. self.tagdefs.update({
  274. "stdin": {'background':None,'foreground':None},
  275. "stdout": idleConf.GetHighlight(theme, "stdout"),
  276. "stderr": idleConf.GetHighlight(theme, "stderr"),
  277. "console": idleConf.GetHighlight(theme, "console"),
  278. })
  279. class ModifiedUndoDelegator(UndoDelegator):
  280. "Extend base class: forbid insert/delete before the I/O mark"
  281. def insert(self, index, chars, tags=None):
  282. try:
  283. if self.delegate.compare(index, "<", "iomark"):
  284. self.delegate.bell()
  285. return
  286. except TclError:
  287. pass
  288. UndoDelegator.insert(self, index, chars, tags)
  289. def delete(self, index1, index2=None):
  290. try:
  291. if self.delegate.compare(index1, "<", "iomark"):
  292. self.delegate.bell()
  293. return
  294. except TclError:
  295. pass
  296. UndoDelegator.delete(self, index1, index2)
  297. class MyRPCClient(rpc.RPCClient):
  298. def handle_EOF(self):
  299. "Override the base class - just re-raise EOFError"
  300. raise EOFError
  301. class ModifiedInterpreter(InteractiveInterpreter):
  302. def __init__(self, tkconsole):
  303. self.tkconsole = tkconsole
  304. locals = sys.modules['__main__'].__dict__
  305. InteractiveInterpreter.__init__(self, locals=locals)
  306. self.save_warnings_filters = None
  307. self.restarting = False
  308. self.subprocess_arglist = None
  309. self.port = PORT
  310. self.original_compiler_flags = self.compile.compiler.flags
  311. rpcclt = None
  312. rpcpid = None
  313. def spawn_subprocess(self):
  314. if self.subprocess_arglist is None:
  315. self.subprocess_arglist = self.build_subprocess_arglist()
  316. args = self.subprocess_arglist
  317. self.rpcpid = os.spawnv(os.P_NOWAIT, sys.executable, args)
  318. def build_subprocess_arglist(self):
  319. assert (self.port!=0), (
  320. "Socket should have been assigned a port number.")
  321. w = ['-W' + s for s in sys.warnoptions]
  322. if 1/2 > 0: # account for new division
  323. w.append('-Qnew')
  324. # Maybe IDLE is installed and is being accessed via sys.path,
  325. # or maybe it's not installed and the idle.py script is being
  326. # run from the IDLE source directory.
  327. del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
  328. default=False, type='bool')
  329. if __name__ == 'idlelib.PyShell':
  330. command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
  331. else:
  332. command = "__import__('run').main(%r)" % (del_exitf,)
  333. if sys.platform[:3] == 'win' and ' ' in sys.executable:
  334. # handle embedded space in path by quoting the argument
  335. decorated_exec = '"%s"' % sys.executable
  336. else:
  337. decorated_exec = sys.executable
  338. return [decorated_exec] + w + ["-c", command, str(self.port)]
  339. def start_subprocess(self):
  340. addr = (HOST, self.port)
  341. # GUI makes several attempts to acquire socket, listens for connection
  342. for i in range(3):
  343. time.sleep(i)
  344. try:
  345. self.rpcclt = MyRPCClient(addr)
  346. break
  347. except socket.error, err:
  348. pass
  349. else:
  350. self.display_port_binding_error()
  351. return None
  352. # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
  353. self.port = self.rpcclt.listening_sock.getsockname()[1]
  354. # if PORT was not 0, probably working with a remote execution server
  355. if PORT != 0:
  356. # To allow reconnection within the 2MSL wait (cf. Stevens TCP
  357. # V1, 18.6), set SO_REUSEADDR. Note that this can be problematic
  358. # on Windows since the implementation allows two active sockets on
  359. # the same address!
  360. self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
  361. socket.SO_REUSEADDR, 1)
  362. self.spawn_subprocess()
  363. #time.sleep(20) # test to simulate GUI not accepting connection
  364. # Accept the connection from the Python execution server
  365. self.rpcclt.listening_sock.settimeout(10)
  366. try:
  367. self.rpcclt.accept()
  368. except socket.timeout, err:
  369. self.display_no_subprocess_error()
  370. return None
  371. self.rpcclt.register("stdin", self.tkconsole)
  372. self.rpcclt.register("stdout", self.tkconsole.stdout)
  373. self.rpcclt.register("stderr", self.tkconsole.stderr)
  374. self.rpcclt.register("flist", self.tkconsole.flist)
  375. self.rpcclt.register("linecache", linecache)
  376. self.rpcclt.register("interp", self)
  377. self.transfer_path(with_cwd=True)
  378. self.poll_subprocess()
  379. return self.rpcclt
  380. def restart_subprocess(self, with_cwd=False):
  381. if self.restarting:
  382. return self.rpcclt
  383. self.restarting = True
  384. # close only the subprocess debugger
  385. debug = self.getdebugger()
  386. if debug:
  387. try:
  388. # Only close subprocess debugger, don't unregister gui_adap!
  389. RemoteDebugger.close_subprocess_debugger(self.rpcclt)
  390. except:
  391. pass
  392. # Kill subprocess, spawn a new one, accept connection.
  393. self.rpcclt.close()
  394. self.unix_terminate()
  395. console = self.tkconsole
  396. was_executing = console.executing
  397. console.executing = False
  398. self.spawn_subprocess()
  399. try:
  400. self.rpcclt.accept()
  401. except socket.timeout, err:
  402. self.display_no_subprocess_error()
  403. return None
  404. self.transfer_path(with_cwd=with_cwd)
  405. # annotate restart in shell window and mark it
  406. console.text.delete("iomark", "end-1c")
  407. if was_executing:
  408. console.write('\n')
  409. console.showprompt()
  410. halfbar = ((int(console.width) - 16) // 2) * '='
  411. console.write(halfbar + ' RESTART ' + halfbar)
  412. console.text.mark_set("restart", "end-1c")
  413. console.text.mark_gravity("restart", "left")
  414. console.showprompt()
  415. # restart subprocess debugger
  416. if debug:
  417. # Restarted debugger connects to current instance of debug GUI
  418. gui = RemoteDebugger.restart_subprocess_debugger(self.rpcclt)
  419. # reload remote debugger breakpoints for all PyShellEditWindows
  420. debug.load_breakpoints()
  421. self.compile.compiler.flags = self.original_compiler_flags
  422. self.restarting = False
  423. return self.rpcclt
  424. def __request_interrupt(self):
  425. self.rpcclt.remotecall("exec", "interrupt_the_server", (), {})
  426. def interrupt_subprocess(self):
  427. threading.Thread(target=self.__request_interrupt).start()
  428. def kill_subprocess(self):
  429. try:
  430. self.rpcclt.close()
  431. except AttributeError: # no socket
  432. pass
  433. self.unix_terminate()
  434. self.tkconsole.executing = False
  435. self.rpcclt = None
  436. def unix_terminate(self):
  437. "UNIX: make sure subprocess is terminated and collect status"
  438. if hasattr(os, 'kill'):
  439. try:
  440. os.kill(self.rpcpid, SIGTERM)
  441. except OSError:
  442. # process already terminated:
  443. return
  444. else:
  445. try:
  446. os.waitpid(self.rpcpid, 0)
  447. except OSError:
  448. return
  449. def transfer_path(self, with_cwd=False):
  450. if with_cwd: # Issue 13506
  451. path = [''] # include Current Working Directory
  452. path.extend(sys.path)
  453. else:
  454. path = sys.path
  455. self.runcommand("""if 1:
  456. import sys as _sys
  457. _sys.path = %r
  458. del _sys
  459. \n""" % (path,))
  460. active_seq = None
  461. def poll_subprocess(self):
  462. clt = self.rpcclt
  463. if clt is None:
  464. return
  465. try:
  466. response = clt.pollresponse(self.active_seq, wait=0.05)
  467. except (EOFError, IOError, KeyboardInterrupt):
  468. # lost connection or subprocess terminated itself, restart
  469. # [the KBI is from rpc.SocketIO.handle_EOF()]
  470. if self.tkconsole.closing:
  471. return
  472. response = None
  473. self.restart_subprocess()
  474. if response:
  475. self.tkconsole.resetoutput()
  476. self.active_seq = None
  477. how, what = response
  478. console = self.tkconsole.console
  479. if how == "OK":
  480. if what is not None:
  481. print >>console, repr(what)
  482. elif how == "EXCEPTION":
  483. if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
  484. self.remote_stack_viewer()
  485. elif how == "ERROR":
  486. errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
  487. print >>sys.__stderr__, errmsg, what
  488. print >>console, errmsg, what
  489. # we received a response to the currently active seq number:
  490. try:
  491. self.tkconsole.endexecuting()
  492. except AttributeError: # shell may have closed
  493. pass
  494. # Reschedule myself
  495. if not self.tkconsole.closing:
  496. self.tkconsole.text.after(self.tkconsole.pollinterval,
  497. self.poll_subprocess)
  498. debugger = None
  499. def setdebugger(self, debugger):
  500. self.debugger = debugger
  501. def getdebugger(self):
  502. return self.debugger
  503. def open_remote_stack_viewer(self):
  504. """Initiate the remote stack viewer from a separate thread.
  505. This method is called from the subprocess, and by returning from this
  506. method we allow the subprocess to unblock. After a bit the shell
  507. requests the subprocess to open the remote stack viewer which returns a
  508. static object looking at the last exception. It is queried through
  509. the RPC mechanism.
  510. """
  511. self.tkconsole.text.after(300, self.remote_stack_viewer)
  512. return
  513. def remote_stack_viewer(self):
  514. from idlelib import RemoteObjectBrowser
  515. oid = self.rpcclt.remotequeue("exec", "stackviewer", ("flist",), {})
  516. if oid is None:
  517. self.tkconsole.root.bell()
  518. return
  519. item = RemoteObjectBrowser.StubObjectTreeItem(self.rpcclt, oid)
  520. from idlelib.TreeWidget import ScrolledCanvas, TreeNode
  521. top = Toplevel(self.tkconsole.root)
  522. theme = idleConf.GetOption('main','Theme','name')
  523. background = idleConf.GetHighlight(theme, 'normal')['background']
  524. sc = ScrolledCanvas(top, bg=background, highlightthickness=0)
  525. sc.frame.pack(expand=1, fill="both")
  526. node = TreeNode(sc.canvas, None, item)
  527. node.expand()
  528. # XXX Should GC the remote tree when closing the window
  529. gid = 0
  530. def execsource(self, source):
  531. "Like runsource() but assumes complete exec source"
  532. filename = self.stuffsource(source)
  533. self.execfile(filename, source)
  534. def execfile(self, filename, source=None):
  535. "Execute an existing file"
  536. if source is None:
  537. source = open(filename, "r").read()
  538. try:
  539. code = compile(source, filename, "exec")
  540. except (OverflowError, SyntaxError):
  541. self.tkconsole.resetoutput()
  542. tkerr = self.tkconsole.stderr
  543. print>>tkerr, '*** Error in script or command!\n'
  544. print>>tkerr, 'Traceback (most recent call last):'
  545. InteractiveInterpreter.showsyntaxerror(self, filename)
  546. self.tkconsole.showprompt()
  547. else:
  548. self.runcode(code)
  549. def runsource(self, source):
  550. "Extend base class method: Stuff the source in the line cache first"
  551. filename = self.stuffsource(source)
  552. self.more = 0
  553. self.save_warnings_filters = warnings.filters[:]
  554. warnings.filterwarnings(action="error", category=SyntaxWarning)
  555. if isinstance(source, types.UnicodeType):
  556. from idlelib import IOBinding
  557. try:
  558. source = source.encode(IOBinding.encoding)
  559. except UnicodeError:
  560. self.tkconsole.resetoutput()
  561. self.write("Unsupported characters in input\n")
  562. return
  563. try:
  564. # InteractiveInterpreter.runsource() calls its runcode() method,
  565. # which is overridden (see below)
  566. return InteractiveInterpreter.runsource(self, source, filename)
  567. finally:
  568. if self.save_warnings_filters is not None:
  569. warnings.filters[:] = self.save_warnings_filters
  570. self.save_warnings_filters = None
  571. def stuffsource(self, source):
  572. "Stuff source in the filename cache"
  573. filename = "<pyshell#%d>" % self.gid
  574. self.gid = self.gid + 1
  575. lines = source.split("\n")
  576. linecache.cache[filename] = len(source)+1, 0, lines, filename
  577. return filename
  578. def prepend_syspath(self, filename):
  579. "Prepend sys.path with file's directory if not already included"
  580. self.runcommand("""if 1:
  581. _filename = %r
  582. import sys as _sys
  583. from os.path import dirname as _dirname
  584. _dir = _dirname(_filename)
  585. if not _dir in _sys.path:
  586. _sys.path.insert(0, _dir)
  587. del _filename, _sys, _dirname, _dir
  588. \n""" % (filename,))
  589. def showsyntaxerror(self, filename=None):
  590. """Extend base class method: Add Colorizing
  591. Color the offending position instead of printing it and pointing at it
  592. with a caret.
  593. """
  594. text = self.tkconsole.text
  595. stuff = self.unpackerror()
  596. if stuff:
  597. msg, lineno, offset, line = stuff
  598. if lineno == 1:
  599. pos = "iomark + %d chars" % (offset-1)
  600. else:
  601. pos = "iomark linestart + %d lines + %d chars" % \
  602. (lineno-1, offset-1)
  603. text.tag_add("ERROR", pos)
  604. text.see(pos)
  605. char = text.get(pos)
  606. if char and char in IDENTCHARS:
  607. text.tag_add("ERROR", pos + " wordstart", pos)
  608. self.tkconsole.resetoutput()
  609. self.write("SyntaxError: %s\n" % str(msg))
  610. else:
  611. self.tkconsole.resetoutput()
  612. InteractiveInterpreter.showsyntaxerror(self, filename)
  613. self.tkconsole.showprompt()
  614. def unpackerror(self):
  615. type, value, tb = sys.exc_info()
  616. ok = type is SyntaxError
  617. if ok:
  618. try:
  619. msg, (dummy_filename, lineno, offset, line) = value
  620. if not offset:
  621. offset = 0
  622. except:
  623. ok = 0
  624. if ok:
  625. return msg, lineno, offset, line
  626. else:
  627. return None
  628. def showtraceback(self):
  629. "Extend base class method to reset output properly"
  630. self.tkconsole.resetoutput()
  631. self.checklinecache()
  632. InteractiveInterpreter.showtraceback(self)
  633. if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
  634. self.tkconsole.open_stack_viewer()
  635. def checklinecache(self):
  636. c = linecache.cache
  637. for key in c.keys():
  638. if key[:1] + key[-1:] != "<>":
  639. del c[key]
  640. def runcommand(self, code):
  641. "Run the code without invoking the debugger"
  642. # The code better not raise an exception!
  643. if self.tkconsole.executing:
  644. self.display_executing_dialog()
  645. return 0
  646. if self.rpcclt:
  647. self.rpcclt.remotequeue("exec", "runcode", (code,), {})
  648. else:
  649. exec code in self.locals
  650. return 1
  651. def runcode(self, code):
  652. "Override base class method"
  653. if self.tkconsole.executing:
  654. self.interp.restart_subprocess()
  655. self.checklinecache()
  656. if self.save_warnings_filters is not None:
  657. warnings.filters[:] = self.save_warnings_filters
  658. self.save_warnings_filters = None
  659. debugger = self.debugger
  660. try:
  661. self.tkconsole.beginexecuting()
  662. if not debugger and self.rpcclt is not None:
  663. self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
  664. (code,), {})
  665. elif debugger:
  666. debugger.run(code, self.locals)
  667. else:
  668. exec code in self.locals
  669. except SystemExit:
  670. if not self.tkconsole.closing:
  671. if tkMessageBox.askyesno(
  672. "Exit?",
  673. "Do you want to exit altogether?",
  674. default="yes",
  675. master=self.tkconsole.text):
  676. raise
  677. else:
  678. self.showtraceback()
  679. else:
  680. raise
  681. except:
  682. if use_subprocess:
  683. print >>self.tkconsole.stderr, \
  684. "IDLE internal error in runcode()"
  685. self.showtraceback()
  686. self.tkconsole.endexecuting()
  687. else:
  688. if self.tkconsole.canceled:
  689. self.tkconsole.canceled = False
  690. print >>self.tkconsole.stderr, "KeyboardInterrupt"
  691. else:
  692. self.showtraceback()
  693. finally:
  694. if not use_subprocess:
  695. try:
  696. self.tkconsole.endexecuting()
  697. except AttributeError: # shell may have closed
  698. pass
  699. def write(self, s):
  700. "Override base class method"
  701. self.tkconsole.stderr.write(s)
  702. def display_port_binding_error(self):
  703. tkMessageBox.showerror(
  704. "Port Binding Error",
  705. "IDLE can't bind to a TCP/IP port, which is necessary to "
  706. "communicate with its Python execution server. This might be "
  707. "because no networking is installed on this computer. "
  708. "Run IDLE with the -n command line switch to start without a "
  709. "subprocess and refer to Help/IDLE Help 'Running without a "
  710. "subprocess' for further details.",
  711. master=self.tkconsole.text)
  712. def display_no_subprocess_error(self):
  713. tkMessageBox.showerror(
  714. "Subprocess Startup Error",
  715. "IDLE's subprocess didn't make connection. Either IDLE can't "
  716. "start a subprocess or personal firewall software is blocking "
  717. "the connection.",
  718. master=self.tkconsole.text)
  719. def display_executing_dialog(self):
  720. tkMessageBox.showerror(
  721. "Already executing",
  722. "The Python Shell window is already executing a command; "
  723. "please wait until it is finished.",
  724. master=self.tkconsole.text)
  725. class PyShell(OutputWindow):
  726. shell_title = "Python Shell"
  727. # Override classes
  728. ColorDelegator = ModifiedColorDelegator
  729. UndoDelegator = ModifiedUndoDelegator
  730. # Override menus
  731. menu_specs = [
  732. ("file", "_File"),
  733. ("edit", "_Edit"),
  734. ("debug", "_Debug"),
  735. ("options", "_Options"),
  736. ("windows", "_Windows"),
  737. ("help", "_Help"),
  738. ]
  739. if macosxSupport.runningAsOSXApp():
  740. del menu_specs[-3]
  741. menu_specs[-2] = ("windows", "_Window")
  742. # New classes
  743. from idlelib.IdleHistory import History
  744. def __init__(self, flist=None):
  745. if use_subprocess:
  746. ms = self.menu_specs
  747. if ms[2][0] != "shell":
  748. ms.insert(2, ("shell", "She_ll"))
  749. self.interp = ModifiedInterpreter(self)
  750. if flist is None:
  751. root = Tk()
  752. fixwordbreaks(root)
  753. root.withdraw()
  754. flist = PyShellFileList(root)
  755. #
  756. OutputWindow.__init__(self, flist, None, None)
  757. #
  758. ## self.config(usetabs=1, indentwidth=8, context_use_ps1=1)
  759. self.usetabs = True
  760. # indentwidth must be 8 when using tabs. See note in EditorWindow:
  761. self.indentwidth = 8
  762. self.context_use_ps1 = True
  763. #
  764. text = self.text
  765. text.configure(wrap="char")
  766. text.bind("<<newline-and-indent>>", self.enter_callback)
  767. text.bind("<<plain-newline-and-indent>>", self.linefeed_callback)
  768. text.bind("<<interrupt-execution>>", self.cancel_callback)
  769. text.bind("<<end-of-file>>", self.eof_callback)
  770. text.bind("<<open-stack-viewer>>", self.open_stack_viewer)
  771. text.bind("<<toggle-debugger>>", self.toggle_debugger)
  772. text.bind("<<toggle-jit-stack-viewer>>", self.toggle_jit_stack_viewer)
  773. if use_subprocess:
  774. text.bind("<<view-restart>>", self.view_restart_mark)
  775. text.bind("<<restart-shell>>", self.restart_shell)
  776. #
  777. self.save_stdout = sys.stdout
  778. self.save_stderr = sys.stderr
  779. self.save_stdin = sys.stdin
  780. from idlelib import IOBinding
  781. self.stdout = PseudoFile(self, "stdout", IOBinding.encoding)
  782. self.stderr = PseudoFile(self, "stderr", IOBinding.encoding)
  783. self.console = PseudoFile(self, "console", IOBinding.encoding)
  784. if not use_subprocess:
  785. sys.stdout = self.stdout
  786. sys.stderr = self.stderr
  787. sys.stdin = self
  788. #
  789. self.history = self.History(self.text)
  790. #
  791. self.pollinterval = 50 # millisec
  792. def get_standard_extension_names(self):
  793. return idleConf.GetExtensions(shell_only=True)
  794. reading = False
  795. executing = False
  796. canceled = False
  797. endoffile = False
  798. closing = False
  799. def set_warning_stream(self, stream):
  800. global warning_stream
  801. warning_stream = stream
  802. def get_warning_stream(self):
  803. return warning_stream
  804. def toggle_debugger(self, event=None):
  805. if self.executing:
  806. tkMessageBox.showerror("Don't debug now",
  807. "You can only toggle the debugger when idle",
  808. master=self.text)
  809. self.set_debugger_indicator()
  810. return "break"
  811. else:
  812. db = self.interp.getdebugger()
  813. if db:
  814. self.close_debugger()
  815. else:
  816. self.open_debugger()
  817. def set_debugger_indicator(self):
  818. db = self.interp.getdebugger()
  819. self.setvar("<<toggle-debugger>>", not not db)
  820. def toggle_jit_stack_viewer(self, event=None):
  821. pass # All we need is the variable
  822. def close_debugger(self):
  823. db = self.interp.getdebugger()
  824. if db:
  825. self.interp.setdebugger(None)
  826. db.close()
  827. if self.interp.rpcclt:
  828. RemoteDebugger.close_remote_debugger(self.interp.rpcclt)
  829. self.resetoutput()
  830. self.console.write("[DEBUG OFF]\n")
  831. sys.ps1 = ">>> "
  832. self.showprompt()
  833. self.set_debugger_indicator()
  834. def open_debugger(self):
  835. if self.interp.rpcclt:
  836. dbg_gui = RemoteDebugger.start_remote_debugger(self.interp.rpcclt,
  837. self)
  838. else:
  839. dbg_gui = Debugger.Debugger(self)
  840. self.interp.setdebugger(dbg_gui)
  841. dbg_gui.load_breakpoints()
  842. sys.ps1 = "[DEBUG ON]\n>>> "
  843. self.showprompt()
  844. self.set_debugger_indicator()
  845. def beginexecuting(self):
  846. "Helper for ModifiedInterpreter"
  847. self.resetoutput()
  848. self.executing = 1
  849. def endexecuting(self):
  850. "Helper for ModifiedInterpreter"
  851. self.executing = 0
  852. self.canceled = 0
  853. self.showprompt()
  854. def close(self):
  855. "Extend EditorWindow.close()"
  856. if self.executing:
  857. response = tkMessageBox.askokcancel(
  858. "Kill?",
  859. "The program is still running!\n Do you want to kill it?",
  860. default="ok",
  861. parent=self.text)
  862. if response is False:
  863. return "cancel"
  864. if self.reading:
  865. self.top.quit()
  866. self.canceled = True
  867. self.closing = True
  868. # Wait for poll_subprocess() rescheduling to stop
  869. self.text.after(2 * self.pollinterval, self.close2)
  870. def close2(self):
  871. return EditorWindow.close(self)
  872. def _close(self):
  873. "Extend EditorWindow._close(), shut down debugger and execution server"
  874. self.close_debugger()
  875. if use_subprocess:
  876. self.interp.kill_subprocess()
  877. # Restore std streams
  878. sys.stdout = self.save_stdout
  879. sys.stderr = self.save_stderr
  880. sys.stdin = self.save_stdin
  881. # Break cycles
  882. self.interp = None
  883. self.console = None
  884. self.flist.pyshell = None
  885. self.history = None
  886. EditorWindow._close(self)
  887. def ispythonsource(self, filename):
  888. "Override EditorWindow method: never remove the colorizer"
  889. return True
  890. def short_title(self):
  891. return self.shell_title
  892. COPYRIGHT = \
  893. 'Type "copyright", "credits" or "license()" for more information.'
  894. def begin(self):
  895. self.resetoutput()
  896. if use_subprocess:
  897. nosub = ''
  898. client = self.interp.start_subprocess()
  899. if not client:
  900. self.close()
  901. return False
  902. else:
  903. nosub = "==== No Subprocess ===="
  904. self.write("Python %s on %s\n%s\n%s" %
  905. (sys.version, sys.platform, self.COPYRIGHT, nosub))
  906. self.showprompt()
  907. import Tkinter
  908. Tkinter._default_root = None # 03Jan04 KBK What's this?
  909. return True
  910. def readline(self):
  911. save = self.reading
  912. try:
  913. self.reading = 1
  914. self.top.mainloop() # nested mainloop()
  915. finally:
  916. self.reading = save
  917. line = self.text.get("iomark", "end-1c")
  918. if len(line) == 0: # may be EOF if we quit our mainloop with Ctrl-C
  919. line = "\n"
  920. if isinstance(line, unicode):
  921. from idlelib import IOBinding
  922. try:
  923. line = line.encode(IOBinding.encoding)
  924. except UnicodeError:
  925. pass
  926. self.resetoutput()
  927. if self.canceled:
  928. self.canceled = 0
  929. if not use_subprocess:
  930. raise KeyboardInterrupt
  931. if self.endoffile:
  932. self.endoffile = 0
  933. line = ""
  934. return line
  935. def isatty(self):
  936. return True
  937. def cancel_callback(self, event=None):
  938. try:
  939. if self.text.compare("sel.first", "!=", "sel.last"):
  940. return # Active selection -- always use default binding
  941. except:
  942. pass
  943. if not (self.executing or self.reading):
  944. self.resetoutput()
  945. self.interp.write("KeyboardInterrupt\n")
  946. self.showprompt()
  947. return "break"
  948. self.endoffile = 0
  949. self.canceled = 1
  950. if (self.executing and self.interp.rpcclt):
  951. if self.interp.getdebugger():
  952. self.interp.restart_subprocess()
  953. else:
  954. self.interp.interrupt_subprocess()
  955. if self.reading:
  956. self.top.quit() # exit the nested mainloop() in readline()
  957. return "break"
  958. def eof_callback(self, event):
  959. if self.executing and not self.reading:
  960. return # Let the default binding (delete next char) take over
  961. if not (self.text.compare("iomark", "==", "insert") and
  962. self.text.compare("insert", "==", "end-1c")):
  963. return # Let the default binding (delete next char) take over
  964. if not self.executing:
  965. self.resetoutput()
  966. self.close()
  967. else:
  968. self.canceled = 0
  969. self.endoffile = 1
  970. self.top.quit()
  971. return "break"
  972. def linefeed_callback(self, event):
  973. # Insert a linefeed without entering anything (still autoindented)
  974. if self.reading:
  975. self.text.insert("insert", "\n")
  976. self.text.see("insert")
  977. else:
  978. self.newline_and_indent_event(event)
  979. return "break"
  980. def enter_callback(self, event):
  981. if self.executing and not self.reading:
  982. return # Let the default binding (insert '\n') take over
  983. # If some text is selected, recall the selection
  984. # (but only if this before the I/O mark)
  985. try:
  986. sel = self.text.get("sel.first", "sel.last")
  987. if sel:
  988. if self.text.compare("sel.last", "<=", "iomark"):
  989. self.recall(sel, event)
  990. return "break"
  991. except:
  992. pass
  993. # If we're strictly before the line containing iomark, recall
  994. # the current line, less a leading prompt, less leading or
  995. # trailing whitespace
  996. if self.text.compare("insert", "<", "iomark linestart"):
  997. # Check if there's a relevant stdin range -- if so, use it
  998. prev = self.text.tag_prevrange("stdin", "insert")
  999. if prev and self.text.compare("insert", "<", prev[1]):
  1000. self.recall(self.text.get(prev[0], prev[1]), event)
  1001. return "break"
  1002. next = self.text.tag_nextrange("stdin", "insert")
  1003. if next and self.text.compare("insert lineend", ">=", next[0]):
  1004. self.recall(self.text.get(next[0], next[1]), event)
  1005. return "break"
  1006. # No stdin mark -- just get the current line, less any prompt
  1007. indices = self.text.tag_nextrange("console", "insert linestart")
  1008. if indices and \
  1009. self.text.compare(indices[0], "<=", "insert linestart"):
  1010. self.recall(self.text.get(indices[1], "insert lineend"), event)
  1011. else:
  1012. self.recall(self.text.get("insert linestart", "insert lineend"), event)
  1013. return "break"
  1014. # If we're between the beginning of the line and the iomark, i.e.
  1015. # in the prompt area, move to the end of the prompt
  1016. if self.text.compare("insert", "<", "iomark"):
  1017. self.text.mark_set("insert", "iomark")
  1018. # If we're in the current input and there's only whitespace
  1019. # beyond the cursor, erase that whitespace first
  1020. s = self.text.get("insert", "end-1c")
  1021. if s and not s.strip():
  1022. self.text.delete("insert", "end-1c")
  1023. # If we're in the current input before its last line,
  1024. # insert a newline right at the insert point
  1025. if self.text.compare("insert", "<", "end-1c linestart"):
  1026. self.newline_and_indent_event(event)
  1027. return "break"
  1028. # We're in the last line; append a newline and submit it
  1029. self.text.mark_set("insert", "end-1c")
  1030. if self.reading:
  1031. self.text.insert("insert", "\n")
  1032. self.text.see("insert")
  1033. else:
  1034. self.newline_and_indent_event(event)
  1035. self.text.tag_add("stdin", "iomark", "end-1c")
  1036. self.text.update_idletasks()
  1037. if self.reading:
  1038. self.top.quit() # Break out of recursive mainloop() in raw_input()
  1039. else:
  1040. self.runit()
  1041. return "break"
  1042. def recall(self, s, event):
  1043. # remove leading and trailing empty or whitespace lines
  1044. s = re.sub(r'^\s*\n', '' , s)
  1045. s = re.sub(r'\n\s*$', '', s)
  1046. lines = s.split('\n')
  1047. self.text.undo_block_start()
  1048. try:
  1049. self.text.tag_remove("sel", "1.0", "end")
  1050. self.text.mark_set("insert", "end-1c")
  1051. prefix = self.text.get("insert linestart", "insert")
  1052. if prefix.rstrip().endswith(':'):
  1053. self.newline_and_indent_event(event)
  1054. prefix = self.text.get("insert linestart", "insert")
  1055. self.text.insert("insert", lines[0].strip())
  1056. if len(lines) > 1:
  1057. orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
  1058. new_base_indent = re.search(r'^([ \t]*)', prefix).group(0)
  1059. for line in lines[1:]:
  1060. if line.startswith(orig_base_indent):
  1061. # replace orig base indentation with new indentation
  1062. line = new_base_indent + line[len(orig_base_indent):]
  1063. self.text.insert('insert', '\n'+line.rstrip())
  1064. finally:
  1065. self.text.see("insert")
  1066. self.text.undo_block_stop()
  1067. def runit(self):
  1068. line = self.text.get("iomark", "end-1c")
  1069. # Strip off last newline and surrounding whitespace.
  1070. # (To allow you to hit return twice to end a statement.)
  1071. i = len(line)
  1072. while i > 0 and line[i-1] in " \t":
  1073. i = i-1
  1074. if i > 0 and line[i-1] == "\n":
  1075. i = i-1
  1076. while i > 0 and line[i-1] in " \t":
  1077. i = i-1
  1078. line = line[:i]
  1079. more = self.interp.runsource(line)
  1080. def open_stack_viewer(self, event=None):
  1081. if self.interp.rpcclt:
  1082. return self.interp.remote_stack_viewer()
  1083. try:
  1084. sys.last_traceback
  1085. except:
  1086. tkMessageBox.showerror("No stack trace",
  1087. "There is no stack trace yet.\n"
  1088. "(sys.last_traceback is not defined)",
  1089. master=self.text)
  1090. return
  1091. from idlelib.StackViewer import StackBrowser
  1092. sv = StackBrowser(self.root, self.flist)
  1093. def view_restart_mark(self, event=None):
  1094. self.text.see("iomark")
  1095. self.text.see("restart")
  1096. def restart_shell(self, event=None):
  1097. "Callback for Run/Restart Shell Cntl-F6"
  1098. self.interp.restart_subprocess(with_cwd=True)
  1099. def showprompt(self):
  1100. self.resetoutput()
  1101. try:
  1102. s = str(sys.ps1)
  1103. except:
  1104. s = ""
  1105. self.console.write(s)
  1106. self.text.mark_set("insert", "end-1c")
  1107. self.set_line_and_column()
  1108. self.io.reset_undo()
  1109. def resetoutput(self):
  1110. source = self.text.get("iomark", "end-1c")
  1111. if self.history:
  1112. self.history.history_store(source)
  1113. if self.text.get("end-2c") != "\n":
  1114. self.text.insert("end-1c", "\n")
  1115. self.text.mark_set("iomark", "end-1c")
  1116. self.set_line_and_column()
  1117. sys.stdout.softspace = 0
  1118. def write(self, s, tags=()):
  1119. try:
  1120. self.text.mark_gravity("iomark", "right")
  1121. OutputWindow.write(self, s, tags, "iomark")
  1122. self.text.mark_gravity("iomark", "left")
  1123. except:
  1124. pass
  1125. if self.canceled:
  1126. self.canceled = 0
  1127. if not use_subprocess:
  1128. raise KeyboardInterrupt
  1129. class PseudoFile(object):
  1130. def __init__(self, shell, tags, encoding=None):
  1131. self.shell = shell
  1132. self.tags = tags
  1133. self.softspace = 0
  1134. self.encoding = encoding
  1135. def write(self, s):
  1136. self.shell.write(s, self.tags)
  1137. def writelines(self, lines):
  1138. for line in lines:
  1139. self.write(line)
  1140. def flush(self):
  1141. pass
  1142. def isatty(self):
  1143. return True
  1144. usage_msg = """\
  1145. USAGE: idle [-deins] [-t title] [file]*
  1146. idle [-dns] [-t title] (-c cmd | -r file) [arg]*
  1147. idle [-dns] [-t title] - [arg]*
  1148. -h print this help message and exit
  1149. -n run IDLE without a subprocess (see Help/IDLE Help for details)
  1150. The following options will override the IDLE 'settings' configuration:
  1151. -e open an edit window
  1152. -i open a shell window
  1153. The following options imply -i and will open a shell:
  1154. -c cmd run the command in a shell, or
  1155. -r file run script from file
  1156. -d enable the debugger
  1157. -s run $IDLESTARTUP or $PYTHONSTARTUP before anything else
  1158. -t title set title of shell window
  1159. A default edit window will be bypassed when -c, -r, or - are used.
  1160. [arg]* are passed to the command (-c) or script (-r) in sys.argv[1:].
  1161. Examples:
  1162. idle
  1163. Open an edit window or shell depending on IDLE's configuration.
  1164. idle foo.py foobar.py
  1165. Edit the files, also open a shell if configured to start with shell.
  1166. idle -est "Baz" foo.py
  1167. Run $IDLESTARTUP or $PYTHONSTARTUP, edit foo.py, and open a shell
  1168. window with the title "Baz".
  1169. idle -c "import sys; print sys.argv" "foo"
  1170. Open a shell window and run the command, passing "-c" in sys.argv[0]
  1171. and "foo" in sys.argv[1].
  1172. idle -d -s -r foo.py "Hello World"
  1173. Open a shell window, run a startup script, enable the debugger, and
  1174. run foo.py, passing "foo.py" in sys.argv[0] and "Hello World" in
  1175. sys.argv[1].
  1176. echo "import sys; print sys.argv" | idle - "foobar"
  1177. Open a shell window, run the script piped in, passing '' in sys.argv[0]
  1178. and "foobar" in sys.argv[1].
  1179. """
  1180. def main():
  1181. global flist, root, use_subprocess
  1182. use_subprocess = True
  1183. enable_shell = True
  1184. enable_edit = False
  1185. debug = False
  1186. cmd = None
  1187. script = None
  1188. startup = False
  1189. try:
  1190. opts, args = getopt.getopt(sys.argv[1:], "c:deihnr:st:")
  1191. except getopt.error, msg:
  1192. sys.stderr.write("Error: %s\n" % str(msg))
  1193. sys.stderr.write(usage_msg)
  1194. sys.exit(2)
  1195. for o, a in opts:
  1196. if o == '-c':
  1197. cmd = a
  1198. enable_shell = True
  1199. if o == '-d':
  1200. debug = True
  1201. enable_shell = True
  1202. if o == '-e':
  1203. enable_edit = True
  1204. enable_shell = False
  1205. if o == '-h':
  1206. sys.stdout.write(usage_msg)
  1207. sys.exit()
  1208. if o == '-i':
  1209. enable_shell = True
  1210. if o == '-n':
  1211. use_subprocess = False
  1212. if o == '-r':
  1213. script = a
  1214. if os.path.isfile(script):
  1215. pass
  1216. else:
  1217. print "No script file: ", script
  1218. sys.exit()
  1219. enable_shell = True
  1220. if o == '-s':
  1221. startup = True
  1222. enable_shell = True
  1223. if o == '-t':
  1224. PyShell.shell_title = a
  1225. enable_shell = True
  1226. if args and args[0] == '-':
  1227. cmd = sys.stdin.read()
  1228. enable_shell = True
  1229. # process sys.argv and sys.path:
  1230. for i in range(len(sys.path)):
  1231. sys.path[i] = os.path.abspath(sys.path[i])
  1232. if args and args[0] == '-':
  1233. sys.argv = [''] + args[1:]
  1234. elif cmd:
  1235. sys.argv = ['-c'] + args
  1236. elif script:
  1237. sys.argv = [script] + ar

Large files files are truncated, but you can click here to view the full file