##// END OF EJS Templates
use system_raw in terminal, even on Windows...
MinRK -
Show More
@@ -1,641 +1,639 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Subclass of InteractiveShell for terminal based frontends."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2010 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import __builtin__
18 18 import bdb
19 19 import os
20 20 import re
21 21 import sys
22 22
23 23 try:
24 24 from contextlib import nested
25 25 except:
26 26 from IPython.utils.nested_context import nested
27 27
28 28 from IPython.core.error import TryNext
29 29 from IPython.core.usage import interactive_usage, default_banner
30 30 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
31 31 from IPython.lib.inputhook import enable_gui
32 32 from IPython.lib.pylabtools import pylab_activate
33 33 from IPython.testing.skipdoctest import skip_doctest
34 34 from IPython.utils import py3compat
35 35 from IPython.utils.terminal import toggle_set_term_title, set_term_title
36 36 from IPython.utils.process import abbrev_cwd
37 37 from IPython.utils.warn import warn
38 38 from IPython.utils.text import num_ini_spaces
39 39 from IPython.utils.traitlets import Int, CBool, Unicode
40 40
41 41 #-----------------------------------------------------------------------------
42 42 # Utilities
43 43 #-----------------------------------------------------------------------------
44 44
45 45 def get_default_editor():
46 46 try:
47 47 ed = os.environ['EDITOR']
48 48 except KeyError:
49 49 if os.name == 'posix':
50 50 ed = 'vi' # the only one guaranteed to be there!
51 51 else:
52 52 ed = 'notepad' # same in Windows!
53 53 return ed
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Main class
57 57 #-----------------------------------------------------------------------------
58 58
59 59 class TerminalInteractiveShell(InteractiveShell):
60 60
61 61 autoedit_syntax = CBool(False, config=True,
62 62 help="auto editing of files with syntax errors.")
63 63 banner = Unicode('')
64 64 banner1 = Unicode(default_banner, config=True,
65 65 help="""The part of the banner to be printed before the profile"""
66 66 )
67 67 banner2 = Unicode('', config=True,
68 68 help="""The part of the banner to be printed after the profile"""
69 69 )
70 70 confirm_exit = CBool(True, config=True,
71 71 help="""
72 72 Set to confirm when you try to exit IPython with an EOF (Control-D
73 73 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
74 74 you can force a direct exit without any confirmation.""",
75 75 )
76 76 # This display_banner only controls whether or not self.show_banner()
77 77 # is called when mainloop/interact are called. The default is False
78 78 # because for the terminal based application, the banner behavior
79 79 # is controlled by Global.display_banner, which IPythonApp looks at
80 80 # to determine if *it* should call show_banner() by hand or not.
81 81 display_banner = CBool(False) # This isn't configurable!
82 82 embedded = CBool(False)
83 83 embedded_active = CBool(False)
84 84 editor = Unicode(get_default_editor(), config=True,
85 85 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
86 86 )
87 87 pager = Unicode('less', config=True,
88 88 help="The shell program to be used for paging.")
89 89
90 90 screen_length = Int(0, config=True,
91 91 help=
92 92 """Number of lines of your screen, used to control printing of very
93 93 long strings. Strings longer than this number of lines will be sent
94 94 through a pager instead of directly printed. The default value for
95 95 this is 0, which means IPython will auto-detect your screen size every
96 96 time it needs to print certain potentially long strings (this doesn't
97 97 change the behavior of the 'print' keyword, it's only triggered
98 98 internally). If for some reason this isn't working well (it needs
99 99 curses support), specify it yourself. Otherwise don't change the
100 100 default.""",
101 101 )
102 102 term_title = CBool(False, config=True,
103 103 help="Enable auto setting the terminal title."
104 104 )
105 105
106 106 def __init__(self, config=None, ipython_dir=None, profile_dir=None, user_ns=None,
107 107 user_global_ns=None, custom_exceptions=((),None),
108 108 usage=None, banner1=None, banner2=None,
109 109 display_banner=None):
110 110
111 111 super(TerminalInteractiveShell, self).__init__(
112 112 config=config, profile_dir=profile_dir, user_ns=user_ns,
113 113 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
114 114 )
115 # use os.system instead of utils.process.system by default, except on Windows
116 if os.name == 'nt':
117 self.system = self.system_piped
118 else:
119 self.system = self.system_raw
115 # use os.system instead of utils.process.system by default,
116 # because piped system doesn't make sense in the Terminal:
117 self.system = self.system_raw
120 118
121 119 self.init_term_title()
122 120 self.init_usage(usage)
123 121 self.init_banner(banner1, banner2, display_banner)
124 122
125 123 #-------------------------------------------------------------------------
126 124 # Things related to the terminal
127 125 #-------------------------------------------------------------------------
128 126
129 127 @property
130 128 def usable_screen_length(self):
131 129 if self.screen_length == 0:
132 130 return 0
133 131 else:
134 132 num_lines_bot = self.separate_in.count('\n')+1
135 133 return self.screen_length - num_lines_bot
136 134
137 135 def init_term_title(self):
138 136 # Enable or disable the terminal title.
139 137 if self.term_title:
140 138 toggle_set_term_title(True)
141 139 set_term_title('IPython: ' + abbrev_cwd())
142 140 else:
143 141 toggle_set_term_title(False)
144 142
145 143 #-------------------------------------------------------------------------
146 144 # Things related to aliases
147 145 #-------------------------------------------------------------------------
148 146
149 147 def init_alias(self):
150 148 # The parent class defines aliases that can be safely used with any
151 149 # frontend.
152 150 super(TerminalInteractiveShell, self).init_alias()
153 151
154 152 # Now define aliases that only make sense on the terminal, because they
155 153 # need direct access to the console in a way that we can't emulate in
156 154 # GUI or web frontend
157 155 if os.name == 'posix':
158 156 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
159 157 ('man', 'man')]
160 158 elif os.name == 'nt':
161 159 aliases = [('cls', 'cls')]
162 160
163 161
164 162 for name, cmd in aliases:
165 163 self.alias_manager.define_alias(name, cmd)
166 164
167 165 #-------------------------------------------------------------------------
168 166 # Things related to the banner and usage
169 167 #-------------------------------------------------------------------------
170 168
171 169 def _banner1_changed(self):
172 170 self.compute_banner()
173 171
174 172 def _banner2_changed(self):
175 173 self.compute_banner()
176 174
177 175 def _term_title_changed(self, name, new_value):
178 176 self.init_term_title()
179 177
180 178 def init_banner(self, banner1, banner2, display_banner):
181 179 if banner1 is not None:
182 180 self.banner1 = banner1
183 181 if banner2 is not None:
184 182 self.banner2 = banner2
185 183 if display_banner is not None:
186 184 self.display_banner = display_banner
187 185 self.compute_banner()
188 186
189 187 def show_banner(self, banner=None):
190 188 if banner is None:
191 189 banner = self.banner
192 190 self.write(banner)
193 191
194 192 def compute_banner(self):
195 193 self.banner = self.banner1
196 194 if self.profile and self.profile != 'default':
197 195 self.banner += '\nIPython profile: %s\n' % self.profile
198 196 if self.banner2:
199 197 self.banner += '\n' + self.banner2
200 198
201 199 def init_usage(self, usage=None):
202 200 if usage is None:
203 201 self.usage = interactive_usage
204 202 else:
205 203 self.usage = usage
206 204
207 205 #-------------------------------------------------------------------------
208 206 # Mainloop and code execution logic
209 207 #-------------------------------------------------------------------------
210 208
211 209 def mainloop(self, display_banner=None):
212 210 """Start the mainloop.
213 211
214 212 If an optional banner argument is given, it will override the
215 213 internally created default banner.
216 214 """
217 215
218 216 with nested(self.builtin_trap, self.display_trap):
219 217
220 218 while 1:
221 219 try:
222 220 self.interact(display_banner=display_banner)
223 221 #self.interact_with_readline()
224 222 # XXX for testing of a readline-decoupled repl loop, call
225 223 # interact_with_readline above
226 224 break
227 225 except KeyboardInterrupt:
228 226 # this should not be necessary, but KeyboardInterrupt
229 227 # handling seems rather unpredictable...
230 228 self.write("\nKeyboardInterrupt in interact()\n")
231 229
232 230 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
233 231 """Store multiple lines as a single entry in history"""
234 232
235 233 # do nothing without readline or disabled multiline
236 234 if not self.has_readline or not self.multiline_history:
237 235 return hlen_before_cell
238 236
239 237 # windows rl has no remove_history_item
240 238 if not hasattr(self.readline, "remove_history_item"):
241 239 return hlen_before_cell
242 240
243 241 # skip empty cells
244 242 if not source_raw.rstrip():
245 243 return hlen_before_cell
246 244
247 245 # nothing changed do nothing, e.g. when rl removes consecutive dups
248 246 hlen = self.readline.get_current_history_length()
249 247 if hlen == hlen_before_cell:
250 248 return hlen_before_cell
251 249
252 250 for i in range(hlen - hlen_before_cell):
253 251 self.readline.remove_history_item(hlen - i - 1)
254 252 stdin_encoding = sys.stdin.encoding or "utf-8"
255 253 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
256 254 stdin_encoding))
257 255 return self.readline.get_current_history_length()
258 256
259 257 def interact(self, display_banner=None):
260 258 """Closely emulate the interactive Python console."""
261 259
262 260 # batch run -> do not interact
263 261 if self.exit_now:
264 262 return
265 263
266 264 if display_banner is None:
267 265 display_banner = self.display_banner
268 266
269 267 if isinstance(display_banner, basestring):
270 268 self.show_banner(display_banner)
271 269 elif display_banner:
272 270 self.show_banner()
273 271
274 272 more = False
275 273
276 274 # Mark activity in the builtins
277 275 __builtin__.__dict__['__IPYTHON__active'] += 1
278 276
279 277 if self.has_readline:
280 278 self.readline_startup_hook(self.pre_readline)
281 279 hlen_b4_cell = self.readline.get_current_history_length()
282 280 else:
283 281 hlen_b4_cell = 0
284 282 # exit_now is set by a call to %Exit or %Quit, through the
285 283 # ask_exit callback.
286 284
287 285 while not self.exit_now:
288 286 self.hooks.pre_prompt_hook()
289 287 if more:
290 288 try:
291 289 prompt = self.hooks.generate_prompt(True)
292 290 except:
293 291 self.showtraceback()
294 292 if self.autoindent:
295 293 self.rl_do_indent = True
296 294
297 295 else:
298 296 try:
299 297 prompt = self.hooks.generate_prompt(False)
300 298 except:
301 299 self.showtraceback()
302 300 try:
303 301 line = self.raw_input(prompt)
304 302 if self.exit_now:
305 303 # quick exit on sys.std[in|out] close
306 304 break
307 305 if self.autoindent:
308 306 self.rl_do_indent = False
309 307
310 308 except KeyboardInterrupt:
311 309 #double-guard against keyboardinterrupts during kbdint handling
312 310 try:
313 311 self.write('\nKeyboardInterrupt\n')
314 312 source_raw = self.input_splitter.source_raw_reset()[1]
315 313 hlen_b4_cell = \
316 314 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
317 315 more = False
318 316 except KeyboardInterrupt:
319 317 pass
320 318 except EOFError:
321 319 if self.autoindent:
322 320 self.rl_do_indent = False
323 321 if self.has_readline:
324 322 self.readline_startup_hook(None)
325 323 self.write('\n')
326 324 self.exit()
327 325 except bdb.BdbQuit:
328 326 warn('The Python debugger has exited with a BdbQuit exception.\n'
329 327 'Because of how pdb handles the stack, it is impossible\n'
330 328 'for IPython to properly format this particular exception.\n'
331 329 'IPython will resume normal operation.')
332 330 except:
333 331 # exceptions here are VERY RARE, but they can be triggered
334 332 # asynchronously by signal handlers, for example.
335 333 self.showtraceback()
336 334 else:
337 335 self.input_splitter.push(line)
338 336 more = self.input_splitter.push_accepts_more()
339 337 if (self.SyntaxTB.last_syntax_error and
340 338 self.autoedit_syntax):
341 339 self.edit_syntax_error()
342 340 if not more:
343 341 source_raw = self.input_splitter.source_raw_reset()[1]
344 342 self.run_cell(source_raw, store_history=True)
345 343 hlen_b4_cell = \
346 344 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
347 345
348 346 # We are off again...
349 347 __builtin__.__dict__['__IPYTHON__active'] -= 1
350 348
351 349 # Turn off the exit flag, so the mainloop can be restarted if desired
352 350 self.exit_now = False
353 351
354 352 def raw_input(self, prompt=''):
355 353 """Write a prompt and read a line.
356 354
357 355 The returned line does not include the trailing newline.
358 356 When the user enters the EOF key sequence, EOFError is raised.
359 357
360 358 Optional inputs:
361 359
362 360 - prompt(''): a string to be printed to prompt the user.
363 361
364 362 - continue_prompt(False): whether this line is the first one or a
365 363 continuation in a sequence of inputs.
366 364 """
367 365 # Code run by the user may have modified the readline completer state.
368 366 # We must ensure that our completer is back in place.
369 367
370 368 if self.has_readline:
371 369 self.set_readline_completer()
372 370
373 371 try:
374 372 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
375 373 except ValueError:
376 374 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
377 375 " or sys.stdout.close()!\nExiting IPython!")
378 376 self.ask_exit()
379 377 return ""
380 378
381 379 # Try to be reasonably smart about not re-indenting pasted input more
382 380 # than necessary. We do this by trimming out the auto-indent initial
383 381 # spaces, if the user's actual input started itself with whitespace.
384 382 if self.autoindent:
385 383 if num_ini_spaces(line) > self.indent_current_nsp:
386 384 line = line[self.indent_current_nsp:]
387 385 self.indent_current_nsp = 0
388 386
389 387 return line
390 388
391 389 #-------------------------------------------------------------------------
392 390 # Methods to support auto-editing of SyntaxErrors.
393 391 #-------------------------------------------------------------------------
394 392
395 393 def edit_syntax_error(self):
396 394 """The bottom half of the syntax error handler called in the main loop.
397 395
398 396 Loop until syntax error is fixed or user cancels.
399 397 """
400 398
401 399 while self.SyntaxTB.last_syntax_error:
402 400 # copy and clear last_syntax_error
403 401 err = self.SyntaxTB.clear_err_state()
404 402 if not self._should_recompile(err):
405 403 return
406 404 try:
407 405 # may set last_syntax_error again if a SyntaxError is raised
408 406 self.safe_execfile(err.filename,self.user_ns)
409 407 except:
410 408 self.showtraceback()
411 409 else:
412 410 try:
413 411 f = file(err.filename)
414 412 try:
415 413 # This should be inside a display_trap block and I
416 414 # think it is.
417 415 sys.displayhook(f.read())
418 416 finally:
419 417 f.close()
420 418 except:
421 419 self.showtraceback()
422 420
423 421 def _should_recompile(self,e):
424 422 """Utility routine for edit_syntax_error"""
425 423
426 424 if e.filename in ('<ipython console>','<input>','<string>',
427 425 '<console>','<BackgroundJob compilation>',
428 426 None):
429 427
430 428 return False
431 429 try:
432 430 if (self.autoedit_syntax and
433 431 not self.ask_yes_no('Return to editor to correct syntax error? '
434 432 '[Y/n] ','y')):
435 433 return False
436 434 except EOFError:
437 435 return False
438 436
439 437 def int0(x):
440 438 try:
441 439 return int(x)
442 440 except TypeError:
443 441 return 0
444 442 # always pass integer line and offset values to editor hook
445 443 try:
446 444 self.hooks.fix_error_editor(e.filename,
447 445 int0(e.lineno),int0(e.offset),e.msg)
448 446 except TryNext:
449 447 warn('Could not open editor')
450 448 return False
451 449 return True
452 450
453 451 #-------------------------------------------------------------------------
454 452 # Things related to GUI support and pylab
455 453 #-------------------------------------------------------------------------
456 454
457 455 def enable_pylab(self, gui=None, import_all=True):
458 456 """Activate pylab support at runtime.
459 457
460 458 This turns on support for matplotlib, preloads into the interactive
461 459 namespace all of numpy and pylab, and configures IPython to correcdtly
462 460 interact with the GUI event loop. The GUI backend to be used can be
463 461 optionally selected with the optional :param:`gui` argument.
464 462
465 463 Parameters
466 464 ----------
467 465 gui : optional, string
468 466
469 467 If given, dictates the choice of matplotlib GUI backend to use
470 468 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
471 469 'gtk'), otherwise we use the default chosen by matplotlib (as
472 470 dictated by the matplotlib build-time options plus the user's
473 471 matplotlibrc configuration file).
474 472 """
475 473 # We want to prevent the loading of pylab to pollute the user's
476 474 # namespace as shown by the %who* magics, so we execute the activation
477 475 # code in an empty namespace, and we update *both* user_ns and
478 476 # user_ns_hidden with this information.
479 477 ns = {}
480 478 try:
481 479 gui = pylab_activate(ns, gui, import_all)
482 480 except KeyError:
483 481 error("Backend %r not supported" % gui)
484 482 return
485 483 self.user_ns.update(ns)
486 484 self.user_ns_hidden.update(ns)
487 485 # Now we must activate the gui pylab wants to use, and fix %run to take
488 486 # plot updates into account
489 487 enable_gui(gui)
490 488 self.magic_run = self._pylab_magic_run
491 489
492 490 #-------------------------------------------------------------------------
493 491 # Things related to exiting
494 492 #-------------------------------------------------------------------------
495 493
496 494 def ask_exit(self):
497 495 """ Ask the shell to exit. Can be overiden and used as a callback. """
498 496 self.exit_now = True
499 497
500 498 def exit(self):
501 499 """Handle interactive exit.
502 500
503 501 This method calls the ask_exit callback."""
504 502 if self.confirm_exit:
505 503 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
506 504 self.ask_exit()
507 505 else:
508 506 self.ask_exit()
509 507
510 508 #------------------------------------------------------------------------
511 509 # Magic overrides
512 510 #------------------------------------------------------------------------
513 511 # Once the base class stops inheriting from magic, this code needs to be
514 512 # moved into a separate machinery as well. For now, at least isolate here
515 513 # the magics which this class needs to implement differently from the base
516 514 # class, or that are unique to it.
517 515
518 516 def magic_autoindent(self, parameter_s = ''):
519 517 """Toggle autoindent on/off (if available)."""
520 518
521 519 self.shell.set_autoindent()
522 520 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523 521
524 522 @skip_doctest
525 523 def magic_cpaste(self, parameter_s=''):
526 524 """Paste & execute a pre-formatted code block from clipboard.
527 525
528 526 You must terminate the block with '--' (two minus-signs) or Ctrl-D alone on the
529 527 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
530 528 is the new sentinel for this operation)
531 529
532 530 The block is dedented prior to execution to enable execution of method
533 531 definitions. '>' and '+' characters at the beginning of a line are
534 532 ignored, to allow pasting directly from e-mails, diff files and
535 533 doctests (the '...' continuation prompt is also stripped). The
536 534 executed block is also assigned to variable named 'pasted_block' for
537 535 later editing with '%edit pasted_block'.
538 536
539 537 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
540 538 This assigns the pasted block to variable 'foo' as string, without
541 539 dedenting or executing it (preceding >>> and + is still stripped)
542 540
543 541 '%cpaste -r' re-executes the block previously entered by cpaste.
544 542
545 543 Do not be alarmed by garbled output on Windows (it's a readline bug).
546 544 Just press enter and type -- (and press enter again) and the block
547 545 will be what was just pasted.
548 546
549 547 IPython statements (magics, shell escapes) are not supported (yet).
550 548
551 549 See also
552 550 --------
553 551 paste: automatically pull code from clipboard.
554 552
555 553 Examples
556 554 --------
557 555 ::
558 556
559 557 In [8]: %cpaste
560 558 Pasting code; enter '--' alone on the line to stop.
561 559 :>>> a = ["world!", "Hello"]
562 560 :>>> print " ".join(sorted(a))
563 561 :--
564 562 Hello world!
565 563 """
566 564
567 565 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
568 566 par = args.strip()
569 567 if opts.has_key('r'):
570 568 self._rerun_pasted()
571 569 return
572 570
573 571 sentinel = opts.get('s','--')
574 572
575 573 block = self._strip_pasted_lines_for_code(
576 574 self._get_pasted_lines(sentinel))
577 575
578 576 self._execute_block(block, par)
579 577
580 578 def magic_paste(self, parameter_s=''):
581 579 """Paste & execute a pre-formatted code block from clipboard.
582 580
583 581 The text is pulled directly from the clipboard without user
584 582 intervention and printed back on the screen before execution (unless
585 583 the -q flag is given to force quiet mode).
586 584
587 585 The block is dedented prior to execution to enable execution of method
588 586 definitions. '>' and '+' characters at the beginning of a line are
589 587 ignored, to allow pasting directly from e-mails, diff files and
590 588 doctests (the '...' continuation prompt is also stripped). The
591 589 executed block is also assigned to variable named 'pasted_block' for
592 590 later editing with '%edit pasted_block'.
593 591
594 592 You can also pass a variable name as an argument, e.g. '%paste foo'.
595 593 This assigns the pasted block to variable 'foo' as string, without
596 594 dedenting or executing it (preceding >>> and + is still stripped)
597 595
598 596 Options
599 597 -------
600 598
601 599 -r: re-executes the block previously entered by cpaste.
602 600
603 601 -q: quiet mode: do not echo the pasted text back to the terminal.
604 602
605 603 IPython statements (magics, shell escapes) are not supported (yet).
606 604
607 605 See also
608 606 --------
609 607 cpaste: manually paste code into terminal until you mark its end.
610 608 """
611 609 opts,args = self.parse_options(parameter_s,'rq',mode='string')
612 610 par = args.strip()
613 611 if opts.has_key('r'):
614 612 self._rerun_pasted()
615 613 return
616 614
617 615 text = self.shell.hooks.clipboard_get()
618 616 block = self._strip_pasted_lines_for_code(text.splitlines())
619 617
620 618 # By default, echo back to terminal unless quiet mode is requested
621 619 if not opts.has_key('q'):
622 620 write = self.shell.write
623 621 write(self.shell.pycolorize(block))
624 622 if not block.endswith('\n'):
625 623 write('\n')
626 624 write("## -- End pasted text --\n")
627 625
628 626 self._execute_block(block, par)
629 627
630 628 if sys.platform == 'win32':
631 629 def magic_cls(self, s):
632 630 """Clear screen.
633 631 """
634 632 os.system("cls")
635 633
636 634 def showindentationerror(self):
637 635 super(TerminalInteractiveShell, self).showindentationerror()
638 636 print("If you want to paste code into IPython, try the %paste magic function.")
639 637
640 638
641 639 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now