Show More
@@ -0,0 +1,48 b'' | |||||
|
1 | """Tests for the IPython tab-completion machinery. | |||
|
2 | """ | |||
|
3 | #----------------------------------------------------------------------------- | |||
|
4 | # Module imports | |||
|
5 | #----------------------------------------------------------------------------- | |||
|
6 | ||||
|
7 | # stdlib | |||
|
8 | import os | |||
|
9 | import sys | |||
|
10 | import unittest | |||
|
11 | ||||
|
12 | # third party | |||
|
13 | import nose.tools as nt | |||
|
14 | ||||
|
15 | # our own packages | |||
|
16 | from IPython.utils.tempdir import TemporaryDirectory | |||
|
17 | from IPython.core.history import HistoryManager | |||
|
18 | ||||
|
19 | def test_history(): | |||
|
20 | ||||
|
21 | ip = get_ipython() | |||
|
22 | with TemporaryDirectory() as tmpdir: | |||
|
23 | #tmpdir = '/software/temp' | |||
|
24 | histfile = os.path.realpath(os.path.join(tmpdir, 'history.json')) | |||
|
25 | # Ensure that we restore the history management that we mess with in | |||
|
26 | # this test doesn't affect the IPython instance used by the test suite | |||
|
27 | # beyond this test. | |||
|
28 | hist_manager_ori = ip.history_manager | |||
|
29 | try: | |||
|
30 | ip.history_manager = HistoryManager(ip) | |||
|
31 | ip.history_manager.hist_file = histfile | |||
|
32 | print 'test',histfile | |||
|
33 | hist = ['a=1\n', 'def f():\n test = 1\n return test\n', 'b=2\n'] | |||
|
34 | # test save and load | |||
|
35 | ip.history_manager.input_hist_raw[:] = [] | |||
|
36 | for h in hist: | |||
|
37 | ip.history_manager.input_hist_raw.append(h) | |||
|
38 | ip.save_history() | |||
|
39 | ip.history_manager.input_hist_raw[:] = [] | |||
|
40 | ip.reload_history() | |||
|
41 | print type(ip.history_manager.input_hist_raw) | |||
|
42 | print ip.history_manager.input_hist_raw | |||
|
43 | nt.assert_equal(len(ip.history_manager.input_hist_raw), len(hist)) | |||
|
44 | for i,h in enumerate(hist): | |||
|
45 | nt.assert_equal(hist[i], ip.history_manager.input_hist_raw[i]) | |||
|
46 | finally: | |||
|
47 | # Restore history manager | |||
|
48 | ip.history_manager = hist_manager_ori |
@@ -1,144 +1,146 b'' | |||||
1 | # Get the config being loaded so we can set attributes on it |
|
1 | # Get the config being loaded so we can set attributes on it | |
2 | c = get_config() |
|
2 | c = get_config() | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Global options |
|
5 | # Global options | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 |
|
7 | |||
8 | # c.Global.display_banner = True |
|
8 | # c.Global.display_banner = True | |
9 |
|
9 | |||
10 | # c.Global.classic = False |
|
10 | # c.Global.classic = False | |
11 |
|
11 | |||
12 | # c.Global.nosep = True |
|
12 | # c.Global.nosep = True | |
13 |
|
13 | |||
14 | # Set this to determine the detail of what is logged at startup. |
|
14 | # Set this to determine the detail of what is logged at startup. | |
15 | # The default is 30 and possible values are 0,10,20,30,40,50. |
|
15 | # The default is 30 and possible values are 0,10,20,30,40,50. | |
16 | # c.Global.log_level = 20 |
|
16 | # c.Global.log_level = 20 | |
17 |
|
17 | |||
18 | # This should be a list of importable Python modules that have an |
|
18 | # This should be a list of importable Python modules that have an | |
19 | # load_in_ipython(ip) method. This method gets called when the extension |
|
19 | # load_in_ipython(ip) method. This method gets called when the extension | |
20 | # is loaded. You can put your extensions anywhere they can be imported |
|
20 | # is loaded. You can put your extensions anywhere they can be imported | |
21 | # but we add the extensions subdir of the ipython directory to sys.path |
|
21 | # but we add the extensions subdir of the ipython directory to sys.path | |
22 | # during extension loading, so you can put them there as well. |
|
22 | # during extension loading, so you can put them there as well. | |
23 | # c.Global.extensions = [ |
|
23 | # c.Global.extensions = [ | |
24 | # 'myextension' |
|
24 | # 'myextension' | |
25 | # ] |
|
25 | # ] | |
26 |
|
26 | |||
27 | # These lines are run in IPython in the user's namespace after extensions |
|
27 | # These lines are run in IPython in the user's namespace after extensions | |
28 | # are loaded. They can contain full IPython syntax with magics etc. |
|
28 | # are loaded. They can contain full IPython syntax with magics etc. | |
29 | # c.Global.exec_lines = [ |
|
29 | # c.Global.exec_lines = [ | |
30 | # 'import numpy', |
|
30 | # 'import numpy', | |
31 | # 'a = 10; b = 20', |
|
31 | # 'a = 10; b = 20', | |
32 | # '1/0' |
|
32 | # '1/0' | |
33 | # ] |
|
33 | # ] | |
34 |
|
34 | |||
35 | # These files are run in IPython in the user's namespace. Files with a .py |
|
35 | # These files are run in IPython in the user's namespace. Files with a .py | |
36 | # extension need to be pure Python. Files with a .ipy extension can have |
|
36 | # extension need to be pure Python. Files with a .ipy extension can have | |
37 | # custom IPython syntax (like magics, etc.). |
|
37 | # custom IPython syntax (like magics, etc.). | |
38 | # These files need to be in the cwd, the ipython_dir or be absolute paths. |
|
38 | # These files need to be in the cwd, the ipython_dir or be absolute paths. | |
39 | # c.Global.exec_files = [ |
|
39 | # c.Global.exec_files = [ | |
40 | # 'mycode.py', |
|
40 | # 'mycode.py', | |
41 | # 'fancy.ipy' |
|
41 | # 'fancy.ipy' | |
42 | # ] |
|
42 | # ] | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # InteractiveShell options |
|
45 | # InteractiveShell options | |
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 |
|
47 | |||
48 | # c.InteractiveShell.autocall = 1 |
|
48 | # c.InteractiveShell.autocall = 1 | |
49 |
|
49 | |||
50 | # c.TerminalInteractiveShell.autoedit_syntax = False |
|
50 | # c.TerminalInteractiveShell.autoedit_syntax = False | |
51 |
|
51 | |||
52 | # c.InteractiveShell.autoindent = True |
|
52 | # c.InteractiveShell.autoindent = True | |
53 |
|
53 | |||
54 | # c.InteractiveShell.automagic = False |
|
54 | # c.InteractiveShell.automagic = False | |
55 |
|
55 | |||
56 | # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner' |
|
56 | # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner' | |
57 |
|
57 | |||
58 | # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text" |
|
58 | # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text" | |
59 |
|
59 | |||
60 | # c.InteractiveShell.cache_size = 1000 |
|
60 | # c.InteractiveShell.cache_size = 1000 | |
61 |
|
61 | |||
62 | # c.InteractiveShell.colors = 'LightBG' |
|
62 | # c.InteractiveShell.colors = 'LightBG' | |
63 |
|
63 | |||
64 | # c.InteractiveShell.color_info = True |
|
64 | # c.InteractiveShell.color_info = True | |
65 |
|
65 | |||
66 | # c.TerminalInteractiveShell.confirm_exit = True |
|
66 | # c.TerminalInteractiveShell.confirm_exit = True | |
67 |
|
67 | |||
68 | # c.InteractiveShell.deep_reload = False |
|
68 | # c.InteractiveShell.deep_reload = False | |
69 |
|
69 | |||
70 | # c.TerminalInteractiveShell.editor = 'nano' |
|
70 | # c.TerminalInteractiveShell.editor = 'nano' | |
71 |
|
71 | |||
72 | # c.InteractiveShell.logstart = True |
|
72 | # c.InteractiveShell.logstart = True | |
73 |
|
73 | |||
74 | # c.InteractiveShell.logfile = u'ipython_log.py' |
|
74 | # c.InteractiveShell.logfile = u'ipython_log.py' | |
75 |
|
75 | |||
76 | # c.InteractiveShell.logappend = u'mylog.py' |
|
76 | # c.InteractiveShell.logappend = u'mylog.py' | |
77 |
|
77 | |||
78 | # c.InteractiveShell.object_info_string_level = 0 |
|
78 | # c.InteractiveShell.object_info_string_level = 0 | |
79 |
|
79 | |||
80 | # c.TerminalInteractiveShell.pager = 'less' |
|
80 | # c.TerminalInteractiveShell.pager = 'less' | |
81 |
|
81 | |||
82 | # c.InteractiveShell.pdb = False |
|
82 | # c.InteractiveShell.pdb = False | |
83 |
|
83 | |||
84 | # c.InteractiveShell.pprint = True |
|
84 | # c.InteractiveShell.pprint = True | |
85 |
|
85 | |||
86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' |
|
86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' | |
87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' |
|
87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' | |
88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' |
|
88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' | |
89 | # c.InteractiveShell.prompts_pad_left = True |
|
89 | # c.InteractiveShell.prompts_pad_left = True | |
90 |
|
90 | |||
91 | # c.InteractiveShell.quiet = False |
|
91 | # c.InteractiveShell.quiet = False | |
92 |
|
92 | |||
|
93 | # c.InteractiveShell.history_length = 10000 | |||
|
94 | ||||
93 | # Readline |
|
95 | # Readline | |
94 | # c.InteractiveShell.readline_use = True |
|
96 | # c.InteractiveShell.readline_use = True | |
95 |
|
97 | |||
96 | # c.InteractiveShell.readline_parse_and_bind = [ |
|
98 | # c.InteractiveShell.readline_parse_and_bind = [ | |
97 | # 'tab: complete', |
|
99 | # 'tab: complete', | |
98 | # '"\C-l": possible-completions', |
|
100 | # '"\C-l": possible-completions', | |
99 | # 'set show-all-if-ambiguous on', |
|
101 | # 'set show-all-if-ambiguous on', | |
100 | # '"\C-o": tab-insert', |
|
102 | # '"\C-o": tab-insert', | |
101 | # '"\M-i": " "', |
|
103 | # '"\M-i": " "', | |
102 | # '"\M-o": "\d\d\d\d"', |
|
104 | # '"\M-o": "\d\d\d\d"', | |
103 | # '"\M-I": "\d\d\d\d"', |
|
105 | # '"\M-I": "\d\d\d\d"', | |
104 | # '"\C-r": reverse-search-history', |
|
106 | # '"\C-r": reverse-search-history', | |
105 | # '"\C-s": forward-search-history', |
|
107 | # '"\C-s": forward-search-history', | |
106 | # '"\C-p": history-search-backward', |
|
108 | # '"\C-p": history-search-backward', | |
107 | # '"\C-n": history-search-forward', |
|
109 | # '"\C-n": history-search-forward', | |
108 | # '"\e[A": history-search-backward', |
|
110 | # '"\e[A": history-search-backward', | |
109 | # '"\e[B": history-search-forward', |
|
111 | # '"\e[B": history-search-forward', | |
110 | # '"\C-k": kill-line', |
|
112 | # '"\C-k": kill-line', | |
111 | # '"\C-u": unix-line-discard', |
|
113 | # '"\C-u": unix-line-discard', | |
112 | # ] |
|
114 | # ] | |
113 | # c.InteractiveShell.readline_remove_delims = '-/~' |
|
115 | # c.InteractiveShell.readline_remove_delims = '-/~' | |
114 | # c.InteractiveShell.readline_merge_completions = True |
|
116 | # c.InteractiveShell.readline_merge_completions = True | |
115 | # c.InteractiveShell.readline_omit__names = 0 |
|
117 | # c.InteractiveShell.readline_omit__names = 0 | |
116 |
|
118 | |||
117 | # c.TerminalInteractiveShell.screen_length = 0 |
|
119 | # c.TerminalInteractiveShell.screen_length = 0 | |
118 |
|
120 | |||
119 | # c.InteractiveShell.separate_in = '\n' |
|
121 | # c.InteractiveShell.separate_in = '\n' | |
120 | # c.InteractiveShell.separate_out = '' |
|
122 | # c.InteractiveShell.separate_out = '' | |
121 | # c.InteractiveShell.separate_out2 = '' |
|
123 | # c.InteractiveShell.separate_out2 = '' | |
122 |
|
124 | |||
123 | # c.TerminalInteractiveShell.term_title = False |
|
125 | # c.TerminalInteractiveShell.term_title = False | |
124 |
|
126 | |||
125 | # c.InteractiveShell.wildcards_case_sensitive = True |
|
127 | # c.InteractiveShell.wildcards_case_sensitive = True | |
126 |
|
128 | |||
127 | # c.InteractiveShell.xmode = 'Context' |
|
129 | # c.InteractiveShell.xmode = 'Context' | |
128 |
|
130 | |||
129 | #----------------------------------------------------------------------------- |
|
131 | #----------------------------------------------------------------------------- | |
130 | # PrefilterManager options |
|
132 | # PrefilterManager options | |
131 | #----------------------------------------------------------------------------- |
|
133 | #----------------------------------------------------------------------------- | |
132 |
|
134 | |||
133 | # c.PrefilterManager.multi_line_specials = True |
|
135 | # c.PrefilterManager.multi_line_specials = True | |
134 |
|
136 | |||
135 | #----------------------------------------------------------------------------- |
|
137 | #----------------------------------------------------------------------------- | |
136 | # AliasManager options |
|
138 | # AliasManager options | |
137 | #----------------------------------------------------------------------------- |
|
139 | #----------------------------------------------------------------------------- | |
138 |
|
140 | |||
139 | # Do this to disable all defaults |
|
141 | # Do this to disable all defaults | |
140 | # c.AliasManager.default_aliases = [] |
|
142 | # c.AliasManager.default_aliases = [] | |
141 |
|
143 | |||
142 | # c.AliasManager.user_aliases = [ |
|
144 | # c.AliasManager.user_aliases = [ | |
143 | # ('foo', 'echo Hi') |
|
145 | # ('foo', 'echo Hi') | |
144 | # ] |
|
146 | # ] |
@@ -1,304 +1,304 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | Authors: |
|
4 | Authors: | |
5 |
|
5 | |||
6 | * Fernando Perez |
|
6 | * Fernando Perez | |
7 | * Brian Granger |
|
7 | * Brian Granger | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2010 The IPython Development Team |
|
11 | # Copyright (C) 2008-2010 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 |
|
23 | |||
24 | from IPython.config.configurable import Configurable |
|
24 | from IPython.config.configurable import Configurable | |
25 | from IPython.core import prompts |
|
25 | from IPython.core import prompts | |
26 | import IPython.utils.generics |
|
26 | import IPython.utils.generics | |
27 | import IPython.utils.io |
|
27 | import IPython.utils.io | |
28 | from IPython.utils.traitlets import Instance, List |
|
28 | from IPython.utils.traitlets import Instance, List | |
29 | from IPython.utils.warn import warn |
|
29 | from IPython.utils.warn import warn | |
30 | from IPython.core.formatters import DefaultFormatter |
|
30 | from IPython.core.formatters import DefaultFormatter | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Main displayhook class |
|
33 | # Main displayhook class | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | # TODO: The DisplayHook class should be split into two classes, one that |
|
36 | # TODO: The DisplayHook class should be split into two classes, one that | |
37 | # manages the prompts and their synchronization and another that just does the |
|
37 | # manages the prompts and their synchronization and another that just does the | |
38 | # displayhook logic and calls into the prompt manager. |
|
38 | # displayhook logic and calls into the prompt manager. | |
39 |
|
39 | |||
40 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
40 | # TODO: Move the various attributes (cache_size, colors, input_sep, | |
41 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
41 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also | |
42 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
42 | # attributes of InteractiveShell. They should be on ONE object only and the | |
43 | # other objects should ask that one object for their values. |
|
43 | # other objects should ask that one object for their values. | |
44 |
|
44 | |||
45 | class DisplayHook(Configurable): |
|
45 | class DisplayHook(Configurable): | |
46 | """The custom IPython displayhook to replace sys.displayhook. |
|
46 | """The custom IPython displayhook to replace sys.displayhook. | |
47 |
|
47 | |||
48 | This class does many things, but the basic idea is that it is a callable |
|
48 | This class does many things, but the basic idea is that it is a callable | |
49 | that gets called anytime user code returns a value. |
|
49 | that gets called anytime user code returns a value. | |
50 |
|
50 | |||
51 | Currently this class does more than just the displayhook logic and that |
|
51 | Currently this class does more than just the displayhook logic and that | |
52 | extra logic should eventually be moved out of here. |
|
52 | extra logic should eventually be moved out of here. | |
53 | """ |
|
53 | """ | |
54 |
|
54 | |||
55 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
55 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
56 |
|
56 | |||
57 | # The default formatter. |
|
57 | # The default formatter. | |
58 | default_formatter = Instance('IPython.core.formatters.FormatterABC') |
|
58 | default_formatter = Instance('IPython.core.formatters.FormatterABC') | |
59 | def _default_formatter_default(self): |
|
59 | def _default_formatter_default(self): | |
60 | # FIXME: backwards compatibility for the InteractiveShell.pprint option? |
|
60 | # FIXME: backwards compatibility for the InteractiveShell.pprint option? | |
61 | return DefaultFormatter(config=self.config) |
|
61 | return DefaultFormatter(config=self.config) | |
62 |
|
62 | |||
63 | # Any additional FormatterABC instances we use. |
|
63 | # Any additional FormatterABC instances we use. | |
64 | # FIXME: currently unused. |
|
64 | # FIXME: currently unused. | |
65 | extra_formatters = List(config=True) |
|
65 | extra_formatters = List(config=True) | |
66 |
|
66 | |||
67 | # Each call to the In[] prompt raises it by 1, even the first. |
|
67 | # Each call to the In[] prompt raises it by 1, even the first. | |
68 | #prompt_count = Int(0) |
|
68 | #prompt_count = Int(0) | |
69 |
|
69 | |||
70 | def __init__(self, shell=None, cache_size=1000, |
|
70 | def __init__(self, shell=None, cache_size=1000, | |
71 | colors='NoColor', input_sep='\n', |
|
71 | colors='NoColor', input_sep='\n', | |
72 | output_sep='\n', output_sep2='', |
|
72 | output_sep='\n', output_sep2='', | |
73 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
73 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, | |
74 | config=None): |
|
74 | config=None): | |
75 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
75 | super(DisplayHook, self).__init__(shell=shell, config=config) | |
76 |
|
76 | |||
77 | cache_size_min = 3 |
|
77 | cache_size_min = 3 | |
78 | if cache_size <= 0: |
|
78 | if cache_size <= 0: | |
79 | self.do_full_cache = 0 |
|
79 | self.do_full_cache = 0 | |
80 | cache_size = 0 |
|
80 | cache_size = 0 | |
81 | elif cache_size < cache_size_min: |
|
81 | elif cache_size < cache_size_min: | |
82 | self.do_full_cache = 0 |
|
82 | self.do_full_cache = 0 | |
83 | cache_size = 0 |
|
83 | cache_size = 0 | |
84 | warn('caching was disabled (min value for cache size is %s).' % |
|
84 | warn('caching was disabled (min value for cache size is %s).' % | |
85 | cache_size_min,level=3) |
|
85 | cache_size_min,level=3) | |
86 | else: |
|
86 | else: | |
87 | self.do_full_cache = 1 |
|
87 | self.do_full_cache = 1 | |
88 |
|
88 | |||
89 | self.cache_size = cache_size |
|
89 | self.cache_size = cache_size | |
90 | self.input_sep = input_sep |
|
90 | self.input_sep = input_sep | |
91 |
|
91 | |||
92 | # we need a reference to the user-level namespace |
|
92 | # we need a reference to the user-level namespace | |
93 | self.shell = shell |
|
93 | self.shell = shell | |
94 |
|
94 | |||
95 | # Set input prompt strings and colors |
|
95 | # Set input prompt strings and colors | |
96 | if cache_size == 0: |
|
96 | if cache_size == 0: | |
97 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
97 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ | |
98 | or ps1.find(r'\N') > -1: |
|
98 | or ps1.find(r'\N') > -1: | |
99 | ps1 = '>>> ' |
|
99 | ps1 = '>>> ' | |
100 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
100 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ | |
101 | or ps2.find(r'\N') > -1: |
|
101 | or ps2.find(r'\N') > -1: | |
102 | ps2 = '... ' |
|
102 | ps2 = '... ' | |
103 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
103 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') | |
104 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
104 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') | |
105 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
105 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') | |
106 |
|
106 | |||
107 | self.color_table = prompts.PromptColors |
|
107 | self.color_table = prompts.PromptColors | |
108 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
108 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, | |
109 | pad_left=pad_left) |
|
109 | pad_left=pad_left) | |
110 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
110 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) | |
111 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
111 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, | |
112 | pad_left=pad_left) |
|
112 | pad_left=pad_left) | |
113 | self.set_colors(colors) |
|
113 | self.set_colors(colors) | |
114 |
|
114 | |||
115 | # Store the last prompt string each time, we need it for aligning |
|
115 | # Store the last prompt string each time, we need it for aligning | |
116 | # continuation and auto-rewrite prompts |
|
116 | # continuation and auto-rewrite prompts | |
117 | self.last_prompt = '' |
|
117 | self.last_prompt = '' | |
118 | self.output_sep = output_sep |
|
118 | self.output_sep = output_sep | |
119 | self.output_sep2 = output_sep2 |
|
119 | self.output_sep2 = output_sep2 | |
120 | self._,self.__,self.___ = '','','' |
|
120 | self._,self.__,self.___ = '','','' | |
121 |
|
121 | |||
122 | # these are deliberately global: |
|
122 | # these are deliberately global: | |
123 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
123 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
124 | self.shell.user_ns.update(to_user_ns) |
|
124 | self.shell.user_ns.update(to_user_ns) | |
125 |
|
125 | |||
126 | @property |
|
126 | @property | |
127 | def prompt_count(self): |
|
127 | def prompt_count(self): | |
128 | return self.shell.execution_count |
|
128 | return self.shell.execution_count | |
129 |
|
129 | |||
130 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
130 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): | |
131 | if p_str is None: |
|
131 | if p_str is None: | |
132 | if self.do_full_cache: |
|
132 | if self.do_full_cache: | |
133 | return cache_def |
|
133 | return cache_def | |
134 | else: |
|
134 | else: | |
135 | return no_cache_def |
|
135 | return no_cache_def | |
136 | else: |
|
136 | else: | |
137 | return p_str |
|
137 | return p_str | |
138 |
|
138 | |||
139 | def set_colors(self, colors): |
|
139 | def set_colors(self, colors): | |
140 | """Set the active color scheme and configure colors for the three |
|
140 | """Set the active color scheme and configure colors for the three | |
141 | prompt subsystems.""" |
|
141 | prompt subsystems.""" | |
142 |
|
142 | |||
143 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
143 | # FIXME: This modifying of the global prompts.prompt_specials needs | |
144 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
144 | # to be fixed. We need to refactor all of the prompts stuff to use | |
145 | # proper configuration and traits notifications. |
|
145 | # proper configuration and traits notifications. | |
146 | if colors.lower()=='nocolor': |
|
146 | if colors.lower()=='nocolor': | |
147 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
147 | prompts.prompt_specials = prompts.prompt_specials_nocolor | |
148 | else: |
|
148 | else: | |
149 | prompts.prompt_specials = prompts.prompt_specials_color |
|
149 | prompts.prompt_specials = prompts.prompt_specials_color | |
150 |
|
150 | |||
151 | self.color_table.set_active_scheme(colors) |
|
151 | self.color_table.set_active_scheme(colors) | |
152 | self.prompt1.set_colors() |
|
152 | self.prompt1.set_colors() | |
153 | self.prompt2.set_colors() |
|
153 | self.prompt2.set_colors() | |
154 | self.prompt_out.set_colors() |
|
154 | self.prompt_out.set_colors() | |
155 |
|
155 | |||
156 | #------------------------------------------------------------------------- |
|
156 | #------------------------------------------------------------------------- | |
157 | # Methods used in __call__. Override these methods to modify the behavior |
|
157 | # Methods used in __call__. Override these methods to modify the behavior | |
158 | # of the displayhook. |
|
158 | # of the displayhook. | |
159 | #------------------------------------------------------------------------- |
|
159 | #------------------------------------------------------------------------- | |
160 |
|
160 | |||
161 | def check_for_underscore(self): |
|
161 | def check_for_underscore(self): | |
162 | """Check if the user has set the '_' variable by hand.""" |
|
162 | """Check if the user has set the '_' variable by hand.""" | |
163 | # If something injected a '_' variable in __builtin__, delete |
|
163 | # If something injected a '_' variable in __builtin__, delete | |
164 | # ipython's automatic one so we don't clobber that. gettext() in |
|
164 | # ipython's automatic one so we don't clobber that. gettext() in | |
165 | # particular uses _, so we need to stay away from it. |
|
165 | # particular uses _, so we need to stay away from it. | |
166 | if '_' in __builtin__.__dict__: |
|
166 | if '_' in __builtin__.__dict__: | |
167 | try: |
|
167 | try: | |
168 | del self.shell.user_ns['_'] |
|
168 | del self.shell.user_ns['_'] | |
169 | except KeyError: |
|
169 | except KeyError: | |
170 | pass |
|
170 | pass | |
171 |
|
171 | |||
172 | def quiet(self): |
|
172 | def quiet(self): | |
173 | """Should we silence the display hook because of ';'?""" |
|
173 | """Should we silence the display hook because of ';'?""" | |
174 | # do not print output if input ends in ';' |
|
174 | # do not print output if input ends in ';' | |
175 | try: |
|
175 | try: | |
176 | if self.shell.input_hist[self.prompt_count].endswith(';\n'): |
|
176 | if self.shell.history_manager.input_hist_parsed[self.prompt_count].endswith(';\n'): | |
177 | return True |
|
177 | return True | |
178 | except IndexError: |
|
178 | except IndexError: | |
179 | # some uses of ipshellembed may fail here |
|
179 | # some uses of ipshellembed may fail here | |
180 | pass |
|
180 | pass | |
181 | return False |
|
181 | return False | |
182 |
|
182 | |||
183 | def start_displayhook(self): |
|
183 | def start_displayhook(self): | |
184 | """Start the displayhook, initializing resources.""" |
|
184 | """Start the displayhook, initializing resources.""" | |
185 | pass |
|
185 | pass | |
186 |
|
186 | |||
187 | def write_output_prompt(self): |
|
187 | def write_output_prompt(self): | |
188 | """Write the output prompt.""" |
|
188 | """Write the output prompt.""" | |
189 | # Use write, not print which adds an extra space. |
|
189 | # Use write, not print which adds an extra space. | |
190 | IPython.utils.io.Term.cout.write(self.output_sep) |
|
190 | IPython.utils.io.Term.cout.write(self.output_sep) | |
191 | outprompt = str(self.prompt_out) |
|
191 | outprompt = str(self.prompt_out) | |
192 | if self.do_full_cache: |
|
192 | if self.do_full_cache: | |
193 | IPython.utils.io.Term.cout.write(outprompt) |
|
193 | IPython.utils.io.Term.cout.write(outprompt) | |
194 |
|
194 | |||
195 | def compute_result_repr(self, result): |
|
195 | def compute_result_repr(self, result): | |
196 | """Compute and return the repr of the object to be displayed. |
|
196 | """Compute and return the repr of the object to be displayed. | |
197 |
|
197 | |||
198 | This method only compute the string form of the repr and should NOT |
|
198 | This method only compute the string form of the repr and should NOT | |
199 | actually print or write that to a stream. |
|
199 | actually print or write that to a stream. | |
200 | """ |
|
200 | """ | |
201 | result_repr = self.default_formatter(result) |
|
201 | result_repr = self.default_formatter(result) | |
202 | extra_formats = [] |
|
202 | extra_formats = [] | |
203 | for f in self.extra_formatters: |
|
203 | for f in self.extra_formatters: | |
204 | try: |
|
204 | try: | |
205 | data = f(result) |
|
205 | data = f(result) | |
206 | except Exception: |
|
206 | except Exception: | |
207 | # FIXME: log the exception. |
|
207 | # FIXME: log the exception. | |
208 | continue |
|
208 | continue | |
209 | if data is not None: |
|
209 | if data is not None: | |
210 | extra_formats.append((f.id, f.format, data)) |
|
210 | extra_formats.append((f.id, f.format, data)) | |
211 |
|
211 | |||
212 | return result_repr, extra_formats |
|
212 | return result_repr, extra_formats | |
213 |
|
213 | |||
214 | def write_result_repr(self, result_repr, extra_formats): |
|
214 | def write_result_repr(self, result_repr, extra_formats): | |
215 | # We want to print because we want to always make sure we have a |
|
215 | # We want to print because we want to always make sure we have a | |
216 | # newline, even if all the prompt separators are ''. This is the |
|
216 | # newline, even if all the prompt separators are ''. This is the | |
217 | # standard IPython behavior. |
|
217 | # standard IPython behavior. | |
218 | if '\n' in result_repr: |
|
218 | if '\n' in result_repr: | |
219 | # So that multi-line strings line up with the left column of |
|
219 | # So that multi-line strings line up with the left column of | |
220 | # the screen, instead of having the output prompt mess up |
|
220 | # the screen, instead of having the output prompt mess up | |
221 | # their first line. |
|
221 | # their first line. | |
222 | # We use the ps_out_str template instead of the expanded prompt |
|
222 | # We use the ps_out_str template instead of the expanded prompt | |
223 | # because the expansion may add ANSI escapes that will interfere |
|
223 | # because the expansion may add ANSI escapes that will interfere | |
224 | # with our ability to determine whether or not we should add |
|
224 | # with our ability to determine whether or not we should add | |
225 | # a newline. |
|
225 | # a newline. | |
226 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): |
|
226 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): | |
227 | # But avoid extraneous empty lines. |
|
227 | # But avoid extraneous empty lines. | |
228 | result_repr = '\n' + result_repr |
|
228 | result_repr = '\n' + result_repr | |
229 |
|
229 | |||
230 | print >>IPython.utils.io.Term.cout, result_repr |
|
230 | print >>IPython.utils.io.Term.cout, result_repr | |
231 |
|
231 | |||
232 | def update_user_ns(self, result): |
|
232 | def update_user_ns(self, result): | |
233 | """Update user_ns with various things like _, __, _1, etc.""" |
|
233 | """Update user_ns with various things like _, __, _1, etc.""" | |
234 |
|
234 | |||
235 | # Avoid recursive reference when displaying _oh/Out |
|
235 | # Avoid recursive reference when displaying _oh/Out | |
236 | if result is not self.shell.user_ns['_oh']: |
|
236 | if result is not self.shell.user_ns['_oh']: | |
237 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
237 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
238 | warn('Output cache limit (currently '+ |
|
238 | warn('Output cache limit (currently '+ | |
239 | `self.cache_size`+' entries) hit.\n' |
|
239 | `self.cache_size`+' entries) hit.\n' | |
240 | 'Flushing cache and resetting history counter...\n' |
|
240 | 'Flushing cache and resetting history counter...\n' | |
241 | 'The only history variables available will be _,__,___ and _1\n' |
|
241 | 'The only history variables available will be _,__,___ and _1\n' | |
242 | 'with the current result.') |
|
242 | 'with the current result.') | |
243 |
|
243 | |||
244 | self.flush() |
|
244 | self.flush() | |
245 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
245 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
246 | # we cause buggy behavior for things like gettext). |
|
246 | # we cause buggy behavior for things like gettext). | |
247 | if '_' not in __builtin__.__dict__: |
|
247 | if '_' not in __builtin__.__dict__: | |
248 | self.___ = self.__ |
|
248 | self.___ = self.__ | |
249 | self.__ = self._ |
|
249 | self.__ = self._ | |
250 | self._ = result |
|
250 | self._ = result | |
251 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) |
|
251 | self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___}) | |
252 |
|
252 | |||
253 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
253 | # hackish access to top-level namespace to create _1,_2... dynamically | |
254 | to_main = {} |
|
254 | to_main = {} | |
255 | if self.do_full_cache: |
|
255 | if self.do_full_cache: | |
256 | new_result = '_'+`self.prompt_count` |
|
256 | new_result = '_'+`self.prompt_count` | |
257 | to_main[new_result] = result |
|
257 | to_main[new_result] = result | |
258 | self.shell.user_ns.update(to_main) |
|
258 | self.shell.user_ns.update(to_main) | |
259 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
259 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
260 |
|
260 | |||
261 | def log_output(self, result): |
|
261 | def log_output(self, result): | |
262 | """Log the output.""" |
|
262 | """Log the output.""" | |
263 | if self.shell.logger.log_output: |
|
263 | if self.shell.logger.log_output: | |
264 | self.shell.logger.log_write(repr(result), 'output') |
|
264 | self.shell.logger.log_write(repr(result), 'output') | |
265 |
|
265 | |||
266 | def finish_displayhook(self): |
|
266 | def finish_displayhook(self): | |
267 | """Finish up all displayhook activities.""" |
|
267 | """Finish up all displayhook activities.""" | |
268 | IPython.utils.io.Term.cout.write(self.output_sep2) |
|
268 | IPython.utils.io.Term.cout.write(self.output_sep2) | |
269 | IPython.utils.io.Term.cout.flush() |
|
269 | IPython.utils.io.Term.cout.flush() | |
270 |
|
270 | |||
271 | def __call__(self, result=None): |
|
271 | def __call__(self, result=None): | |
272 | """Printing with history cache management. |
|
272 | """Printing with history cache management. | |
273 |
|
273 | |||
274 | This is invoked everytime the interpreter needs to print, and is |
|
274 | This is invoked everytime the interpreter needs to print, and is | |
275 | activated by setting the variable sys.displayhook to it. |
|
275 | activated by setting the variable sys.displayhook to it. | |
276 | """ |
|
276 | """ | |
277 | self.check_for_underscore() |
|
277 | self.check_for_underscore() | |
278 | if result is not None and not self.quiet(): |
|
278 | if result is not None and not self.quiet(): | |
279 | self.start_displayhook() |
|
279 | self.start_displayhook() | |
280 | self.write_output_prompt() |
|
280 | self.write_output_prompt() | |
281 | result_repr, extra_formats = self.compute_result_repr(result) |
|
281 | result_repr, extra_formats = self.compute_result_repr(result) | |
282 | self.write_result_repr(result_repr, extra_formats) |
|
282 | self.write_result_repr(result_repr, extra_formats) | |
283 | self.update_user_ns(result) |
|
283 | self.update_user_ns(result) | |
284 | self.log_output(result) |
|
284 | self.log_output(result) | |
285 | self.finish_displayhook() |
|
285 | self.finish_displayhook() | |
286 |
|
286 | |||
287 | def flush(self): |
|
287 | def flush(self): | |
288 | if not self.do_full_cache: |
|
288 | if not self.do_full_cache: | |
289 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
289 | raise ValueError,"You shouldn't have reached the cache flush "\ | |
290 | "if full caching is not enabled!" |
|
290 | "if full caching is not enabled!" | |
291 | # delete auto-generated vars from global namespace |
|
291 | # delete auto-generated vars from global namespace | |
292 |
|
292 | |||
293 | for n in range(1,self.prompt_count + 1): |
|
293 | for n in range(1,self.prompt_count + 1): | |
294 | key = '_'+`n` |
|
294 | key = '_'+`n` | |
295 | try: |
|
295 | try: | |
296 | del self.shell.user_ns[key] |
|
296 | del self.shell.user_ns[key] | |
297 | except: pass |
|
297 | except: pass | |
298 | self.shell.user_ns['_oh'].clear() |
|
298 | self.shell.user_ns['_oh'].clear() | |
299 |
|
299 | |||
300 | if '_' not in __builtin__.__dict__: |
|
300 | if '_' not in __builtin__.__dict__: | |
301 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
301 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
302 | import gc |
|
302 | import gc | |
303 | gc.collect() # xxx needed? |
|
303 | gc.collect() # xxx needed? | |
304 |
|
304 |
@@ -1,506 +1,513 b'' | |||||
1 | """ History related magics and functionality """ |
|
1 | """ History related magics and functionality """ | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (C) 2010 The IPython Development Team. |
|
3 | # Copyright (C) 2010 The IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. |
|
5 | # Distributed under the terms of the BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | # Stdlib imports |
|
15 | # Stdlib imports | |
16 | import fnmatch |
|
16 | import fnmatch | |
|
17 | import json | |||
17 | import os |
|
18 | import os | |
18 | import sys |
|
19 | import sys | |
19 |
|
20 | |||
20 | # Our own packages |
|
21 | # Our own packages | |
21 | import IPython.utils.io |
|
22 | import IPython.utils.io | |
22 |
|
23 | |||
23 | from IPython.core.inputlist import InputList |
|
24 | from IPython.core.inputlist import InputList | |
24 | from IPython.utils.pickleshare import PickleShareDB |
|
25 | from IPython.utils.pickleshare import PickleShareDB | |
25 | from IPython.utils.io import ask_yes_no |
|
26 | from IPython.utils.io import ask_yes_no | |
26 | from IPython.utils.warn import warn |
|
27 | from IPython.utils.warn import warn | |
27 |
|
28 | |||
28 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
29 | # Classes and functions |
|
30 | # Classes and functions | |
30 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
31 |
|
32 | |||
32 | class HistoryManager(object): |
|
33 | class HistoryManager(object): | |
33 | """A class to organize all history-related functionality in one place. |
|
34 | """A class to organize all history-related functionality in one place. | |
34 | """ |
|
35 | """ | |
35 | # Public interface |
|
36 | # Public interface | |
36 |
|
37 | |||
37 | # An instance of the IPython shell we are attached to |
|
38 | # An instance of the IPython shell we are attached to | |
38 | shell = None |
|
39 | shell = None | |
39 | # An InputList instance to hold processed history |
|
40 | # An InputList instance to hold processed history | |
40 | input_hist = None |
|
41 | input_hist_parsed = None | |
41 | # An InputList instance to hold raw history (as typed by user) |
|
42 | # An InputList instance to hold raw history (as typed by user) | |
42 | input_hist_raw = None |
|
43 | input_hist_raw = None | |
43 | # A list of directories visited during session |
|
44 | # A list of directories visited during session | |
44 | dir_hist = None |
|
45 | dir_hist = None | |
45 | # A dict of output history, keyed with ints from the shell's execution count |
|
46 | # A dict of output history, keyed with ints from the shell's execution count | |
46 | output_hist = None |
|
47 | output_hist = None | |
47 | # String with path to the history file |
|
48 | # String with path to the history file | |
48 | hist_file = None |
|
49 | hist_file = None | |
49 | # PickleShareDB instance holding the raw data for the shadow history |
|
50 | # PickleShareDB instance holding the raw data for the shadow history | |
50 | shadow_db = None |
|
51 | shadow_db = None | |
51 | # ShadowHist instance with the actual shadow history |
|
52 | # ShadowHist instance with the actual shadow history | |
52 | shadow_hist = None |
|
53 | shadow_hist = None | |
53 |
|
54 | |||
54 | # Private interface |
|
55 | # Private interface | |
55 | # Variables used to store the three last inputs from the user. On each new |
|
56 | # Variables used to store the three last inputs from the user. On each new | |
56 | # history update, we populate the user's namespace with these, shifted as |
|
57 | # history update, we populate the user's namespace with these, shifted as | |
57 | # necessary. |
|
58 | # necessary. | |
58 | _i00, _i, _ii, _iii = '','','','' |
|
59 | _i00, _i, _ii, _iii = '','','','' | |
59 |
|
60 | |||
60 | def __init__(self, shell): |
|
61 | def __init__(self, shell): | |
61 | """Create a new history manager associated with a shell instance. |
|
62 | """Create a new history manager associated with a shell instance. | |
62 | """ |
|
63 | """ | |
63 | # We need a pointer back to the shell for various tasks. |
|
64 | # We need a pointer back to the shell for various tasks. | |
64 | self.shell = shell |
|
65 | self.shell = shell | |
65 |
|
66 | |||
66 | # List of input with multi-line handling. |
|
67 | # List of input with multi-line handling. | |
67 |
self.input_hist = |
|
68 | self.input_hist_parsed = [] | |
68 | # This one will hold the 'raw' input history, without any |
|
69 | # This one will hold the 'raw' input history, without any | |
69 | # pre-processing. This will allow users to retrieve the input just as |
|
70 | # pre-processing. This will allow users to retrieve the input just as | |
70 | # it was exactly typed in by the user, with %hist -r. |
|
71 | # it was exactly typed in by the user, with %hist -r. | |
71 |
self.input_hist_raw = |
|
72 | self.input_hist_raw = [] | |
72 |
|
73 | |||
73 | # list of visited directories |
|
74 | # list of visited directories | |
74 | try: |
|
75 | try: | |
75 | self.dir_hist = [os.getcwd()] |
|
76 | self.dir_hist = [os.getcwd()] | |
76 | except OSError: |
|
77 | except OSError: | |
77 | self.dir_hist = [] |
|
78 | self.dir_hist = [] | |
78 |
|
79 | |||
79 | # dict of output history |
|
80 | # dict of output history | |
80 | self.output_hist = {} |
|
81 | self.output_hist = {} | |
81 |
|
82 | |||
82 | # Now the history file |
|
83 | # Now the history file | |
83 | if shell.profile: |
|
84 | if shell.profile: | |
84 | histfname = 'history-%s' % shell.profile |
|
85 | histfname = 'history-%s' % shell.profile | |
85 | else: |
|
86 | else: | |
86 | histfname = 'history' |
|
87 | histfname = 'history' | |
87 | self.hist_file = os.path.join(shell.ipython_dir, histfname) |
|
88 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.json') | |
88 |
|
89 | |||
89 | # Objects related to shadow history management |
|
90 | # Objects related to shadow history management | |
90 | self._init_shadow_hist() |
|
91 | self._init_shadow_hist() | |
91 |
|
92 | |||
92 | self._i00, self._i, self._ii, self._iii = '','','','' |
|
93 | self._i00, self._i, self._ii, self._iii = '','','','' | |
93 |
|
94 | |||
94 | # Object is fully initialized, we can now call methods on it. |
|
95 | # Object is fully initialized, we can now call methods on it. | |
95 |
|
96 | |||
96 | # Fill the history zero entry, user counter starts at 1 |
|
97 | # Fill the history zero entry, user counter starts at 1 | |
97 | self.store_inputs('\n', '\n') |
|
98 | self.store_inputs('\n', '\n') | |
98 |
|
99 | |||
99 | # For backwards compatibility, we must put these back in the shell |
|
|||
100 | # object, until we've removed all direct uses of the history objects in |
|
|||
101 | # the shell itself. |
|
|||
102 | shell.input_hist = self.input_hist |
|
|||
103 | shell.input_hist_raw = self.input_hist_raw |
|
|||
104 | shell.output_hist = self.output_hist |
|
|||
105 | shell.dir_hist = self.dir_hist |
|
|||
106 | shell.histfile = self.hist_file |
|
|||
107 | shell.shadowhist = self.shadow_hist |
|
|||
108 | shell.db = self.shadow_db |
|
|||
109 |
|
||||
110 | def _init_shadow_hist(self): |
|
100 | def _init_shadow_hist(self): | |
111 | try: |
|
101 | try: | |
112 | self.shadow_db = PickleShareDB(os.path.join( |
|
102 | self.shadow_db = PickleShareDB(os.path.join( | |
113 | self.shell.ipython_dir, 'db')) |
|
103 | self.shell.ipython_dir, 'db')) | |
114 | except UnicodeDecodeError: |
|
104 | except UnicodeDecodeError: | |
115 | print("Your ipython_dir can't be decoded to unicode!") |
|
105 | print("Your ipython_dir can't be decoded to unicode!") | |
116 | print("Please set HOME environment variable to something that") |
|
106 | print("Please set HOME environment variable to something that") | |
117 | print(r"only has ASCII characters, e.g. c:\home") |
|
107 | print(r"only has ASCII characters, e.g. c:\home") | |
118 | print("Now it is", self.ipython_dir) |
|
108 | print("Now it is", self.ipython_dir) | |
119 | sys.exit() |
|
109 | sys.exit() | |
120 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) |
|
110 | self.shadow_hist = ShadowHist(self.shadow_db, self.shell) | |
121 |
|
111 | |||
122 |
def |
|
112 | def populate_readline_history(self): | |
123 | """Save input history to a file (via readline library).""" |
|
113 | """Populate the readline history from the raw history. | |
124 |
|
|
114 | ||
125 | try: |
|
115 | We only store one copy of the raw history, which is persisted to a json | |
126 | self.shell.readline.write_history_file(self.hist_file) |
|
116 | file on disk. The readline history is repopulated from the contents of | |
127 | except: |
|
117 | this file.""" | |
128 | print('Unable to save IPython command history to file: ' + |
|
|||
129 | `self.hist_file`) |
|
|||
130 |
|
||||
131 | def reload_hist(self): |
|
|||
132 | """Reload the input history from disk file.""" |
|
|||
133 |
|
118 | |||
134 | try: |
|
119 | try: | |
135 | self.shell.readline.clear_history() |
|
120 | self.shell.readline.clear_history() | |
136 | self.shell.readline.read_history_file(self.hist_file) |
|
|||
137 | except AttributeError: |
|
121 | except AttributeError: | |
138 | pass |
|
122 | pass | |
|
123 | else: | |||
|
124 | for h in self.input_hist_raw: | |||
|
125 | if not h.isspace(): | |||
|
126 | for line in h.splitlines(): | |||
|
127 | self.shell.readline.add_history(line) | |||
|
128 | ||||
|
129 | def save_history(self): | |||
|
130 | """Save input history to a file (via readline library).""" | |||
|
131 | hist = dict(raw=self.input_hist_raw, #[-self.shell.history_length:], | |||
|
132 | parsed=self.input_hist_parsed) #[-self.shell.history_length:]) | |||
|
133 | with open(self.hist_file,'wt') as hfile: | |||
|
134 | json.dump(hist, hfile, | |||
|
135 | sort_keys=True, indent=4) | |||
|
136 | ||||
|
137 | def reload_history(self): | |||
|
138 | """Reload the input history from disk file.""" | |||
139 |
|
139 | |||
|
140 | with open(self.hist_file,'rt') as hfile: | |||
|
141 | hist = json.load(hfile) | |||
|
142 | self.input_hist_parsed = hist['parsed'] | |||
|
143 | self.input_hist_raw = hist['raw'] | |||
|
144 | if self.shell.has_readline: | |||
|
145 | self.populate_readline_history() | |||
|
146 | ||||
140 | def get_history(self, index=None, raw=False, output=True): |
|
147 | def get_history(self, index=None, raw=False, output=True): | |
141 | """Get the history list. |
|
148 | """Get the history list. | |
142 |
|
149 | |||
143 | Get the input and output history. |
|
150 | Get the input and output history. | |
144 |
|
151 | |||
145 | Parameters |
|
152 | Parameters | |
146 | ---------- |
|
153 | ---------- | |
147 | index : n or (n1, n2) or None |
|
154 | index : n or (n1, n2) or None | |
148 | If n, then the last entries. If a tuple, then all in |
|
155 | If n, then the last entries. If a tuple, then all in | |
149 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
156 | range(n1, n2). If None, then all entries. Raises IndexError if | |
150 | the format of index is incorrect. |
|
157 | the format of index is incorrect. | |
151 | raw : bool |
|
158 | raw : bool | |
152 | If True, return the raw input. |
|
159 | If True, return the raw input. | |
153 | output : bool |
|
160 | output : bool | |
154 | If True, then return the output as well. |
|
161 | If True, then return the output as well. | |
155 |
|
162 | |||
156 | Returns |
|
163 | Returns | |
157 | ------- |
|
164 | ------- | |
158 | If output is True, then return a dict of tuples, keyed by the prompt |
|
165 | If output is True, then return a dict of tuples, keyed by the prompt | |
159 | numbers and with values of (input, output). If output is False, then |
|
166 | numbers and with values of (input, output). If output is False, then | |
160 | a dict, keyed by the prompt number with the values of input. Raises |
|
167 | a dict, keyed by the prompt number with the values of input. Raises | |
161 | IndexError if no history is found. |
|
168 | IndexError if no history is found. | |
162 | """ |
|
169 | """ | |
163 | if raw: |
|
170 | if raw: | |
164 | input_hist = self.input_hist_raw |
|
171 | input_hist = self.input_hist_raw | |
165 | else: |
|
172 | else: | |
166 | input_hist = self.input_hist |
|
173 | input_hist = self.input_hist_parsed | |
167 | if output: |
|
174 | if output: | |
168 | output_hist = self.output_hist |
|
175 | output_hist = self.output_hist | |
169 | n = len(input_hist) |
|
176 | n = len(input_hist) | |
170 | if index is None: |
|
177 | if index is None: | |
171 | start=0; stop=n |
|
178 | start=0; stop=n | |
172 | elif isinstance(index, int): |
|
179 | elif isinstance(index, int): | |
173 | start=n-index; stop=n |
|
180 | start=n-index; stop=n | |
174 | elif isinstance(index, tuple) and len(index) == 2: |
|
181 | elif isinstance(index, tuple) and len(index) == 2: | |
175 | start=index[0]; stop=index[1] |
|
182 | start=index[0]; stop=index[1] | |
176 | else: |
|
183 | else: | |
177 | raise IndexError('Not a valid index for the input history: %r' |
|
184 | raise IndexError('Not a valid index for the input history: %r' | |
178 | % index) |
|
185 | % index) | |
179 | hist = {} |
|
186 | hist = {} | |
180 | for i in range(start, stop): |
|
187 | for i in range(start, stop): | |
181 | if output: |
|
188 | if output: | |
182 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
189 | hist[i] = (input_hist[i], output_hist.get(i)) | |
183 | else: |
|
190 | else: | |
184 | hist[i] = input_hist[i] |
|
191 | hist[i] = input_hist[i] | |
185 | if not hist: |
|
192 | if not hist: | |
186 | raise IndexError('No history for range of indices: %r' % index) |
|
193 | raise IndexError('No history for range of indices: %r' % index) | |
187 | return hist |
|
194 | return hist | |
188 |
|
195 | |||
189 | def store_inputs(self, source, source_raw=None): |
|
196 | def store_inputs(self, source, source_raw=None): | |
190 | """Store source and raw input in history and create input cache |
|
197 | """Store source and raw input in history and create input cache | |
191 | variables _i*. |
|
198 | variables _i*. | |
192 |
|
199 | |||
193 | Parameters |
|
200 | Parameters | |
194 | ---------- |
|
201 | ---------- | |
195 | source : str |
|
202 | source : str | |
196 | Python input. |
|
203 | Python input. | |
197 |
|
204 | |||
198 | source_raw : str, optional |
|
205 | source_raw : str, optional | |
199 | If given, this is the raw input without any IPython transformations |
|
206 | If given, this is the raw input without any IPython transformations | |
200 | applied to it. If not given, ``source`` is used. |
|
207 | applied to it. If not given, ``source`` is used. | |
201 | """ |
|
208 | """ | |
202 | if source_raw is None: |
|
209 | if source_raw is None: | |
203 | source_raw = source |
|
210 | source_raw = source | |
204 | self.input_hist.append(source) |
|
211 | self.input_hist_parsed.append(source) | |
205 | self.input_hist_raw.append(source_raw) |
|
212 | self.input_hist_raw.append(source_raw) | |
206 | self.shadow_hist.add(source) |
|
213 | self.shadow_hist.add(source) | |
207 |
|
214 | |||
208 | # update the auto _i variables |
|
215 | # update the auto _i variables | |
209 | self._iii = self._ii |
|
216 | self._iii = self._ii | |
210 | self._ii = self._i |
|
217 | self._ii = self._i | |
211 | self._i = self._i00 |
|
218 | self._i = self._i00 | |
212 | self._i00 = source_raw |
|
219 | self._i00 = source_raw | |
213 |
|
220 | |||
214 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
221 | # hackish access to user namespace to create _i1,_i2... dynamically | |
215 | new_i = '_i%s' % self.shell.execution_count |
|
222 | new_i = '_i%s' % self.shell.execution_count | |
216 | to_main = {'_i': self._i, |
|
223 | to_main = {'_i': self._i, | |
217 | '_ii': self._ii, |
|
224 | '_ii': self._ii, | |
218 | '_iii': self._iii, |
|
225 | '_iii': self._iii, | |
219 | new_i : self._i00 } |
|
226 | new_i : self._i00 } | |
220 | self.shell.user_ns.update(to_main) |
|
227 | self.shell.user_ns.update(to_main) | |
221 |
|
228 | |||
222 | def sync_inputs(self): |
|
229 | def sync_inputs(self): | |
223 | """Ensure raw and translated histories have same length.""" |
|
230 | """Ensure raw and translated histories have same length.""" | |
224 | if len(self.input_hist) != len (self.input_hist_raw): |
|
231 | if len(self.input_hist_parsed) != len (self.input_hist_raw): | |
225 | self.input_hist_raw = InputList(self.input_hist) |
|
232 | self.input_hist_raw = InputList(self.input_hist_parsed) | |
226 |
|
233 | |||
227 | def reset(self): |
|
234 | def reset(self): | |
228 | """Clear all histories managed by this object.""" |
|
235 | """Clear all histories managed by this object.""" | |
229 | self.input_hist[:] = [] |
|
236 | self.input_hist_parsed[:] = [] | |
230 | self.input_hist_raw[:] = [] |
|
237 | self.input_hist_raw[:] = [] | |
231 | self.output_hist.clear() |
|
238 | self.output_hist.clear() | |
232 | # The directory history can't be completely empty |
|
239 | # The directory history can't be completely empty | |
233 | self.dir_hist[:] = [os.getcwd()] |
|
240 | self.dir_hist[:] = [os.getcwd()] | |
234 |
|
241 | |||
235 |
|
242 | |||
236 | def magic_history(self, parameter_s = ''): |
|
243 | def magic_history(self, parameter_s = ''): | |
237 | """Print input history (_i<n> variables), with most recent last. |
|
244 | """Print input history (_i<n> variables), with most recent last. | |
238 |
|
245 | |||
239 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
246 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
240 | %history n -> print at most n inputs\\ |
|
247 | %history n -> print at most n inputs\\ | |
241 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
248 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
242 |
|
249 | |||
243 | By default, input history is printed without line numbers so it can be |
|
250 | By default, input history is printed without line numbers so it can be | |
244 | directly pasted into an editor. |
|
251 | directly pasted into an editor. | |
245 |
|
252 | |||
246 | With -n, each input's number <n> is shown, and is accessible as the |
|
253 | With -n, each input's number <n> is shown, and is accessible as the | |
247 | automatically generated variable _i<n> as well as In[<n>]. Multi-line |
|
254 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
248 | statements are printed starting at a new line for easy copy/paste. |
|
255 | statements are printed starting at a new line for easy copy/paste. | |
249 |
|
256 | |||
250 | Options: |
|
257 | Options: | |
251 |
|
258 | |||
252 | -n: print line numbers for each input. |
|
259 | -n: print line numbers for each input. | |
253 | This feature is only available if numbered prompts are in use. |
|
260 | This feature is only available if numbered prompts are in use. | |
254 |
|
261 | |||
255 | -o: also print outputs for each input. |
|
262 | -o: also print outputs for each input. | |
256 |
|
263 | |||
257 | -p: print classic '>>>' python prompts before each input. This is useful |
|
264 | -p: print classic '>>>' python prompts before each input. This is useful | |
258 | for making documentation, and in conjunction with -o, for producing |
|
265 | for making documentation, and in conjunction with -o, for producing | |
259 | doctest-ready output. |
|
266 | doctest-ready output. | |
260 |
|
267 | |||
261 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
268 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. | |
262 |
|
269 | |||
263 | -t: print the 'translated' history, as IPython understands it. IPython |
|
270 | -t: print the 'translated' history, as IPython understands it. IPython | |
264 | filters your input and converts it all into valid Python source before |
|
271 | filters your input and converts it all into valid Python source before | |
265 | executing it (things like magics or aliases are turned into function |
|
272 | executing it (things like magics or aliases are turned into function | |
266 | calls, for example). With this option, you'll see the native history |
|
273 | calls, for example). With this option, you'll see the native history | |
267 | instead of the user-entered version: '%cd /' will be seen as |
|
274 | instead of the user-entered version: '%cd /' will be seen as | |
268 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
275 | 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
269 |
|
276 | |||
270 | -g: treat the arg as a pattern to grep for in (full) history. |
|
277 | -g: treat the arg as a pattern to grep for in (full) history. | |
271 | This includes the "shadow history" (almost all commands ever written). |
|
278 | This includes the "shadow history" (almost all commands ever written). | |
272 | Use '%hist -g' to show full shadow history (may be very long). |
|
279 | Use '%hist -g' to show full shadow history (may be very long). | |
273 | In shadow history, every index nuwber starts with 0. |
|
280 | In shadow history, every index nuwber starts with 0. | |
274 |
|
281 | |||
275 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
282 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
276 | the given file. The file is always overwritten, though IPython asks for |
|
283 | the given file. The file is always overwritten, though IPython asks for | |
277 | confirmation first if it already exists. |
|
284 | confirmation first if it already exists. | |
278 | """ |
|
285 | """ | |
279 |
|
286 | |||
280 | if not self.shell.displayhook.do_full_cache: |
|
287 | if not self.shell.displayhook.do_full_cache: | |
281 | print('This feature is only available if numbered prompts are in use.') |
|
288 | print('This feature is only available if numbered prompts are in use.') | |
282 | return |
|
289 | return | |
283 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') |
|
290 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') | |
284 |
|
291 | |||
285 | # Check if output to specific file was requested. |
|
292 | # Check if output to specific file was requested. | |
286 | try: |
|
293 | try: | |
287 | outfname = opts['f'] |
|
294 | outfname = opts['f'] | |
288 | except KeyError: |
|
295 | except KeyError: | |
289 | outfile = IPython.utils.io.Term.cout # default |
|
296 | outfile = IPython.utils.io.Term.cout # default | |
290 | # We don't want to close stdout at the end! |
|
297 | # We don't want to close stdout at the end! | |
291 | close_at_end = False |
|
298 | close_at_end = False | |
292 | else: |
|
299 | else: | |
293 | if os.path.exists(outfname): |
|
300 | if os.path.exists(outfname): | |
294 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
301 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
295 | print('Aborting.') |
|
302 | print('Aborting.') | |
296 | return |
|
303 | return | |
297 |
|
304 | |||
298 | outfile = open(outfname,'w') |
|
305 | outfile = open(outfname,'w') | |
299 | close_at_end = True |
|
306 | close_at_end = True | |
300 |
|
307 | |||
301 | if 't' in opts: |
|
308 | if 't' in opts: | |
302 | input_hist = self.shell.input_hist |
|
309 | input_hist = self.shell.history_manager.input_hist_parsed | |
303 | elif 'r' in opts: |
|
310 | elif 'r' in opts: | |
304 | input_hist = self.shell.input_hist_raw |
|
311 | input_hist = self.shell.history_manager.input_hist_raw | |
305 | else: |
|
312 | else: | |
306 | # Raw history is the default |
|
313 | # Raw history is the default | |
307 | input_hist = self.shell.input_hist_raw |
|
314 | input_hist = self.shell.history_manager.input_hist_raw | |
308 |
|
315 | |||
309 | default_length = 40 |
|
316 | default_length = 40 | |
310 | pattern = None |
|
317 | pattern = None | |
311 | if 'g' in opts: |
|
318 | if 'g' in opts: | |
312 | init = 1 |
|
319 | init = 1 | |
313 | final = len(input_hist) |
|
320 | final = len(input_hist) | |
314 | parts = parameter_s.split(None, 1) |
|
321 | parts = parameter_s.split(None, 1) | |
315 | if len(parts) == 1: |
|
322 | if len(parts) == 1: | |
316 | parts += '*' |
|
323 | parts += '*' | |
317 | head, pattern = parts |
|
324 | head, pattern = parts | |
318 | pattern = "*" + pattern + "*" |
|
325 | pattern = "*" + pattern + "*" | |
319 | elif len(args) == 0: |
|
326 | elif len(args) == 0: | |
320 | final = len(input_hist)-1 |
|
327 | final = len(input_hist)-1 | |
321 | init = max(1,final-default_length) |
|
328 | init = max(1,final-default_length) | |
322 | elif len(args) == 1: |
|
329 | elif len(args) == 1: | |
323 | final = len(input_hist) |
|
330 | final = len(input_hist) | |
324 | init = max(1, final-int(args[0])) |
|
331 | init = max(1, final-int(args[0])) | |
325 | elif len(args) == 2: |
|
332 | elif len(args) == 2: | |
326 | init, final = map(int, args) |
|
333 | init, final = map(int, args) | |
327 | else: |
|
334 | else: | |
328 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
335 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
329 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) |
|
336 | print(self.magic_hist.__doc__, file=IPython.utils.io.Term.cout) | |
330 | return |
|
337 | return | |
331 |
|
338 | |||
332 | width = len(str(final)) |
|
339 | width = len(str(final)) | |
333 | line_sep = ['','\n'] |
|
340 | line_sep = ['','\n'] | |
334 | print_nums = 'n' in opts |
|
341 | print_nums = 'n' in opts | |
335 | print_outputs = 'o' in opts |
|
342 | print_outputs = 'o' in opts | |
336 | pyprompts = 'p' in opts |
|
343 | pyprompts = 'p' in opts | |
337 |
|
344 | |||
338 | found = False |
|
345 | found = False | |
339 | if pattern is not None: |
|
346 | if pattern is not None: | |
340 | sh = self.shell.shadowhist.all() |
|
347 | sh = self.shell.history_manager.shadowhist.all() | |
341 | for idx, s in sh: |
|
348 | for idx, s in sh: | |
342 | if fnmatch.fnmatch(s, pattern): |
|
349 | if fnmatch.fnmatch(s, pattern): | |
343 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) |
|
350 | print("0%d: %s" %(idx, s.expandtabs(4)), file=outfile) | |
344 | found = True |
|
351 | found = True | |
345 |
|
352 | |||
346 | if found: |
|
353 | if found: | |
347 | print("===", file=outfile) |
|
354 | print("===", file=outfile) | |
348 | print("shadow history ends, fetch by %rep <number> (must start with 0)", |
|
355 | print("shadow history ends, fetch by %rep <number> (must start with 0)", | |
349 | file=outfile) |
|
356 | file=outfile) | |
350 | print("=== start of normal history ===", file=outfile) |
|
357 | print("=== start of normal history ===", file=outfile) | |
351 |
|
358 | |||
352 | for in_num in range(init, final): |
|
359 | for in_num in range(init, final): | |
353 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
360 | # Print user history with tabs expanded to 4 spaces. The GUI clients | |
354 | # use hard tabs for easier usability in auto-indented code, but we want |
|
361 | # use hard tabs for easier usability in auto-indented code, but we want | |
355 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
362 | # to produce PEP-8 compliant history for safe pasting into an editor. | |
356 | inline = input_hist[in_num].expandtabs(4) |
|
363 | inline = input_hist[in_num].expandtabs(4) | |
357 |
|
364 | |||
358 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
365 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
359 | continue |
|
366 | continue | |
360 |
|
367 | |||
361 | multiline = int(inline.count('\n') > 1) |
|
368 | multiline = int(inline.count('\n') > 1) | |
362 | if print_nums: |
|
369 | if print_nums: | |
363 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), |
|
370 | print('%s:%s' % (str(in_num).ljust(width), line_sep[multiline]), | |
364 | file=outfile) |
|
371 | file=outfile) | |
365 | if pyprompts: |
|
372 | if pyprompts: | |
366 | print('>>>', file=outfile) |
|
373 | print('>>>', file=outfile) | |
367 | if multiline: |
|
374 | if multiline: | |
368 | lines = inline.splitlines() |
|
375 | lines = inline.splitlines() | |
369 | print('\n... '.join(lines), file=outfile) |
|
376 | print('\n... '.join(lines), file=outfile) | |
370 | print('... ', file=outfile) |
|
377 | print('... ', file=outfile) | |
371 | else: |
|
378 | else: | |
372 | print(inline, end='', file=outfile) |
|
379 | print(inline, end='', file=outfile) | |
373 | else: |
|
380 | else: | |
374 | print(inline, end='', file=outfile) |
|
381 | print(inline, end='', file=outfile) | |
375 | if print_outputs: |
|
382 | if print_outputs: | |
376 | output = self.shell.output_hist.get(in_num) |
|
383 | output = self.shell.history_manager.output_hist.get(in_num) | |
377 | if output is not None: |
|
384 | if output is not None: | |
378 | print(repr(output), file=outfile) |
|
385 | print(repr(output), file=outfile) | |
379 |
|
386 | |||
380 | if close_at_end: |
|
387 | if close_at_end: | |
381 | outfile.close() |
|
388 | outfile.close() | |
382 |
|
389 | |||
383 |
|
390 | |||
384 | def magic_hist(self, parameter_s=''): |
|
391 | def magic_hist(self, parameter_s=''): | |
385 | """Alternate name for %history.""" |
|
392 | """Alternate name for %history.""" | |
386 | return self.magic_history(parameter_s) |
|
393 | return self.magic_history(parameter_s) | |
387 |
|
394 | |||
388 |
|
395 | |||
389 | def rep_f(self, arg): |
|
396 | def rep_f(self, arg): | |
390 | r""" Repeat a command, or get command to input line for editing |
|
397 | r""" Repeat a command, or get command to input line for editing | |
391 |
|
398 | |||
392 | - %rep (no arguments): |
|
399 | - %rep (no arguments): | |
393 |
|
400 | |||
394 | Place a string version of last computation result (stored in the special '_' |
|
401 | Place a string version of last computation result (stored in the special '_' | |
395 | variable) to the next input prompt. Allows you to create elaborate command |
|
402 | variable) to the next input prompt. Allows you to create elaborate command | |
396 | lines without using copy-paste:: |
|
403 | lines without using copy-paste:: | |
397 |
|
404 | |||
398 | $ l = ["hei", "vaan"] |
|
405 | $ l = ["hei", "vaan"] | |
399 | $ "".join(l) |
|
406 | $ "".join(l) | |
400 | ==> heivaan |
|
407 | ==> heivaan | |
401 | $ %rep |
|
408 | $ %rep | |
402 | $ heivaan_ <== cursor blinking |
|
409 | $ heivaan_ <== cursor blinking | |
403 |
|
410 | |||
404 | %rep 45 |
|
411 | %rep 45 | |
405 |
|
412 | |||
406 | Place history line 45 to next input prompt. Use %hist to find out the |
|
413 | Place history line 45 to next input prompt. Use %hist to find out the | |
407 | number. |
|
414 | number. | |
408 |
|
415 | |||
409 | %rep 1-4 6-7 3 |
|
416 | %rep 1-4 6-7 3 | |
410 |
|
417 | |||
411 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
418 | Repeat the specified lines immediately. Input slice syntax is the same as | |
412 | in %macro and %save. |
|
419 | in %macro and %save. | |
413 |
|
420 | |||
414 | %rep foo |
|
421 | %rep foo | |
415 |
|
422 | |||
416 | Place the most recent line that has the substring "foo" to next input. |
|
423 | Place the most recent line that has the substring "foo" to next input. | |
417 | (e.g. 'svn ci -m foobar'). |
|
424 | (e.g. 'svn ci -m foobar'). | |
418 | """ |
|
425 | """ | |
419 |
|
426 | |||
420 | opts,args = self.parse_options(arg,'',mode='list') |
|
427 | opts,args = self.parse_options(arg,'',mode='list') | |
421 | if not args: |
|
428 | if not args: | |
422 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
429 | self.set_next_input(str(self.shell.user_ns["_"])) | |
423 | return |
|
430 | return | |
424 |
|
431 | |||
425 | if len(args) == 1 and not '-' in args[0]: |
|
432 | if len(args) == 1 and not '-' in args[0]: | |
426 | arg = args[0] |
|
433 | arg = args[0] | |
427 | if len(arg) > 1 and arg.startswith('0'): |
|
434 | if len(arg) > 1 and arg.startswith('0'): | |
428 | # get from shadow hist |
|
435 | # get from shadow hist | |
429 | num = int(arg[1:]) |
|
436 | num = int(arg[1:]) | |
430 | line = self.shell.shadowhist.get(num) |
|
437 | line = self.shell.shadowhist.get(num) | |
431 | self.set_next_input(str(line)) |
|
438 | self.set_next_input(str(line)) | |
432 | return |
|
439 | return | |
433 | try: |
|
440 | try: | |
434 | num = int(args[0]) |
|
441 | num = int(args[0]) | |
435 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) |
|
442 | self.set_next_input(str(self.shell.input_hist_raw[num]).rstrip()) | |
436 | return |
|
443 | return | |
437 | except ValueError: |
|
444 | except ValueError: | |
438 | pass |
|
445 | pass | |
439 |
|
446 | |||
440 | for h in reversed(self.shell.input_hist_raw): |
|
447 | for h in reversed(self.shell.input_hist_raw): | |
441 | if 'rep' in h: |
|
448 | if 'rep' in h: | |
442 | continue |
|
449 | continue | |
443 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
450 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
444 | self.set_next_input(str(h).rstrip()) |
|
451 | self.set_next_input(str(h).rstrip()) | |
445 | return |
|
452 | return | |
446 |
|
453 | |||
447 | try: |
|
454 | try: | |
448 | lines = self.extract_input_slices(args, True) |
|
455 | lines = self.extract_input_slices(args, True) | |
449 | print("lines", lines) |
|
456 | print("lines", lines) | |
450 | self.run_cell(lines) |
|
457 | self.run_cell(lines) | |
451 | except ValueError: |
|
458 | except ValueError: | |
452 | print("Not found in recent history:", args) |
|
459 | print("Not found in recent history:", args) | |
453 |
|
460 | |||
454 |
|
461 | |||
455 | _sentinel = object() |
|
462 | _sentinel = object() | |
456 |
|
463 | |||
457 | class ShadowHist(object): |
|
464 | class ShadowHist(object): | |
458 | def __init__(self, db, shell): |
|
465 | def __init__(self, db, shell): | |
459 | # cmd => idx mapping |
|
466 | # cmd => idx mapping | |
460 | self.curidx = 0 |
|
467 | self.curidx = 0 | |
461 | self.db = db |
|
468 | self.db = db | |
462 | self.disabled = False |
|
469 | self.disabled = False | |
463 | self.shell = shell |
|
470 | self.shell = shell | |
464 |
|
471 | |||
465 | def inc_idx(self): |
|
472 | def inc_idx(self): | |
466 | idx = self.db.get('shadowhist_idx', 1) |
|
473 | idx = self.db.get('shadowhist_idx', 1) | |
467 | self.db['shadowhist_idx'] = idx + 1 |
|
474 | self.db['shadowhist_idx'] = idx + 1 | |
468 | return idx |
|
475 | return idx | |
469 |
|
476 | |||
470 | def add(self, ent): |
|
477 | def add(self, ent): | |
471 | if self.disabled: |
|
478 | if self.disabled: | |
472 | return |
|
479 | return | |
473 | try: |
|
480 | try: | |
474 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
481 | old = self.db.hget('shadowhist', ent, _sentinel) | |
475 | if old is not _sentinel: |
|
482 | if old is not _sentinel: | |
476 | return |
|
483 | return | |
477 | newidx = self.inc_idx() |
|
484 | newidx = self.inc_idx() | |
478 | #print("new", newidx) # dbg |
|
485 | #print("new", newidx) # dbg | |
479 | self.db.hset('shadowhist',ent, newidx) |
|
486 | self.db.hset('shadowhist',ent, newidx) | |
480 | except: |
|
487 | except: | |
481 | self.shell.showtraceback() |
|
488 | self.shell.showtraceback() | |
482 | print("WARNING: disabling shadow history") |
|
489 | print("WARNING: disabling shadow history") | |
483 | self.disabled = True |
|
490 | self.disabled = True | |
484 |
|
491 | |||
485 | def all(self): |
|
492 | def all(self): | |
486 | d = self.db.hdict('shadowhist') |
|
493 | d = self.db.hdict('shadowhist') | |
487 | items = [(i,s) for (s,i) in d.iteritems()] |
|
494 | items = [(i,s) for (s,i) in d.iteritems()] | |
488 | items.sort() |
|
495 | items.sort() | |
489 | return items |
|
496 | return items | |
490 |
|
497 | |||
491 | def get(self, idx): |
|
498 | def get(self, idx): | |
492 | all = self.all() |
|
499 | all = self.all() | |
493 |
|
500 | |||
494 | for k, v in all: |
|
501 | for k, v in all: | |
495 | if k == idx: |
|
502 | if k == idx: | |
496 | return v |
|
503 | return v | |
497 |
|
504 | |||
498 |
|
505 | |||
499 | def init_ipython(ip): |
|
506 | def init_ipython(ip): | |
500 | ip.define_magic("rep",rep_f) |
|
507 | ip.define_magic("rep",rep_f) | |
501 | ip.define_magic("hist",magic_hist) |
|
508 | ip.define_magic("hist",magic_hist) | |
502 | ip.define_magic("history",magic_history) |
|
509 | ip.define_magic("history",magic_history) | |
503 |
|
510 | |||
504 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
511 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
505 | #import ipy_completers |
|
512 | #import ipy_completers | |
506 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
513 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,2538 +1,2539 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import sys |
|
27 | import sys | |
28 | import tempfile |
|
28 | import tempfile | |
29 | import types |
|
29 | import types | |
30 | from contextlib import nested |
|
30 | from contextlib import nested | |
31 |
|
31 | |||
32 | from IPython.config.configurable import Configurable |
|
32 | from IPython.config.configurable import Configurable | |
33 | from IPython.core import debugger, oinspect |
|
33 | from IPython.core import debugger, oinspect | |
34 | from IPython.core import history as ipcorehist |
|
34 | from IPython.core import history as ipcorehist | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import shadowns |
|
37 | from IPython.core import shadowns | |
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core.alias import AliasManager |
|
39 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.compilerop import CachingCompiler |
|
41 | from IPython.core.compilerop import CachingCompiler | |
42 | from IPython.core.display_trap import DisplayTrap |
|
42 | from IPython.core.display_trap import DisplayTrap | |
43 | from IPython.core.displayhook import DisplayHook |
|
43 | from IPython.core.displayhook import DisplayHook | |
44 | from IPython.core.error import TryNext, UsageError |
|
44 | from IPython.core.error import TryNext, UsageError | |
45 | from IPython.core.extensions import ExtensionManager |
|
45 | from IPython.core.extensions import ExtensionManager | |
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
47 | from IPython.core.history import HistoryManager |
|
47 | from IPython.core.history import HistoryManager | |
48 | from IPython.core.inputlist import InputList |
|
|||
49 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
48 | from IPython.core.inputsplitter import IPythonInputSplitter | |
50 | from IPython.core.logger import Logger |
|
49 | from IPython.core.logger import Logger | |
51 | from IPython.core.magic import Magic |
|
50 | from IPython.core.magic import Magic | |
52 | from IPython.core.payload import PayloadManager |
|
51 | from IPython.core.payload import PayloadManager | |
53 | from IPython.core.plugin import PluginManager |
|
52 | from IPython.core.plugin import PluginManager | |
54 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
53 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
55 | from IPython.external.Itpl import ItplNS |
|
54 | from IPython.external.Itpl import ItplNS | |
56 | from IPython.utils import PyColorize |
|
55 | from IPython.utils import PyColorize | |
57 | from IPython.utils import io |
|
56 | from IPython.utils import io | |
58 | from IPython.utils import pickleshare |
|
57 | from IPython.utils import pickleshare | |
59 | from IPython.utils.doctestreload import doctest_reload |
|
58 | from IPython.utils.doctestreload import doctest_reload | |
60 | from IPython.utils.io import ask_yes_no, rprint |
|
59 | from IPython.utils.io import ask_yes_no, rprint | |
61 | from IPython.utils.ipstruct import Struct |
|
60 | from IPython.utils.ipstruct import Struct | |
62 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
61 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
63 | from IPython.utils.process import system, getoutput |
|
62 | from IPython.utils.process import system, getoutput | |
64 | from IPython.utils.strdispatch import StrDispatch |
|
63 | from IPython.utils.strdispatch import StrDispatch | |
65 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
64 | from IPython.utils.syspathcontext import prepended_to_syspath | |
66 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
65 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
67 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
66 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
68 | List, Unicode, Instance, Type) |
|
67 | List, Unicode, Instance, Type) | |
69 | from IPython.utils.warn import warn, error, fatal |
|
68 | from IPython.utils.warn import warn, error, fatal | |
70 | import IPython.core.hooks |
|
69 | import IPython.core.hooks | |
71 |
|
70 | |||
72 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
73 | # Globals |
|
72 | # Globals | |
74 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
75 |
|
74 | |||
76 | # compiled regexps for autoindent management |
|
75 | # compiled regexps for autoindent management | |
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
76 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
78 |
|
77 | |||
79 | #----------------------------------------------------------------------------- |
|
78 | #----------------------------------------------------------------------------- | |
80 | # Utilities |
|
79 | # Utilities | |
81 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
82 |
|
81 | |||
83 | # store the builtin raw_input globally, and use this always, in case user code |
|
82 | # store the builtin raw_input globally, and use this always, in case user code | |
84 | # overwrites it (like wx.py.PyShell does) |
|
83 | # overwrites it (like wx.py.PyShell does) | |
85 | raw_input_original = raw_input |
|
84 | raw_input_original = raw_input | |
86 |
|
85 | |||
87 | def softspace(file, newvalue): |
|
86 | def softspace(file, newvalue): | |
88 | """Copied from code.py, to remove the dependency""" |
|
87 | """Copied from code.py, to remove the dependency""" | |
89 |
|
88 | |||
90 | oldvalue = 0 |
|
89 | oldvalue = 0 | |
91 | try: |
|
90 | try: | |
92 | oldvalue = file.softspace |
|
91 | oldvalue = file.softspace | |
93 | except AttributeError: |
|
92 | except AttributeError: | |
94 | pass |
|
93 | pass | |
95 | try: |
|
94 | try: | |
96 | file.softspace = newvalue |
|
95 | file.softspace = newvalue | |
97 | except (AttributeError, TypeError): |
|
96 | except (AttributeError, TypeError): | |
98 | # "attribute-less object" or "read-only attributes" |
|
97 | # "attribute-less object" or "read-only attributes" | |
99 | pass |
|
98 | pass | |
100 | return oldvalue |
|
99 | return oldvalue | |
101 |
|
100 | |||
102 |
|
101 | |||
103 | def no_op(*a, **kw): pass |
|
102 | def no_op(*a, **kw): pass | |
104 |
|
103 | |||
105 | class SpaceInInput(Exception): pass |
|
104 | class SpaceInInput(Exception): pass | |
106 |
|
105 | |||
107 | class Bunch: pass |
|
106 | class Bunch: pass | |
108 |
|
107 | |||
109 |
|
108 | |||
110 | def get_default_colors(): |
|
109 | def get_default_colors(): | |
111 | if sys.platform=='darwin': |
|
110 | if sys.platform=='darwin': | |
112 | return "LightBG" |
|
111 | return "LightBG" | |
113 | elif os.name=='nt': |
|
112 | elif os.name=='nt': | |
114 | return 'Linux' |
|
113 | return 'Linux' | |
115 | else: |
|
114 | else: | |
116 | return 'Linux' |
|
115 | return 'Linux' | |
117 |
|
116 | |||
118 |
|
117 | |||
119 | class SeparateStr(Str): |
|
118 | class SeparateStr(Str): | |
120 | """A Str subclass to validate separate_in, separate_out, etc. |
|
119 | """A Str subclass to validate separate_in, separate_out, etc. | |
121 |
|
120 | |||
122 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
121 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
123 | """ |
|
122 | """ | |
124 |
|
123 | |||
125 | def validate(self, obj, value): |
|
124 | def validate(self, obj, value): | |
126 | if value == '0': value = '' |
|
125 | if value == '0': value = '' | |
127 | value = value.replace('\\n','\n') |
|
126 | value = value.replace('\\n','\n') | |
128 | return super(SeparateStr, self).validate(obj, value) |
|
127 | return super(SeparateStr, self).validate(obj, value) | |
129 |
|
128 | |||
130 | class MultipleInstanceError(Exception): |
|
129 | class MultipleInstanceError(Exception): | |
131 | pass |
|
130 | pass | |
132 |
|
131 | |||
133 |
|
132 | |||
134 | #----------------------------------------------------------------------------- |
|
133 | #----------------------------------------------------------------------------- | |
135 | # Main IPython class |
|
134 | # Main IPython class | |
136 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
137 |
|
136 | |||
138 | class InteractiveShell(Configurable, Magic): |
|
137 | class InteractiveShell(Configurable, Magic): | |
139 | """An enhanced, interactive shell for Python.""" |
|
138 | """An enhanced, interactive shell for Python.""" | |
140 |
|
139 | |||
141 | _instance = None |
|
140 | _instance = None | |
142 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
141 | autocall = Enum((0,1,2), default_value=1, config=True) | |
143 | # TODO: remove all autoindent logic and put into frontends. |
|
142 | # TODO: remove all autoindent logic and put into frontends. | |
144 | # We can't do this yet because even runlines uses the autoindent. |
|
143 | # We can't do this yet because even runlines uses the autoindent. | |
145 | autoindent = CBool(True, config=True) |
|
144 | autoindent = CBool(True, config=True) | |
146 | automagic = CBool(True, config=True) |
|
145 | automagic = CBool(True, config=True) | |
147 | cache_size = Int(1000, config=True) |
|
146 | cache_size = Int(1000, config=True) | |
148 | color_info = CBool(True, config=True) |
|
147 | color_info = CBool(True, config=True) | |
149 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
148 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
150 | default_value=get_default_colors(), config=True) |
|
149 | default_value=get_default_colors(), config=True) | |
151 | debug = CBool(False, config=True) |
|
150 | debug = CBool(False, config=True) | |
152 | deep_reload = CBool(False, config=True) |
|
151 | deep_reload = CBool(False, config=True) | |
153 | displayhook_class = Type(DisplayHook) |
|
152 | displayhook_class = Type(DisplayHook) | |
154 | exit_now = CBool(False) |
|
153 | exit_now = CBool(False) | |
155 | # Monotonically increasing execution counter |
|
154 | # Monotonically increasing execution counter | |
156 | execution_count = Int(1) |
|
155 | execution_count = Int(1) | |
157 | filename = Str("<ipython console>") |
|
156 | filename = Str("<ipython console>") | |
158 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
159 |
|
158 | |||
160 | # Input splitter, to split entire cells of input into either individual |
|
159 | # Input splitter, to split entire cells of input into either individual | |
161 | # interactive statements or whole blocks. |
|
160 | # interactive statements or whole blocks. | |
162 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
161 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
163 | (), {}) |
|
162 | (), {}) | |
164 | logstart = CBool(False, config=True) |
|
163 | logstart = CBool(False, config=True) | |
165 | logfile = Str('', config=True) |
|
164 | logfile = Str('', config=True) | |
166 | logappend = Str('', config=True) |
|
165 | logappend = Str('', config=True) | |
167 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
166 | object_info_string_level = Enum((0,1,2), default_value=0, | |
168 | config=True) |
|
167 | config=True) | |
169 | pdb = CBool(False, config=True) |
|
168 | pdb = CBool(False, config=True) | |
170 |
|
169 | |||
171 | pprint = CBool(True, config=True) |
|
170 | pprint = CBool(True, config=True) | |
172 | profile = Str('', config=True) |
|
171 | profile = Str('', config=True) | |
173 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
172 | prompt_in1 = Str('In [\\#]: ', config=True) | |
174 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
173 | prompt_in2 = Str(' .\\D.: ', config=True) | |
175 | prompt_out = Str('Out[\\#]: ', config=True) |
|
174 | prompt_out = Str('Out[\\#]: ', config=True) | |
176 | prompts_pad_left = CBool(True, config=True) |
|
175 | prompts_pad_left = CBool(True, config=True) | |
177 | quiet = CBool(False, config=True) |
|
176 | quiet = CBool(False, config=True) | |
178 |
|
177 | |||
|
178 | history_length = Int(10000, config=True) | |||
|
179 | ||||
179 | # The readline stuff will eventually be moved to the terminal subclass |
|
180 | # The readline stuff will eventually be moved to the terminal subclass | |
180 | # but for now, we can't do that as readline is welded in everywhere. |
|
181 | # but for now, we can't do that as readline is welded in everywhere. | |
181 | readline_use = CBool(True, config=True) |
|
182 | readline_use = CBool(True, config=True) | |
182 | readline_merge_completions = CBool(True, config=True) |
|
183 | readline_merge_completions = CBool(True, config=True) | |
183 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
184 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) | |
184 | readline_remove_delims = Str('-/~', config=True) |
|
185 | readline_remove_delims = Str('-/~', config=True) | |
185 | readline_parse_and_bind = List([ |
|
186 | readline_parse_and_bind = List([ | |
186 | 'tab: complete', |
|
187 | 'tab: complete', | |
187 | '"\C-l": clear-screen', |
|
188 | '"\C-l": clear-screen', | |
188 | 'set show-all-if-ambiguous on', |
|
189 | 'set show-all-if-ambiguous on', | |
189 | '"\C-o": tab-insert', |
|
190 | '"\C-o": tab-insert', | |
190 | '"\M-i": " "', |
|
191 | '"\M-i": " "', | |
191 | '"\M-o": "\d\d\d\d"', |
|
192 | '"\M-o": "\d\d\d\d"', | |
192 | '"\M-I": "\d\d\d\d"', |
|
193 | '"\M-I": "\d\d\d\d"', | |
193 | '"\C-r": reverse-search-history', |
|
194 | '"\C-r": reverse-search-history', | |
194 | '"\C-s": forward-search-history', |
|
195 | '"\C-s": forward-search-history', | |
195 | '"\C-p": history-search-backward', |
|
196 | '"\C-p": history-search-backward', | |
196 | '"\C-n": history-search-forward', |
|
197 | '"\C-n": history-search-forward', | |
197 | '"\e[A": history-search-backward', |
|
198 | '"\e[A": history-search-backward', | |
198 | '"\e[B": history-search-forward', |
|
199 | '"\e[B": history-search-forward', | |
199 | '"\C-k": kill-line', |
|
200 | '"\C-k": kill-line', | |
200 | '"\C-u": unix-line-discard', |
|
201 | '"\C-u": unix-line-discard', | |
201 | ], allow_none=False, config=True) |
|
202 | ], allow_none=False, config=True) | |
202 |
|
203 | |||
203 | # TODO: this part of prompt management should be moved to the frontends. |
|
204 | # TODO: this part of prompt management should be moved to the frontends. | |
204 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
205 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
205 | separate_in = SeparateStr('\n', config=True) |
|
206 | separate_in = SeparateStr('\n', config=True) | |
206 | separate_out = SeparateStr('', config=True) |
|
207 | separate_out = SeparateStr('', config=True) | |
207 | separate_out2 = SeparateStr('', config=True) |
|
208 | separate_out2 = SeparateStr('', config=True) | |
208 | wildcards_case_sensitive = CBool(True, config=True) |
|
209 | wildcards_case_sensitive = CBool(True, config=True) | |
209 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
210 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
210 | default_value='Context', config=True) |
|
211 | default_value='Context', config=True) | |
211 |
|
212 | |||
212 | # Subcomponents of InteractiveShell |
|
213 | # Subcomponents of InteractiveShell | |
213 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
214 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
214 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
215 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
215 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
216 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
216 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
217 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
217 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
218 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
218 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
219 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
219 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
220 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
220 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
221 | history_manager = Instance('IPython.core.history.HistoryManager') | |
221 |
|
222 | |||
222 | # Private interface |
|
223 | # Private interface | |
223 | _post_execute = set() |
|
224 | _post_execute = set() | |
224 |
|
225 | |||
225 | def __init__(self, config=None, ipython_dir=None, |
|
226 | def __init__(self, config=None, ipython_dir=None, | |
226 | user_ns=None, user_global_ns=None, |
|
227 | user_ns=None, user_global_ns=None, | |
227 | custom_exceptions=((), None)): |
|
228 | custom_exceptions=((), None)): | |
228 |
|
229 | |||
229 | # This is where traits with a config_key argument are updated |
|
230 | # This is where traits with a config_key argument are updated | |
230 | # from the values on config. |
|
231 | # from the values on config. | |
231 | super(InteractiveShell, self).__init__(config=config) |
|
232 | super(InteractiveShell, self).__init__(config=config) | |
232 |
|
233 | |||
233 | # These are relatively independent and stateless |
|
234 | # These are relatively independent and stateless | |
234 | self.init_ipython_dir(ipython_dir) |
|
235 | self.init_ipython_dir(ipython_dir) | |
235 | self.init_instance_attrs() |
|
236 | self.init_instance_attrs() | |
236 | self.init_environment() |
|
237 | self.init_environment() | |
237 |
|
238 | |||
238 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
239 | # Create namespaces (user_ns, user_global_ns, etc.) | |
239 | self.init_create_namespaces(user_ns, user_global_ns) |
|
240 | self.init_create_namespaces(user_ns, user_global_ns) | |
240 | # This has to be done after init_create_namespaces because it uses |
|
241 | # This has to be done after init_create_namespaces because it uses | |
241 | # something in self.user_ns, but before init_sys_modules, which |
|
242 | # something in self.user_ns, but before init_sys_modules, which | |
242 | # is the first thing to modify sys. |
|
243 | # is the first thing to modify sys. | |
243 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
244 | # TODO: When we override sys.stdout and sys.stderr before this class | |
244 | # is created, we are saving the overridden ones here. Not sure if this |
|
245 | # is created, we are saving the overridden ones here. Not sure if this | |
245 | # is what we want to do. |
|
246 | # is what we want to do. | |
246 | self.save_sys_module_state() |
|
247 | self.save_sys_module_state() | |
247 | self.init_sys_modules() |
|
248 | self.init_sys_modules() | |
248 |
|
249 | |||
249 | self.init_history() |
|
250 | self.init_history() | |
250 | self.init_encoding() |
|
251 | self.init_encoding() | |
251 | self.init_prefilter() |
|
252 | self.init_prefilter() | |
252 |
|
253 | |||
253 | Magic.__init__(self, self) |
|
254 | Magic.__init__(self, self) | |
254 |
|
255 | |||
255 | self.init_syntax_highlighting() |
|
256 | self.init_syntax_highlighting() | |
256 | self.init_hooks() |
|
257 | self.init_hooks() | |
257 | self.init_pushd_popd_magic() |
|
258 | self.init_pushd_popd_magic() | |
258 | # self.init_traceback_handlers use to be here, but we moved it below |
|
259 | # self.init_traceback_handlers use to be here, but we moved it below | |
259 | # because it and init_io have to come after init_readline. |
|
260 | # because it and init_io have to come after init_readline. | |
260 | self.init_user_ns() |
|
261 | self.init_user_ns() | |
261 | self.init_logger() |
|
262 | self.init_logger() | |
262 | self.init_alias() |
|
263 | self.init_alias() | |
263 | self.init_builtins() |
|
264 | self.init_builtins() | |
264 |
|
265 | |||
265 | # pre_config_initialization |
|
266 | # pre_config_initialization | |
266 |
|
267 | |||
267 | # The next section should contain everything that was in ipmaker. |
|
268 | # The next section should contain everything that was in ipmaker. | |
268 | self.init_logstart() |
|
269 | self.init_logstart() | |
269 |
|
270 | |||
270 | # The following was in post_config_initialization |
|
271 | # The following was in post_config_initialization | |
271 | self.init_inspector() |
|
272 | self.init_inspector() | |
272 | # init_readline() must come before init_io(), because init_io uses |
|
273 | # init_readline() must come before init_io(), because init_io uses | |
273 | # readline related things. |
|
274 | # readline related things. | |
274 | self.init_readline() |
|
275 | self.init_readline() | |
275 | # init_completer must come after init_readline, because it needs to |
|
276 | # init_completer must come after init_readline, because it needs to | |
276 | # know whether readline is present or not system-wide to configure the |
|
277 | # know whether readline is present or not system-wide to configure the | |
277 | # completers, since the completion machinery can now operate |
|
278 | # completers, since the completion machinery can now operate | |
278 | # independently of readline (e.g. over the network) |
|
279 | # independently of readline (e.g. over the network) | |
279 | self.init_completer() |
|
280 | self.init_completer() | |
280 | # TODO: init_io() needs to happen before init_traceback handlers |
|
281 | # TODO: init_io() needs to happen before init_traceback handlers | |
281 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
282 | # because the traceback handlers hardcode the stdout/stderr streams. | |
282 | # This logic in in debugger.Pdb and should eventually be changed. |
|
283 | # This logic in in debugger.Pdb and should eventually be changed. | |
283 | self.init_io() |
|
284 | self.init_io() | |
284 | self.init_traceback_handlers(custom_exceptions) |
|
285 | self.init_traceback_handlers(custom_exceptions) | |
285 | self.init_prompts() |
|
286 | self.init_prompts() | |
286 | self.init_displayhook() |
|
287 | self.init_displayhook() | |
287 | self.init_reload_doctest() |
|
288 | self.init_reload_doctest() | |
288 | self.init_magics() |
|
289 | self.init_magics() | |
289 | self.init_pdb() |
|
290 | self.init_pdb() | |
290 | self.init_extension_manager() |
|
291 | self.init_extension_manager() | |
291 | self.init_plugin_manager() |
|
292 | self.init_plugin_manager() | |
292 | self.init_payload() |
|
293 | self.init_payload() | |
293 | self.hooks.late_startup_hook() |
|
294 | self.hooks.late_startup_hook() | |
294 | atexit.register(self.atexit_operations) |
|
295 | atexit.register(self.atexit_operations) | |
295 |
|
296 | |||
|
297 | # While we're trying to have each part of the code directly access what it | |||
|
298 | # needs without keeping redundant references to objects, we have too much | |||
|
299 | # legacy code that expects ip.db to exist, so let's make it a property that | |||
|
300 | # retrieves the underlying object from our new history manager. | |||
|
301 | @property | |||
|
302 | def db(self): | |||
|
303 | return self.history_manager.shadow_db | |||
|
304 | ||||
296 | @classmethod |
|
305 | @classmethod | |
297 | def instance(cls, *args, **kwargs): |
|
306 | def instance(cls, *args, **kwargs): | |
298 | """Returns a global InteractiveShell instance.""" |
|
307 | """Returns a global InteractiveShell instance.""" | |
299 | if cls._instance is None: |
|
308 | if cls._instance is None: | |
300 | inst = cls(*args, **kwargs) |
|
309 | inst = cls(*args, **kwargs) | |
301 | # Now make sure that the instance will also be returned by |
|
310 | # Now make sure that the instance will also be returned by | |
302 | # the subclasses instance attribute. |
|
311 | # the subclasses instance attribute. | |
303 | for subclass in cls.mro(): |
|
312 | for subclass in cls.mro(): | |
304 | if issubclass(cls, subclass) and \ |
|
313 | if issubclass(cls, subclass) and \ | |
305 | issubclass(subclass, InteractiveShell): |
|
314 | issubclass(subclass, InteractiveShell): | |
306 | subclass._instance = inst |
|
315 | subclass._instance = inst | |
307 | else: |
|
316 | else: | |
308 | break |
|
317 | break | |
309 | if isinstance(cls._instance, cls): |
|
318 | if isinstance(cls._instance, cls): | |
310 | return cls._instance |
|
319 | return cls._instance | |
311 | else: |
|
320 | else: | |
312 | raise MultipleInstanceError( |
|
321 | raise MultipleInstanceError( | |
313 | 'Multiple incompatible subclass instances of ' |
|
322 | 'Multiple incompatible subclass instances of ' | |
314 | 'InteractiveShell are being created.' |
|
323 | 'InteractiveShell are being created.' | |
315 | ) |
|
324 | ) | |
316 |
|
325 | |||
317 | @classmethod |
|
326 | @classmethod | |
318 | def initialized(cls): |
|
327 | def initialized(cls): | |
319 | return hasattr(cls, "_instance") |
|
328 | return hasattr(cls, "_instance") | |
320 |
|
329 | |||
321 | def get_ipython(self): |
|
330 | def get_ipython(self): | |
322 | """Return the currently running IPython instance.""" |
|
331 | """Return the currently running IPython instance.""" | |
323 | return self |
|
332 | return self | |
324 |
|
333 | |||
325 | #------------------------------------------------------------------------- |
|
334 | #------------------------------------------------------------------------- | |
326 | # Trait changed handlers |
|
335 | # Trait changed handlers | |
327 | #------------------------------------------------------------------------- |
|
336 | #------------------------------------------------------------------------- | |
328 |
|
337 | |||
329 | def _ipython_dir_changed(self, name, new): |
|
338 | def _ipython_dir_changed(self, name, new): | |
330 | if not os.path.isdir(new): |
|
339 | if not os.path.isdir(new): | |
331 | os.makedirs(new, mode = 0777) |
|
340 | os.makedirs(new, mode = 0777) | |
332 |
|
341 | |||
333 | def set_autoindent(self,value=None): |
|
342 | def set_autoindent(self,value=None): | |
334 | """Set the autoindent flag, checking for readline support. |
|
343 | """Set the autoindent flag, checking for readline support. | |
335 |
|
344 | |||
336 | If called with no arguments, it acts as a toggle.""" |
|
345 | If called with no arguments, it acts as a toggle.""" | |
337 |
|
346 | |||
338 | if not self.has_readline: |
|
347 | if not self.has_readline: | |
339 | if os.name == 'posix': |
|
348 | if os.name == 'posix': | |
340 | warn("The auto-indent feature requires the readline library") |
|
349 | warn("The auto-indent feature requires the readline library") | |
341 | self.autoindent = 0 |
|
350 | self.autoindent = 0 | |
342 | return |
|
351 | return | |
343 | if value is None: |
|
352 | if value is None: | |
344 | self.autoindent = not self.autoindent |
|
353 | self.autoindent = not self.autoindent | |
345 | else: |
|
354 | else: | |
346 | self.autoindent = value |
|
355 | self.autoindent = value | |
347 |
|
356 | |||
348 | #------------------------------------------------------------------------- |
|
357 | #------------------------------------------------------------------------- | |
349 | # init_* methods called by __init__ |
|
358 | # init_* methods called by __init__ | |
350 | #------------------------------------------------------------------------- |
|
359 | #------------------------------------------------------------------------- | |
351 |
|
360 | |||
352 | def init_ipython_dir(self, ipython_dir): |
|
361 | def init_ipython_dir(self, ipython_dir): | |
353 | if ipython_dir is not None: |
|
362 | if ipython_dir is not None: | |
354 | self.ipython_dir = ipython_dir |
|
363 | self.ipython_dir = ipython_dir | |
355 | self.config.Global.ipython_dir = self.ipython_dir |
|
364 | self.config.Global.ipython_dir = self.ipython_dir | |
356 | return |
|
365 | return | |
357 |
|
366 | |||
358 | if hasattr(self.config.Global, 'ipython_dir'): |
|
367 | if hasattr(self.config.Global, 'ipython_dir'): | |
359 | self.ipython_dir = self.config.Global.ipython_dir |
|
368 | self.ipython_dir = self.config.Global.ipython_dir | |
360 | else: |
|
369 | else: | |
361 | self.ipython_dir = get_ipython_dir() |
|
370 | self.ipython_dir = get_ipython_dir() | |
362 |
|
371 | |||
363 | # All children can just read this |
|
372 | # All children can just read this | |
364 | self.config.Global.ipython_dir = self.ipython_dir |
|
373 | self.config.Global.ipython_dir = self.ipython_dir | |
365 |
|
374 | |||
366 | def init_instance_attrs(self): |
|
375 | def init_instance_attrs(self): | |
367 | self.more = False |
|
376 | self.more = False | |
368 |
|
377 | |||
369 | # command compiler |
|
378 | # command compiler | |
370 | self.compile = CachingCompiler() |
|
379 | self.compile = CachingCompiler() | |
371 |
|
380 | |||
372 | # User input buffers |
|
381 | # User input buffers | |
373 | # NOTE: these variables are slated for full removal, once we are 100% |
|
382 | # NOTE: these variables are slated for full removal, once we are 100% | |
374 | # sure that the new execution logic is solid. We will delte runlines, |
|
383 | # sure that the new execution logic is solid. We will delte runlines, | |
375 | # push_line and these buffers, as all input will be managed by the |
|
384 | # push_line and these buffers, as all input will be managed by the | |
376 | # frontends via an inputsplitter instance. |
|
385 | # frontends via an inputsplitter instance. | |
377 | self.buffer = [] |
|
386 | self.buffer = [] | |
378 | self.buffer_raw = [] |
|
387 | self.buffer_raw = [] | |
379 |
|
388 | |||
380 | # Make an empty namespace, which extension writers can rely on both |
|
389 | # Make an empty namespace, which extension writers can rely on both | |
381 | # existing and NEVER being used by ipython itself. This gives them a |
|
390 | # existing and NEVER being used by ipython itself. This gives them a | |
382 | # convenient location for storing additional information and state |
|
391 | # convenient location for storing additional information and state | |
383 | # their extensions may require, without fear of collisions with other |
|
392 | # their extensions may require, without fear of collisions with other | |
384 | # ipython names that may develop later. |
|
393 | # ipython names that may develop later. | |
385 | self.meta = Struct() |
|
394 | self.meta = Struct() | |
386 |
|
395 | |||
387 | # Object variable to store code object waiting execution. This is |
|
396 | # Object variable to store code object waiting execution. This is | |
388 | # used mainly by the multithreaded shells, but it can come in handy in |
|
397 | # used mainly by the multithreaded shells, but it can come in handy in | |
389 | # other situations. No need to use a Queue here, since it's a single |
|
398 | # other situations. No need to use a Queue here, since it's a single | |
390 | # item which gets cleared once run. |
|
399 | # item which gets cleared once run. | |
391 | self.code_to_run = None |
|
400 | self.code_to_run = None | |
392 |
|
401 | |||
393 | # Temporary files used for various purposes. Deleted at exit. |
|
402 | # Temporary files used for various purposes. Deleted at exit. | |
394 | self.tempfiles = [] |
|
403 | self.tempfiles = [] | |
395 |
|
404 | |||
396 | # Keep track of readline usage (later set by init_readline) |
|
405 | # Keep track of readline usage (later set by init_readline) | |
397 | self.has_readline = False |
|
406 | self.has_readline = False | |
398 |
|
407 | |||
399 | # keep track of where we started running (mainly for crash post-mortem) |
|
408 | # keep track of where we started running (mainly for crash post-mortem) | |
400 | # This is not being used anywhere currently. |
|
409 | # This is not being used anywhere currently. | |
401 | self.starting_dir = os.getcwd() |
|
410 | self.starting_dir = os.getcwd() | |
402 |
|
411 | |||
403 | # Indentation management |
|
412 | # Indentation management | |
404 | self.indent_current_nsp = 0 |
|
413 | self.indent_current_nsp = 0 | |
405 |
|
414 | |||
406 | def init_environment(self): |
|
415 | def init_environment(self): | |
407 | """Any changes we need to make to the user's environment.""" |
|
416 | """Any changes we need to make to the user's environment.""" | |
408 | pass |
|
417 | pass | |
409 |
|
418 | |||
410 | def init_encoding(self): |
|
419 | def init_encoding(self): | |
411 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
420 | # Get system encoding at startup time. Certain terminals (like Emacs | |
412 | # under Win32 have it set to None, and we need to have a known valid |
|
421 | # under Win32 have it set to None, and we need to have a known valid | |
413 | # encoding to use in the raw_input() method |
|
422 | # encoding to use in the raw_input() method | |
414 | try: |
|
423 | try: | |
415 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
424 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
416 | except AttributeError: |
|
425 | except AttributeError: | |
417 | self.stdin_encoding = 'ascii' |
|
426 | self.stdin_encoding = 'ascii' | |
418 |
|
427 | |||
419 | def init_syntax_highlighting(self): |
|
428 | def init_syntax_highlighting(self): | |
420 | # Python source parser/formatter for syntax highlighting |
|
429 | # Python source parser/formatter for syntax highlighting | |
421 | pyformat = PyColorize.Parser().format |
|
430 | pyformat = PyColorize.Parser().format | |
422 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
431 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
423 |
|
432 | |||
424 | def init_pushd_popd_magic(self): |
|
433 | def init_pushd_popd_magic(self): | |
425 | # for pushd/popd management |
|
434 | # for pushd/popd management | |
426 | try: |
|
435 | try: | |
427 | self.home_dir = get_home_dir() |
|
436 | self.home_dir = get_home_dir() | |
428 | except HomeDirError, msg: |
|
437 | except HomeDirError, msg: | |
429 | fatal(msg) |
|
438 | fatal(msg) | |
430 |
|
439 | |||
431 | self.dir_stack = [] |
|
440 | self.dir_stack = [] | |
432 |
|
441 | |||
433 | def init_logger(self): |
|
442 | def init_logger(self): | |
434 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
443 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
435 | logmode='rotate') |
|
444 | logmode='rotate') | |
436 |
|
445 | |||
437 | def init_logstart(self): |
|
446 | def init_logstart(self): | |
438 | """Initialize logging in case it was requested at the command line. |
|
447 | """Initialize logging in case it was requested at the command line. | |
439 | """ |
|
448 | """ | |
440 | if self.logappend: |
|
449 | if self.logappend: | |
441 | self.magic_logstart(self.logappend + ' append') |
|
450 | self.magic_logstart(self.logappend + ' append') | |
442 | elif self.logfile: |
|
451 | elif self.logfile: | |
443 | self.magic_logstart(self.logfile) |
|
452 | self.magic_logstart(self.logfile) | |
444 | elif self.logstart: |
|
453 | elif self.logstart: | |
445 | self.magic_logstart() |
|
454 | self.magic_logstart() | |
446 |
|
455 | |||
447 | def init_builtins(self): |
|
456 | def init_builtins(self): | |
448 | self.builtin_trap = BuiltinTrap(shell=self) |
|
457 | self.builtin_trap = BuiltinTrap(shell=self) | |
449 |
|
458 | |||
450 | def init_inspector(self): |
|
459 | def init_inspector(self): | |
451 | # Object inspector |
|
460 | # Object inspector | |
452 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
461 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
453 | PyColorize.ANSICodeColors, |
|
462 | PyColorize.ANSICodeColors, | |
454 | 'NoColor', |
|
463 | 'NoColor', | |
455 | self.object_info_string_level) |
|
464 | self.object_info_string_level) | |
456 |
|
465 | |||
457 | def init_io(self): |
|
466 | def init_io(self): | |
458 | # This will just use sys.stdout and sys.stderr. If you want to |
|
467 | # This will just use sys.stdout and sys.stderr. If you want to | |
459 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
468 | # override sys.stdout and sys.stderr themselves, you need to do that | |
460 | # *before* instantiating this class, because Term holds onto |
|
469 | # *before* instantiating this class, because Term holds onto | |
461 | # references to the underlying streams. |
|
470 | # references to the underlying streams. | |
462 | if sys.platform == 'win32' and self.has_readline: |
|
471 | if sys.platform == 'win32' and self.has_readline: | |
463 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
472 | Term = io.IOTerm(cout=self.readline._outputfile, | |
464 | cerr=self.readline._outputfile) |
|
473 | cerr=self.readline._outputfile) | |
465 | else: |
|
474 | else: | |
466 | Term = io.IOTerm() |
|
475 | Term = io.IOTerm() | |
467 | io.Term = Term |
|
476 | io.Term = Term | |
468 |
|
477 | |||
469 | def init_prompts(self): |
|
478 | def init_prompts(self): | |
470 | # TODO: This is a pass for now because the prompts are managed inside |
|
479 | # TODO: This is a pass for now because the prompts are managed inside | |
471 | # the DisplayHook. Once there is a separate prompt manager, this |
|
480 | # the DisplayHook. Once there is a separate prompt manager, this | |
472 | # will initialize that object and all prompt related information. |
|
481 | # will initialize that object and all prompt related information. | |
473 | pass |
|
482 | pass | |
474 |
|
483 | |||
475 | def init_displayhook(self): |
|
484 | def init_displayhook(self): | |
476 | # Initialize displayhook, set in/out prompts and printing system |
|
485 | # Initialize displayhook, set in/out prompts and printing system | |
477 | self.displayhook = self.displayhook_class( |
|
486 | self.displayhook = self.displayhook_class( | |
478 | config=self.config, |
|
487 | config=self.config, | |
479 | shell=self, |
|
488 | shell=self, | |
480 | cache_size=self.cache_size, |
|
489 | cache_size=self.cache_size, | |
481 | input_sep = self.separate_in, |
|
490 | input_sep = self.separate_in, | |
482 | output_sep = self.separate_out, |
|
491 | output_sep = self.separate_out, | |
483 | output_sep2 = self.separate_out2, |
|
492 | output_sep2 = self.separate_out2, | |
484 | ps1 = self.prompt_in1, |
|
493 | ps1 = self.prompt_in1, | |
485 | ps2 = self.prompt_in2, |
|
494 | ps2 = self.prompt_in2, | |
486 | ps_out = self.prompt_out, |
|
495 | ps_out = self.prompt_out, | |
487 | pad_left = self.prompts_pad_left |
|
496 | pad_left = self.prompts_pad_left | |
488 | ) |
|
497 | ) | |
489 | # This is a context manager that installs/revmoes the displayhook at |
|
498 | # This is a context manager that installs/revmoes the displayhook at | |
490 | # the appropriate time. |
|
499 | # the appropriate time. | |
491 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
500 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
492 |
|
501 | |||
493 | def init_reload_doctest(self): |
|
502 | def init_reload_doctest(self): | |
494 | # Do a proper resetting of doctest, including the necessary displayhook |
|
503 | # Do a proper resetting of doctest, including the necessary displayhook | |
495 | # monkeypatching |
|
504 | # monkeypatching | |
496 | try: |
|
505 | try: | |
497 | doctest_reload() |
|
506 | doctest_reload() | |
498 | except ImportError: |
|
507 | except ImportError: | |
499 | warn("doctest module does not exist.") |
|
508 | warn("doctest module does not exist.") | |
500 |
|
509 | |||
501 | #------------------------------------------------------------------------- |
|
510 | #------------------------------------------------------------------------- | |
502 | # Things related to injections into the sys module |
|
511 | # Things related to injections into the sys module | |
503 | #------------------------------------------------------------------------- |
|
512 | #------------------------------------------------------------------------- | |
504 |
|
513 | |||
505 | def save_sys_module_state(self): |
|
514 | def save_sys_module_state(self): | |
506 | """Save the state of hooks in the sys module. |
|
515 | """Save the state of hooks in the sys module. | |
507 |
|
516 | |||
508 | This has to be called after self.user_ns is created. |
|
517 | This has to be called after self.user_ns is created. | |
509 | """ |
|
518 | """ | |
510 | self._orig_sys_module_state = {} |
|
519 | self._orig_sys_module_state = {} | |
511 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
520 | self._orig_sys_module_state['stdin'] = sys.stdin | |
512 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
521 | self._orig_sys_module_state['stdout'] = sys.stdout | |
513 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
522 | self._orig_sys_module_state['stderr'] = sys.stderr | |
514 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
523 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
515 | try: |
|
524 | try: | |
516 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
525 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
517 | except KeyError: |
|
526 | except KeyError: | |
518 | pass |
|
527 | pass | |
519 |
|
528 | |||
520 | def restore_sys_module_state(self): |
|
529 | def restore_sys_module_state(self): | |
521 | """Restore the state of the sys module.""" |
|
530 | """Restore the state of the sys module.""" | |
522 | try: |
|
531 | try: | |
523 | for k, v in self._orig_sys_module_state.iteritems(): |
|
532 | for k, v in self._orig_sys_module_state.iteritems(): | |
524 | setattr(sys, k, v) |
|
533 | setattr(sys, k, v) | |
525 | except AttributeError: |
|
534 | except AttributeError: | |
526 | pass |
|
535 | pass | |
527 | # Reset what what done in self.init_sys_modules |
|
536 | # Reset what what done in self.init_sys_modules | |
528 | try: |
|
537 | try: | |
529 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
538 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
530 | except (AttributeError, KeyError): |
|
539 | except (AttributeError, KeyError): | |
531 | pass |
|
540 | pass | |
532 |
|
541 | |||
533 | #------------------------------------------------------------------------- |
|
542 | #------------------------------------------------------------------------- | |
534 | # Things related to hooks |
|
543 | # Things related to hooks | |
535 | #------------------------------------------------------------------------- |
|
544 | #------------------------------------------------------------------------- | |
536 |
|
545 | |||
537 | def init_hooks(self): |
|
546 | def init_hooks(self): | |
538 | # hooks holds pointers used for user-side customizations |
|
547 | # hooks holds pointers used for user-side customizations | |
539 | self.hooks = Struct() |
|
548 | self.hooks = Struct() | |
540 |
|
549 | |||
541 | self.strdispatchers = {} |
|
550 | self.strdispatchers = {} | |
542 |
|
551 | |||
543 | # Set all default hooks, defined in the IPython.hooks module. |
|
552 | # Set all default hooks, defined in the IPython.hooks module. | |
544 | hooks = IPython.core.hooks |
|
553 | hooks = IPython.core.hooks | |
545 | for hook_name in hooks.__all__: |
|
554 | for hook_name in hooks.__all__: | |
546 | # default hooks have priority 100, i.e. low; user hooks should have |
|
555 | # default hooks have priority 100, i.e. low; user hooks should have | |
547 | # 0-100 priority |
|
556 | # 0-100 priority | |
548 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
557 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
549 |
|
558 | |||
550 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
559 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
551 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
560 | """set_hook(name,hook) -> sets an internal IPython hook. | |
552 |
|
561 | |||
553 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
562 | IPython exposes some of its internal API as user-modifiable hooks. By | |
554 | adding your function to one of these hooks, you can modify IPython's |
|
563 | adding your function to one of these hooks, you can modify IPython's | |
555 | behavior to call at runtime your own routines.""" |
|
564 | behavior to call at runtime your own routines.""" | |
556 |
|
565 | |||
557 | # At some point in the future, this should validate the hook before it |
|
566 | # At some point in the future, this should validate the hook before it | |
558 | # accepts it. Probably at least check that the hook takes the number |
|
567 | # accepts it. Probably at least check that the hook takes the number | |
559 | # of args it's supposed to. |
|
568 | # of args it's supposed to. | |
560 |
|
569 | |||
561 | f = types.MethodType(hook,self) |
|
570 | f = types.MethodType(hook,self) | |
562 |
|
571 | |||
563 | # check if the hook is for strdispatcher first |
|
572 | # check if the hook is for strdispatcher first | |
564 | if str_key is not None: |
|
573 | if str_key is not None: | |
565 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
574 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
566 | sdp.add_s(str_key, f, priority ) |
|
575 | sdp.add_s(str_key, f, priority ) | |
567 | self.strdispatchers[name] = sdp |
|
576 | self.strdispatchers[name] = sdp | |
568 | return |
|
577 | return | |
569 | if re_key is not None: |
|
578 | if re_key is not None: | |
570 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
579 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
571 | sdp.add_re(re.compile(re_key), f, priority ) |
|
580 | sdp.add_re(re.compile(re_key), f, priority ) | |
572 | self.strdispatchers[name] = sdp |
|
581 | self.strdispatchers[name] = sdp | |
573 | return |
|
582 | return | |
574 |
|
583 | |||
575 | dp = getattr(self.hooks, name, None) |
|
584 | dp = getattr(self.hooks, name, None) | |
576 | if name not in IPython.core.hooks.__all__: |
|
585 | if name not in IPython.core.hooks.__all__: | |
577 | print "Warning! Hook '%s' is not one of %s" % \ |
|
586 | print "Warning! Hook '%s' is not one of %s" % \ | |
578 | (name, IPython.core.hooks.__all__ ) |
|
587 | (name, IPython.core.hooks.__all__ ) | |
579 | if not dp: |
|
588 | if not dp: | |
580 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
589 | dp = IPython.core.hooks.CommandChainDispatcher() | |
581 |
|
590 | |||
582 | try: |
|
591 | try: | |
583 | dp.add(f,priority) |
|
592 | dp.add(f,priority) | |
584 | except AttributeError: |
|
593 | except AttributeError: | |
585 | # it was not commandchain, plain old func - replace |
|
594 | # it was not commandchain, plain old func - replace | |
586 | dp = f |
|
595 | dp = f | |
587 |
|
596 | |||
588 | setattr(self.hooks,name, dp) |
|
597 | setattr(self.hooks,name, dp) | |
589 |
|
598 | |||
590 | def register_post_execute(self, func): |
|
599 | def register_post_execute(self, func): | |
591 | """Register a function for calling after code execution. |
|
600 | """Register a function for calling after code execution. | |
592 | """ |
|
601 | """ | |
593 | if not callable(func): |
|
602 | if not callable(func): | |
594 | raise ValueError('argument %s must be callable' % func) |
|
603 | raise ValueError('argument %s must be callable' % func) | |
595 | self._post_execute.add(func) |
|
604 | self._post_execute.add(func) | |
596 |
|
605 | |||
597 | #------------------------------------------------------------------------- |
|
606 | #------------------------------------------------------------------------- | |
598 | # Things related to the "main" module |
|
607 | # Things related to the "main" module | |
599 | #------------------------------------------------------------------------- |
|
608 | #------------------------------------------------------------------------- | |
600 |
|
609 | |||
601 | def new_main_mod(self,ns=None): |
|
610 | def new_main_mod(self,ns=None): | |
602 | """Return a new 'main' module object for user code execution. |
|
611 | """Return a new 'main' module object for user code execution. | |
603 | """ |
|
612 | """ | |
604 | main_mod = self._user_main_module |
|
613 | main_mod = self._user_main_module | |
605 | init_fakemod_dict(main_mod,ns) |
|
614 | init_fakemod_dict(main_mod,ns) | |
606 | return main_mod |
|
615 | return main_mod | |
607 |
|
616 | |||
608 | def cache_main_mod(self,ns,fname): |
|
617 | def cache_main_mod(self,ns,fname): | |
609 | """Cache a main module's namespace. |
|
618 | """Cache a main module's namespace. | |
610 |
|
619 | |||
611 | When scripts are executed via %run, we must keep a reference to the |
|
620 | When scripts are executed via %run, we must keep a reference to the | |
612 | namespace of their __main__ module (a FakeModule instance) around so |
|
621 | namespace of their __main__ module (a FakeModule instance) around so | |
613 | that Python doesn't clear it, rendering objects defined therein |
|
622 | that Python doesn't clear it, rendering objects defined therein | |
614 | useless. |
|
623 | useless. | |
615 |
|
624 | |||
616 | This method keeps said reference in a private dict, keyed by the |
|
625 | This method keeps said reference in a private dict, keyed by the | |
617 | absolute path of the module object (which corresponds to the script |
|
626 | absolute path of the module object (which corresponds to the script | |
618 | path). This way, for multiple executions of the same script we only |
|
627 | path). This way, for multiple executions of the same script we only | |
619 | keep one copy of the namespace (the last one), thus preventing memory |
|
628 | keep one copy of the namespace (the last one), thus preventing memory | |
620 | leaks from old references while allowing the objects from the last |
|
629 | leaks from old references while allowing the objects from the last | |
621 | execution to be accessible. |
|
630 | execution to be accessible. | |
622 |
|
631 | |||
623 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
632 | Note: we can not allow the actual FakeModule instances to be deleted, | |
624 | because of how Python tears down modules (it hard-sets all their |
|
633 | because of how Python tears down modules (it hard-sets all their | |
625 | references to None without regard for reference counts). This method |
|
634 | references to None without regard for reference counts). This method | |
626 | must therefore make a *copy* of the given namespace, to allow the |
|
635 | must therefore make a *copy* of the given namespace, to allow the | |
627 | original module's __dict__ to be cleared and reused. |
|
636 | original module's __dict__ to be cleared and reused. | |
628 |
|
637 | |||
629 |
|
638 | |||
630 | Parameters |
|
639 | Parameters | |
631 | ---------- |
|
640 | ---------- | |
632 | ns : a namespace (a dict, typically) |
|
641 | ns : a namespace (a dict, typically) | |
633 |
|
642 | |||
634 | fname : str |
|
643 | fname : str | |
635 | Filename associated with the namespace. |
|
644 | Filename associated with the namespace. | |
636 |
|
645 | |||
637 | Examples |
|
646 | Examples | |
638 | -------- |
|
647 | -------- | |
639 |
|
648 | |||
640 | In [10]: import IPython |
|
649 | In [10]: import IPython | |
641 |
|
650 | |||
642 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
651 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
643 |
|
652 | |||
644 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
653 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
645 | Out[12]: True |
|
654 | Out[12]: True | |
646 | """ |
|
655 | """ | |
647 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
656 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
648 |
|
657 | |||
649 | def clear_main_mod_cache(self): |
|
658 | def clear_main_mod_cache(self): | |
650 | """Clear the cache of main modules. |
|
659 | """Clear the cache of main modules. | |
651 |
|
660 | |||
652 | Mainly for use by utilities like %reset. |
|
661 | Mainly for use by utilities like %reset. | |
653 |
|
662 | |||
654 | Examples |
|
663 | Examples | |
655 | -------- |
|
664 | -------- | |
656 |
|
665 | |||
657 | In [15]: import IPython |
|
666 | In [15]: import IPython | |
658 |
|
667 | |||
659 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
668 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
660 |
|
669 | |||
661 | In [17]: len(_ip._main_ns_cache) > 0 |
|
670 | In [17]: len(_ip._main_ns_cache) > 0 | |
662 | Out[17]: True |
|
671 | Out[17]: True | |
663 |
|
672 | |||
664 | In [18]: _ip.clear_main_mod_cache() |
|
673 | In [18]: _ip.clear_main_mod_cache() | |
665 |
|
674 | |||
666 | In [19]: len(_ip._main_ns_cache) == 0 |
|
675 | In [19]: len(_ip._main_ns_cache) == 0 | |
667 | Out[19]: True |
|
676 | Out[19]: True | |
668 | """ |
|
677 | """ | |
669 | self._main_ns_cache.clear() |
|
678 | self._main_ns_cache.clear() | |
670 |
|
679 | |||
671 | #------------------------------------------------------------------------- |
|
680 | #------------------------------------------------------------------------- | |
672 | # Things related to debugging |
|
681 | # Things related to debugging | |
673 | #------------------------------------------------------------------------- |
|
682 | #------------------------------------------------------------------------- | |
674 |
|
683 | |||
675 | def init_pdb(self): |
|
684 | def init_pdb(self): | |
676 | # Set calling of pdb on exceptions |
|
685 | # Set calling of pdb on exceptions | |
677 | # self.call_pdb is a property |
|
686 | # self.call_pdb is a property | |
678 | self.call_pdb = self.pdb |
|
687 | self.call_pdb = self.pdb | |
679 |
|
688 | |||
680 | def _get_call_pdb(self): |
|
689 | def _get_call_pdb(self): | |
681 | return self._call_pdb |
|
690 | return self._call_pdb | |
682 |
|
691 | |||
683 | def _set_call_pdb(self,val): |
|
692 | def _set_call_pdb(self,val): | |
684 |
|
693 | |||
685 | if val not in (0,1,False,True): |
|
694 | if val not in (0,1,False,True): | |
686 | raise ValueError,'new call_pdb value must be boolean' |
|
695 | raise ValueError,'new call_pdb value must be boolean' | |
687 |
|
696 | |||
688 | # store value in instance |
|
697 | # store value in instance | |
689 | self._call_pdb = val |
|
698 | self._call_pdb = val | |
690 |
|
699 | |||
691 | # notify the actual exception handlers |
|
700 | # notify the actual exception handlers | |
692 | self.InteractiveTB.call_pdb = val |
|
701 | self.InteractiveTB.call_pdb = val | |
693 |
|
702 | |||
694 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
703 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
695 | 'Control auto-activation of pdb at exceptions') |
|
704 | 'Control auto-activation of pdb at exceptions') | |
696 |
|
705 | |||
697 | def debugger(self,force=False): |
|
706 | def debugger(self,force=False): | |
698 | """Call the pydb/pdb debugger. |
|
707 | """Call the pydb/pdb debugger. | |
699 |
|
708 | |||
700 | Keywords: |
|
709 | Keywords: | |
701 |
|
710 | |||
702 | - force(False): by default, this routine checks the instance call_pdb |
|
711 | - force(False): by default, this routine checks the instance call_pdb | |
703 | flag and does not actually invoke the debugger if the flag is false. |
|
712 | flag and does not actually invoke the debugger if the flag is false. | |
704 | The 'force' option forces the debugger to activate even if the flag |
|
713 | The 'force' option forces the debugger to activate even if the flag | |
705 | is false. |
|
714 | is false. | |
706 | """ |
|
715 | """ | |
707 |
|
716 | |||
708 | if not (force or self.call_pdb): |
|
717 | if not (force or self.call_pdb): | |
709 | return |
|
718 | return | |
710 |
|
719 | |||
711 | if not hasattr(sys,'last_traceback'): |
|
720 | if not hasattr(sys,'last_traceback'): | |
712 | error('No traceback has been produced, nothing to debug.') |
|
721 | error('No traceback has been produced, nothing to debug.') | |
713 | return |
|
722 | return | |
714 |
|
723 | |||
715 | # use pydb if available |
|
724 | # use pydb if available | |
716 | if debugger.has_pydb: |
|
725 | if debugger.has_pydb: | |
717 | from pydb import pm |
|
726 | from pydb import pm | |
718 | else: |
|
727 | else: | |
719 | # fallback to our internal debugger |
|
728 | # fallback to our internal debugger | |
720 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
729 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
721 | self.history_saving_wrapper(pm)() |
|
730 | self.history_saving_wrapper(pm)() | |
722 |
|
731 | |||
723 | #------------------------------------------------------------------------- |
|
732 | #------------------------------------------------------------------------- | |
724 | # Things related to IPython's various namespaces |
|
733 | # Things related to IPython's various namespaces | |
725 | #------------------------------------------------------------------------- |
|
734 | #------------------------------------------------------------------------- | |
726 |
|
735 | |||
727 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
736 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
728 | # Create the namespace where the user will operate. user_ns is |
|
737 | # Create the namespace where the user will operate. user_ns is | |
729 | # normally the only one used, and it is passed to the exec calls as |
|
738 | # normally the only one used, and it is passed to the exec calls as | |
730 | # the locals argument. But we do carry a user_global_ns namespace |
|
739 | # the locals argument. But we do carry a user_global_ns namespace | |
731 | # given as the exec 'globals' argument, This is useful in embedding |
|
740 | # given as the exec 'globals' argument, This is useful in embedding | |
732 | # situations where the ipython shell opens in a context where the |
|
741 | # situations where the ipython shell opens in a context where the | |
733 | # distinction between locals and globals is meaningful. For |
|
742 | # distinction between locals and globals is meaningful. For | |
734 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
743 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
735 |
|
744 | |||
736 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
745 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
737 | # level as a dict instead of a module. This is a manual fix, but I |
|
746 | # level as a dict instead of a module. This is a manual fix, but I | |
738 | # should really track down where the problem is coming from. Alex |
|
747 | # should really track down where the problem is coming from. Alex | |
739 | # Schmolck reported this problem first. |
|
748 | # Schmolck reported this problem first. | |
740 |
|
749 | |||
741 | # A useful post by Alex Martelli on this topic: |
|
750 | # A useful post by Alex Martelli on this topic: | |
742 | # Re: inconsistent value from __builtins__ |
|
751 | # Re: inconsistent value from __builtins__ | |
743 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
752 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
744 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
753 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
745 | # Gruppen: comp.lang.python |
|
754 | # Gruppen: comp.lang.python | |
746 |
|
755 | |||
747 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
756 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
748 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
757 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
749 | # > <type 'dict'> |
|
758 | # > <type 'dict'> | |
750 | # > >>> print type(__builtins__) |
|
759 | # > >>> print type(__builtins__) | |
751 | # > <type 'module'> |
|
760 | # > <type 'module'> | |
752 | # > Is this difference in return value intentional? |
|
761 | # > Is this difference in return value intentional? | |
753 |
|
762 | |||
754 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
763 | # Well, it's documented that '__builtins__' can be either a dictionary | |
755 | # or a module, and it's been that way for a long time. Whether it's |
|
764 | # or a module, and it's been that way for a long time. Whether it's | |
756 | # intentional (or sensible), I don't know. In any case, the idea is |
|
765 | # intentional (or sensible), I don't know. In any case, the idea is | |
757 | # that if you need to access the built-in namespace directly, you |
|
766 | # that if you need to access the built-in namespace directly, you | |
758 | # should start with "import __builtin__" (note, no 's') which will |
|
767 | # should start with "import __builtin__" (note, no 's') which will | |
759 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
768 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
760 |
|
769 | |||
761 | # These routines return properly built dicts as needed by the rest of |
|
770 | # These routines return properly built dicts as needed by the rest of | |
762 | # the code, and can also be used by extension writers to generate |
|
771 | # the code, and can also be used by extension writers to generate | |
763 | # properly initialized namespaces. |
|
772 | # properly initialized namespaces. | |
764 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
773 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
765 | user_global_ns) |
|
774 | user_global_ns) | |
766 |
|
775 | |||
767 | # Assign namespaces |
|
776 | # Assign namespaces | |
768 | # This is the namespace where all normal user variables live |
|
777 | # This is the namespace where all normal user variables live | |
769 | self.user_ns = user_ns |
|
778 | self.user_ns = user_ns | |
770 | self.user_global_ns = user_global_ns |
|
779 | self.user_global_ns = user_global_ns | |
771 |
|
780 | |||
772 | # An auxiliary namespace that checks what parts of the user_ns were |
|
781 | # An auxiliary namespace that checks what parts of the user_ns were | |
773 | # loaded at startup, so we can list later only variables defined in |
|
782 | # loaded at startup, so we can list later only variables defined in | |
774 | # actual interactive use. Since it is always a subset of user_ns, it |
|
783 | # actual interactive use. Since it is always a subset of user_ns, it | |
775 | # doesn't need to be separately tracked in the ns_table. |
|
784 | # doesn't need to be separately tracked in the ns_table. | |
776 | self.user_ns_hidden = {} |
|
785 | self.user_ns_hidden = {} | |
777 |
|
786 | |||
778 | # A namespace to keep track of internal data structures to prevent |
|
787 | # A namespace to keep track of internal data structures to prevent | |
779 | # them from cluttering user-visible stuff. Will be updated later |
|
788 | # them from cluttering user-visible stuff. Will be updated later | |
780 | self.internal_ns = {} |
|
789 | self.internal_ns = {} | |
781 |
|
790 | |||
782 | # Now that FakeModule produces a real module, we've run into a nasty |
|
791 | # Now that FakeModule produces a real module, we've run into a nasty | |
783 | # problem: after script execution (via %run), the module where the user |
|
792 | # problem: after script execution (via %run), the module where the user | |
784 | # code ran is deleted. Now that this object is a true module (needed |
|
793 | # code ran is deleted. Now that this object is a true module (needed | |
785 | # so docetst and other tools work correctly), the Python module |
|
794 | # so docetst and other tools work correctly), the Python module | |
786 | # teardown mechanism runs over it, and sets to None every variable |
|
795 | # teardown mechanism runs over it, and sets to None every variable | |
787 | # present in that module. Top-level references to objects from the |
|
796 | # present in that module. Top-level references to objects from the | |
788 | # script survive, because the user_ns is updated with them. However, |
|
797 | # script survive, because the user_ns is updated with them. However, | |
789 | # calling functions defined in the script that use other things from |
|
798 | # calling functions defined in the script that use other things from | |
790 | # the script will fail, because the function's closure had references |
|
799 | # the script will fail, because the function's closure had references | |
791 | # to the original objects, which are now all None. So we must protect |
|
800 | # to the original objects, which are now all None. So we must protect | |
792 | # these modules from deletion by keeping a cache. |
|
801 | # these modules from deletion by keeping a cache. | |
793 | # |
|
802 | # | |
794 | # To avoid keeping stale modules around (we only need the one from the |
|
803 | # To avoid keeping stale modules around (we only need the one from the | |
795 | # last run), we use a dict keyed with the full path to the script, so |
|
804 | # last run), we use a dict keyed with the full path to the script, so | |
796 | # only the last version of the module is held in the cache. Note, |
|
805 | # only the last version of the module is held in the cache. Note, | |
797 | # however, that we must cache the module *namespace contents* (their |
|
806 | # however, that we must cache the module *namespace contents* (their | |
798 | # __dict__). Because if we try to cache the actual modules, old ones |
|
807 | # __dict__). Because if we try to cache the actual modules, old ones | |
799 | # (uncached) could be destroyed while still holding references (such as |
|
808 | # (uncached) could be destroyed while still holding references (such as | |
800 | # those held by GUI objects that tend to be long-lived)> |
|
809 | # those held by GUI objects that tend to be long-lived)> | |
801 | # |
|
810 | # | |
802 | # The %reset command will flush this cache. See the cache_main_mod() |
|
811 | # The %reset command will flush this cache. See the cache_main_mod() | |
803 | # and clear_main_mod_cache() methods for details on use. |
|
812 | # and clear_main_mod_cache() methods for details on use. | |
804 |
|
813 | |||
805 | # This is the cache used for 'main' namespaces |
|
814 | # This is the cache used for 'main' namespaces | |
806 | self._main_ns_cache = {} |
|
815 | self._main_ns_cache = {} | |
807 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
816 | # And this is the single instance of FakeModule whose __dict__ we keep | |
808 | # copying and clearing for reuse on each %run |
|
817 | # copying and clearing for reuse on each %run | |
809 | self._user_main_module = FakeModule() |
|
818 | self._user_main_module = FakeModule() | |
810 |
|
819 | |||
811 | # A table holding all the namespaces IPython deals with, so that |
|
820 | # A table holding all the namespaces IPython deals with, so that | |
812 | # introspection facilities can search easily. |
|
821 | # introspection facilities can search easily. | |
813 | self.ns_table = {'user':user_ns, |
|
822 | self.ns_table = {'user':user_ns, | |
814 | 'user_global':user_global_ns, |
|
823 | 'user_global':user_global_ns, | |
815 | 'internal':self.internal_ns, |
|
824 | 'internal':self.internal_ns, | |
816 | 'builtin':__builtin__.__dict__ |
|
825 | 'builtin':__builtin__.__dict__ | |
817 | } |
|
826 | } | |
818 |
|
827 | |||
819 | # Similarly, track all namespaces where references can be held and that |
|
828 | # Similarly, track all namespaces where references can be held and that | |
820 | # we can safely clear (so it can NOT include builtin). This one can be |
|
829 | # we can safely clear (so it can NOT include builtin). This one can be | |
821 | # a simple list. Note that the main execution namespaces, user_ns and |
|
830 | # a simple list. Note that the main execution namespaces, user_ns and | |
822 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
831 | # user_global_ns, can NOT be listed here, as clearing them blindly | |
823 | # causes errors in object __del__ methods. Instead, the reset() method |
|
832 | # causes errors in object __del__ methods. Instead, the reset() method | |
824 | # clears them manually and carefully. |
|
833 | # clears them manually and carefully. | |
825 | self.ns_refs_table = [ self.user_ns_hidden, |
|
834 | self.ns_refs_table = [ self.user_ns_hidden, | |
826 | self.internal_ns, self._main_ns_cache ] |
|
835 | self.internal_ns, self._main_ns_cache ] | |
827 |
|
836 | |||
828 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
837 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
829 | """Return a valid local and global user interactive namespaces. |
|
838 | """Return a valid local and global user interactive namespaces. | |
830 |
|
839 | |||
831 | This builds a dict with the minimal information needed to operate as a |
|
840 | This builds a dict with the minimal information needed to operate as a | |
832 | valid IPython user namespace, which you can pass to the various |
|
841 | valid IPython user namespace, which you can pass to the various | |
833 | embedding classes in ipython. The default implementation returns the |
|
842 | embedding classes in ipython. The default implementation returns the | |
834 | same dict for both the locals and the globals to allow functions to |
|
843 | same dict for both the locals and the globals to allow functions to | |
835 | refer to variables in the namespace. Customized implementations can |
|
844 | refer to variables in the namespace. Customized implementations can | |
836 | return different dicts. The locals dictionary can actually be anything |
|
845 | return different dicts. The locals dictionary can actually be anything | |
837 | following the basic mapping protocol of a dict, but the globals dict |
|
846 | following the basic mapping protocol of a dict, but the globals dict | |
838 | must be a true dict, not even a subclass. It is recommended that any |
|
847 | must be a true dict, not even a subclass. It is recommended that any | |
839 | custom object for the locals namespace synchronize with the globals |
|
848 | custom object for the locals namespace synchronize with the globals | |
840 | dict somehow. |
|
849 | dict somehow. | |
841 |
|
850 | |||
842 | Raises TypeError if the provided globals namespace is not a true dict. |
|
851 | Raises TypeError if the provided globals namespace is not a true dict. | |
843 |
|
852 | |||
844 | Parameters |
|
853 | Parameters | |
845 | ---------- |
|
854 | ---------- | |
846 | user_ns : dict-like, optional |
|
855 | user_ns : dict-like, optional | |
847 | The current user namespace. The items in this namespace should |
|
856 | The current user namespace. The items in this namespace should | |
848 | be included in the output. If None, an appropriate blank |
|
857 | be included in the output. If None, an appropriate blank | |
849 | namespace should be created. |
|
858 | namespace should be created. | |
850 | user_global_ns : dict, optional |
|
859 | user_global_ns : dict, optional | |
851 | The current user global namespace. The items in this namespace |
|
860 | The current user global namespace. The items in this namespace | |
852 | should be included in the output. If None, an appropriate |
|
861 | should be included in the output. If None, an appropriate | |
853 | blank namespace should be created. |
|
862 | blank namespace should be created. | |
854 |
|
863 | |||
855 | Returns |
|
864 | Returns | |
856 | ------- |
|
865 | ------- | |
857 | A pair of dictionary-like object to be used as the local namespace |
|
866 | A pair of dictionary-like object to be used as the local namespace | |
858 | of the interpreter and a dict to be used as the global namespace. |
|
867 | of the interpreter and a dict to be used as the global namespace. | |
859 | """ |
|
868 | """ | |
860 |
|
869 | |||
861 |
|
870 | |||
862 | # We must ensure that __builtin__ (without the final 's') is always |
|
871 | # We must ensure that __builtin__ (without the final 's') is always | |
863 | # available and pointing to the __builtin__ *module*. For more details: |
|
872 | # available and pointing to the __builtin__ *module*. For more details: | |
864 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
873 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
865 |
|
874 | |||
866 | if user_ns is None: |
|
875 | if user_ns is None: | |
867 | # Set __name__ to __main__ to better match the behavior of the |
|
876 | # Set __name__ to __main__ to better match the behavior of the | |
868 | # normal interpreter. |
|
877 | # normal interpreter. | |
869 | user_ns = {'__name__' :'__main__', |
|
878 | user_ns = {'__name__' :'__main__', | |
870 | '__builtin__' : __builtin__, |
|
879 | '__builtin__' : __builtin__, | |
871 | '__builtins__' : __builtin__, |
|
880 | '__builtins__' : __builtin__, | |
872 | } |
|
881 | } | |
873 | else: |
|
882 | else: | |
874 | user_ns.setdefault('__name__','__main__') |
|
883 | user_ns.setdefault('__name__','__main__') | |
875 | user_ns.setdefault('__builtin__',__builtin__) |
|
884 | user_ns.setdefault('__builtin__',__builtin__) | |
876 | user_ns.setdefault('__builtins__',__builtin__) |
|
885 | user_ns.setdefault('__builtins__',__builtin__) | |
877 |
|
886 | |||
878 | if user_global_ns is None: |
|
887 | if user_global_ns is None: | |
879 | user_global_ns = user_ns |
|
888 | user_global_ns = user_ns | |
880 | if type(user_global_ns) is not dict: |
|
889 | if type(user_global_ns) is not dict: | |
881 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
890 | raise TypeError("user_global_ns must be a true dict; got %r" | |
882 | % type(user_global_ns)) |
|
891 | % type(user_global_ns)) | |
883 |
|
892 | |||
884 | return user_ns, user_global_ns |
|
893 | return user_ns, user_global_ns | |
885 |
|
894 | |||
886 | def init_sys_modules(self): |
|
895 | def init_sys_modules(self): | |
887 | # We need to insert into sys.modules something that looks like a |
|
896 | # We need to insert into sys.modules something that looks like a | |
888 | # module but which accesses the IPython namespace, for shelve and |
|
897 | # module but which accesses the IPython namespace, for shelve and | |
889 | # pickle to work interactively. Normally they rely on getting |
|
898 | # pickle to work interactively. Normally they rely on getting | |
890 | # everything out of __main__, but for embedding purposes each IPython |
|
899 | # everything out of __main__, but for embedding purposes each IPython | |
891 | # instance has its own private namespace, so we can't go shoving |
|
900 | # instance has its own private namespace, so we can't go shoving | |
892 | # everything into __main__. |
|
901 | # everything into __main__. | |
893 |
|
902 | |||
894 | # note, however, that we should only do this for non-embedded |
|
903 | # note, however, that we should only do this for non-embedded | |
895 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
904 | # ipythons, which really mimic the __main__.__dict__ with their own | |
896 | # namespace. Embedded instances, on the other hand, should not do |
|
905 | # namespace. Embedded instances, on the other hand, should not do | |
897 | # this because they need to manage the user local/global namespaces |
|
906 | # this because they need to manage the user local/global namespaces | |
898 | # only, but they live within a 'normal' __main__ (meaning, they |
|
907 | # only, but they live within a 'normal' __main__ (meaning, they | |
899 | # shouldn't overtake the execution environment of the script they're |
|
908 | # shouldn't overtake the execution environment of the script they're | |
900 | # embedded in). |
|
909 | # embedded in). | |
901 |
|
910 | |||
902 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
911 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
903 |
|
912 | |||
904 | try: |
|
913 | try: | |
905 | main_name = self.user_ns['__name__'] |
|
914 | main_name = self.user_ns['__name__'] | |
906 | except KeyError: |
|
915 | except KeyError: | |
907 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
916 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
908 | else: |
|
917 | else: | |
909 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
918 | sys.modules[main_name] = FakeModule(self.user_ns) | |
910 |
|
919 | |||
911 | def init_user_ns(self): |
|
920 | def init_user_ns(self): | |
912 | """Initialize all user-visible namespaces to their minimum defaults. |
|
921 | """Initialize all user-visible namespaces to their minimum defaults. | |
913 |
|
922 | |||
914 | Certain history lists are also initialized here, as they effectively |
|
923 | Certain history lists are also initialized here, as they effectively | |
915 | act as user namespaces. |
|
924 | act as user namespaces. | |
916 |
|
925 | |||
917 | Notes |
|
926 | Notes | |
918 | ----- |
|
927 | ----- | |
919 | All data structures here are only filled in, they are NOT reset by this |
|
928 | All data structures here are only filled in, they are NOT reset by this | |
920 | method. If they were not empty before, data will simply be added to |
|
929 | method. If they were not empty before, data will simply be added to | |
921 | therm. |
|
930 | therm. | |
922 | """ |
|
931 | """ | |
923 | # This function works in two parts: first we put a few things in |
|
932 | # This function works in two parts: first we put a few things in | |
924 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
933 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
925 | # initial variables aren't shown by %who. After the sync, we add the |
|
934 | # initial variables aren't shown by %who. After the sync, we add the | |
926 | # rest of what we *do* want the user to see with %who even on a new |
|
935 | # rest of what we *do* want the user to see with %who even on a new | |
927 | # session (probably nothing, so theye really only see their own stuff) |
|
936 | # session (probably nothing, so theye really only see their own stuff) | |
928 |
|
937 | |||
929 | # The user dict must *always* have a __builtin__ reference to the |
|
938 | # The user dict must *always* have a __builtin__ reference to the | |
930 | # Python standard __builtin__ namespace, which must be imported. |
|
939 | # Python standard __builtin__ namespace, which must be imported. | |
931 | # This is so that certain operations in prompt evaluation can be |
|
940 | # This is so that certain operations in prompt evaluation can be | |
932 | # reliably executed with builtins. Note that we can NOT use |
|
941 | # reliably executed with builtins. Note that we can NOT use | |
933 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
942 | # __builtins__ (note the 's'), because that can either be a dict or a | |
934 | # module, and can even mutate at runtime, depending on the context |
|
943 | # module, and can even mutate at runtime, depending on the context | |
935 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
944 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
936 | # always a module object, though it must be explicitly imported. |
|
945 | # always a module object, though it must be explicitly imported. | |
937 |
|
946 | |||
938 | # For more details: |
|
947 | # For more details: | |
939 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
948 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
940 | ns = dict(__builtin__ = __builtin__) |
|
949 | ns = dict(__builtin__ = __builtin__) | |
941 |
|
950 | |||
942 | # Put 'help' in the user namespace |
|
951 | # Put 'help' in the user namespace | |
943 | try: |
|
952 | try: | |
944 | from site import _Helper |
|
953 | from site import _Helper | |
945 | ns['help'] = _Helper() |
|
954 | ns['help'] = _Helper() | |
946 | except ImportError: |
|
955 | except ImportError: | |
947 | warn('help() not available - check site.py') |
|
956 | warn('help() not available - check site.py') | |
948 |
|
957 | |||
949 | # make global variables for user access to the histories |
|
958 | # make global variables for user access to the histories | |
950 | ns['_ih'] = self.input_hist |
|
959 | ns['_ih'] = self.history_manager.input_hist_parsed | |
951 | ns['_oh'] = self.output_hist |
|
960 | ns['_oh'] = self.history_manager.output_hist | |
952 | ns['_dh'] = self.dir_hist |
|
961 | ns['_dh'] = self.history_manager.dir_hist | |
953 |
|
962 | |||
954 | ns['_sh'] = shadowns |
|
963 | ns['_sh'] = shadowns | |
955 |
|
964 | |||
956 | # user aliases to input and output histories. These shouldn't show up |
|
965 | # user aliases to input and output histories. These shouldn't show up | |
957 | # in %who, as they can have very large reprs. |
|
966 | # in %who, as they can have very large reprs. | |
958 | ns['In'] = self.input_hist |
|
967 | ns['In'] = self.history_manager.input_hist_parsed | |
959 | ns['Out'] = self.output_hist |
|
968 | ns['Out'] = self.history_manager.output_hist | |
960 |
|
969 | |||
961 | # Store myself as the public api!!! |
|
970 | # Store myself as the public api!!! | |
962 | ns['get_ipython'] = self.get_ipython |
|
971 | ns['get_ipython'] = self.get_ipython | |
963 |
|
972 | |||
964 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
973 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
965 | # by %who |
|
974 | # by %who | |
966 | self.user_ns_hidden.update(ns) |
|
975 | self.user_ns_hidden.update(ns) | |
967 |
|
976 | |||
968 | # Anything put into ns now would show up in %who. Think twice before |
|
977 | # Anything put into ns now would show up in %who. Think twice before | |
969 | # putting anything here, as we really want %who to show the user their |
|
978 | # putting anything here, as we really want %who to show the user their | |
970 | # stuff, not our variables. |
|
979 | # stuff, not our variables. | |
971 |
|
980 | |||
972 | # Finally, update the real user's namespace |
|
981 | # Finally, update the real user's namespace | |
973 | self.user_ns.update(ns) |
|
982 | self.user_ns.update(ns) | |
974 |
|
983 | |||
975 | def reset(self): |
|
984 | def reset(self): | |
976 | """Clear all internal namespaces. |
|
985 | """Clear all internal namespaces. | |
977 |
|
986 | |||
978 | Note that this is much more aggressive than %reset, since it clears |
|
987 | Note that this is much more aggressive than %reset, since it clears | |
979 | fully all namespaces, as well as all input/output lists. |
|
988 | fully all namespaces, as well as all input/output lists. | |
980 | """ |
|
989 | """ | |
981 | # Clear histories |
|
990 | # Clear histories | |
982 | self.history_manager.reset() |
|
991 | self.history_manager.reset() | |
983 |
|
992 | |||
984 | # Reset counter used to index all histories |
|
993 | # Reset counter used to index all histories | |
985 | self.execution_count = 0 |
|
994 | self.execution_count = 0 | |
986 |
|
995 | |||
987 | # Restore the user namespaces to minimal usability |
|
996 | # Restore the user namespaces to minimal usability | |
988 | for ns in self.ns_refs_table: |
|
997 | for ns in self.ns_refs_table: | |
989 | ns.clear() |
|
998 | ns.clear() | |
990 |
|
999 | |||
991 | # The main execution namespaces must be cleared very carefully, |
|
1000 | # The main execution namespaces must be cleared very carefully, | |
992 | # skipping the deletion of the builtin-related keys, because doing so |
|
1001 | # skipping the deletion of the builtin-related keys, because doing so | |
993 | # would cause errors in many object's __del__ methods. |
|
1002 | # would cause errors in many object's __del__ methods. | |
994 | for ns in [self.user_ns, self.user_global_ns]: |
|
1003 | for ns in [self.user_ns, self.user_global_ns]: | |
995 | drop_keys = set(ns.keys()) |
|
1004 | drop_keys = set(ns.keys()) | |
996 | drop_keys.discard('__builtin__') |
|
1005 | drop_keys.discard('__builtin__') | |
997 | drop_keys.discard('__builtins__') |
|
1006 | drop_keys.discard('__builtins__') | |
998 | for k in drop_keys: |
|
1007 | for k in drop_keys: | |
999 | del ns[k] |
|
1008 | del ns[k] | |
1000 |
|
1009 | |||
1001 | # Restore the user namespaces to minimal usability |
|
1010 | # Restore the user namespaces to minimal usability | |
1002 | self.init_user_ns() |
|
1011 | self.init_user_ns() | |
1003 |
|
1012 | |||
1004 | # Restore the default and user aliases |
|
1013 | # Restore the default and user aliases | |
1005 | self.alias_manager.clear_aliases() |
|
1014 | self.alias_manager.clear_aliases() | |
1006 | self.alias_manager.init_aliases() |
|
1015 | self.alias_manager.init_aliases() | |
1007 |
|
1016 | |||
1008 | def reset_selective(self, regex=None): |
|
1017 | def reset_selective(self, regex=None): | |
1009 | """Clear selective variables from internal namespaces based on a |
|
1018 | """Clear selective variables from internal namespaces based on a | |
1010 | specified regular expression. |
|
1019 | specified regular expression. | |
1011 |
|
1020 | |||
1012 | Parameters |
|
1021 | Parameters | |
1013 | ---------- |
|
1022 | ---------- | |
1014 | regex : string or compiled pattern, optional |
|
1023 | regex : string or compiled pattern, optional | |
1015 | A regular expression pattern that will be used in searching |
|
1024 | A regular expression pattern that will be used in searching | |
1016 | variable names in the users namespaces. |
|
1025 | variable names in the users namespaces. | |
1017 | """ |
|
1026 | """ | |
1018 | if regex is not None: |
|
1027 | if regex is not None: | |
1019 | try: |
|
1028 | try: | |
1020 | m = re.compile(regex) |
|
1029 | m = re.compile(regex) | |
1021 | except TypeError: |
|
1030 | except TypeError: | |
1022 | raise TypeError('regex must be a string or compiled pattern') |
|
1031 | raise TypeError('regex must be a string or compiled pattern') | |
1023 | # Search for keys in each namespace that match the given regex |
|
1032 | # Search for keys in each namespace that match the given regex | |
1024 | # If a match is found, delete the key/value pair. |
|
1033 | # If a match is found, delete the key/value pair. | |
1025 | for ns in self.ns_refs_table: |
|
1034 | for ns in self.ns_refs_table: | |
1026 | for var in ns: |
|
1035 | for var in ns: | |
1027 | if m.search(var): |
|
1036 | if m.search(var): | |
1028 | del ns[var] |
|
1037 | del ns[var] | |
1029 |
|
1038 | |||
1030 | def push(self, variables, interactive=True): |
|
1039 | def push(self, variables, interactive=True): | |
1031 | """Inject a group of variables into the IPython user namespace. |
|
1040 | """Inject a group of variables into the IPython user namespace. | |
1032 |
|
1041 | |||
1033 | Parameters |
|
1042 | Parameters | |
1034 | ---------- |
|
1043 | ---------- | |
1035 | variables : dict, str or list/tuple of str |
|
1044 | variables : dict, str or list/tuple of str | |
1036 | The variables to inject into the user's namespace. If a dict, a |
|
1045 | The variables to inject into the user's namespace. If a dict, a | |
1037 | simple update is done. If a str, the string is assumed to have |
|
1046 | simple update is done. If a str, the string is assumed to have | |
1038 | variable names separated by spaces. A list/tuple of str can also |
|
1047 | variable names separated by spaces. A list/tuple of str can also | |
1039 | be used to give the variable names. If just the variable names are |
|
1048 | be used to give the variable names. If just the variable names are | |
1040 | give (list/tuple/str) then the variable values looked up in the |
|
1049 | give (list/tuple/str) then the variable values looked up in the | |
1041 | callers frame. |
|
1050 | callers frame. | |
1042 | interactive : bool |
|
1051 | interactive : bool | |
1043 | If True (default), the variables will be listed with the ``who`` |
|
1052 | If True (default), the variables will be listed with the ``who`` | |
1044 | magic. |
|
1053 | magic. | |
1045 | """ |
|
1054 | """ | |
1046 | vdict = None |
|
1055 | vdict = None | |
1047 |
|
1056 | |||
1048 | # We need a dict of name/value pairs to do namespace updates. |
|
1057 | # We need a dict of name/value pairs to do namespace updates. | |
1049 | if isinstance(variables, dict): |
|
1058 | if isinstance(variables, dict): | |
1050 | vdict = variables |
|
1059 | vdict = variables | |
1051 | elif isinstance(variables, (basestring, list, tuple)): |
|
1060 | elif isinstance(variables, (basestring, list, tuple)): | |
1052 | if isinstance(variables, basestring): |
|
1061 | if isinstance(variables, basestring): | |
1053 | vlist = variables.split() |
|
1062 | vlist = variables.split() | |
1054 | else: |
|
1063 | else: | |
1055 | vlist = variables |
|
1064 | vlist = variables | |
1056 | vdict = {} |
|
1065 | vdict = {} | |
1057 | cf = sys._getframe(1) |
|
1066 | cf = sys._getframe(1) | |
1058 | for name in vlist: |
|
1067 | for name in vlist: | |
1059 | try: |
|
1068 | try: | |
1060 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1069 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1061 | except: |
|
1070 | except: | |
1062 | print ('Could not get variable %s from %s' % |
|
1071 | print ('Could not get variable %s from %s' % | |
1063 | (name,cf.f_code.co_name)) |
|
1072 | (name,cf.f_code.co_name)) | |
1064 | else: |
|
1073 | else: | |
1065 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1074 | raise ValueError('variables must be a dict/str/list/tuple') | |
1066 |
|
1075 | |||
1067 | # Propagate variables to user namespace |
|
1076 | # Propagate variables to user namespace | |
1068 | self.user_ns.update(vdict) |
|
1077 | self.user_ns.update(vdict) | |
1069 |
|
1078 | |||
1070 | # And configure interactive visibility |
|
1079 | # And configure interactive visibility | |
1071 | config_ns = self.user_ns_hidden |
|
1080 | config_ns = self.user_ns_hidden | |
1072 | if interactive: |
|
1081 | if interactive: | |
1073 | for name, val in vdict.iteritems(): |
|
1082 | for name, val in vdict.iteritems(): | |
1074 | config_ns.pop(name, None) |
|
1083 | config_ns.pop(name, None) | |
1075 | else: |
|
1084 | else: | |
1076 | for name,val in vdict.iteritems(): |
|
1085 | for name,val in vdict.iteritems(): | |
1077 | config_ns[name] = val |
|
1086 | config_ns[name] = val | |
1078 |
|
1087 | |||
1079 | #------------------------------------------------------------------------- |
|
1088 | #------------------------------------------------------------------------- | |
1080 | # Things related to object introspection |
|
1089 | # Things related to object introspection | |
1081 | #------------------------------------------------------------------------- |
|
1090 | #------------------------------------------------------------------------- | |
1082 |
|
1091 | |||
1083 | def _ofind(self, oname, namespaces=None): |
|
1092 | def _ofind(self, oname, namespaces=None): | |
1084 | """Find an object in the available namespaces. |
|
1093 | """Find an object in the available namespaces. | |
1085 |
|
1094 | |||
1086 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1095 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1087 |
|
1096 | |||
1088 | Has special code to detect magic functions. |
|
1097 | Has special code to detect magic functions. | |
1089 | """ |
|
1098 | """ | |
1090 | #oname = oname.strip() |
|
1099 | #oname = oname.strip() | |
1091 | #print '1- oname: <%r>' % oname # dbg |
|
1100 | #print '1- oname: <%r>' % oname # dbg | |
1092 | try: |
|
1101 | try: | |
1093 | oname = oname.strip().encode('ascii') |
|
1102 | oname = oname.strip().encode('ascii') | |
1094 | #print '2- oname: <%r>' % oname # dbg |
|
1103 | #print '2- oname: <%r>' % oname # dbg | |
1095 | except UnicodeEncodeError: |
|
1104 | except UnicodeEncodeError: | |
1096 | print 'Python identifiers can only contain ascii characters.' |
|
1105 | print 'Python identifiers can only contain ascii characters.' | |
1097 | return dict(found=False) |
|
1106 | return dict(found=False) | |
1098 |
|
1107 | |||
1099 | alias_ns = None |
|
1108 | alias_ns = None | |
1100 | if namespaces is None: |
|
1109 | if namespaces is None: | |
1101 | # Namespaces to search in: |
|
1110 | # Namespaces to search in: | |
1102 | # Put them in a list. The order is important so that we |
|
1111 | # Put them in a list. The order is important so that we | |
1103 | # find things in the same order that Python finds them. |
|
1112 | # find things in the same order that Python finds them. | |
1104 | namespaces = [ ('Interactive', self.user_ns), |
|
1113 | namespaces = [ ('Interactive', self.user_ns), | |
1105 | ('IPython internal', self.internal_ns), |
|
1114 | ('IPython internal', self.internal_ns), | |
1106 | ('Python builtin', __builtin__.__dict__), |
|
1115 | ('Python builtin', __builtin__.__dict__), | |
1107 | ('Alias', self.alias_manager.alias_table), |
|
1116 | ('Alias', self.alias_manager.alias_table), | |
1108 | ] |
|
1117 | ] | |
1109 | alias_ns = self.alias_manager.alias_table |
|
1118 | alias_ns = self.alias_manager.alias_table | |
1110 |
|
1119 | |||
1111 | # initialize results to 'null' |
|
1120 | # initialize results to 'null' | |
1112 | found = False; obj = None; ospace = None; ds = None; |
|
1121 | found = False; obj = None; ospace = None; ds = None; | |
1113 | ismagic = False; isalias = False; parent = None |
|
1122 | ismagic = False; isalias = False; parent = None | |
1114 |
|
1123 | |||
1115 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1124 | # We need to special-case 'print', which as of python2.6 registers as a | |
1116 | # function but should only be treated as one if print_function was |
|
1125 | # function but should only be treated as one if print_function was | |
1117 | # loaded with a future import. In this case, just bail. |
|
1126 | # loaded with a future import. In this case, just bail. | |
1118 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1127 | if (oname == 'print' and not (self.compile.compiler_flags & | |
1119 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1128 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1120 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1129 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1121 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1130 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1122 |
|
1131 | |||
1123 | # Look for the given name by splitting it in parts. If the head is |
|
1132 | # Look for the given name by splitting it in parts. If the head is | |
1124 | # found, then we look for all the remaining parts as members, and only |
|
1133 | # found, then we look for all the remaining parts as members, and only | |
1125 | # declare success if we can find them all. |
|
1134 | # declare success if we can find them all. | |
1126 | oname_parts = oname.split('.') |
|
1135 | oname_parts = oname.split('.') | |
1127 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1136 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1128 | for nsname,ns in namespaces: |
|
1137 | for nsname,ns in namespaces: | |
1129 | try: |
|
1138 | try: | |
1130 | obj = ns[oname_head] |
|
1139 | obj = ns[oname_head] | |
1131 | except KeyError: |
|
1140 | except KeyError: | |
1132 | continue |
|
1141 | continue | |
1133 | else: |
|
1142 | else: | |
1134 | #print 'oname_rest:', oname_rest # dbg |
|
1143 | #print 'oname_rest:', oname_rest # dbg | |
1135 | for part in oname_rest: |
|
1144 | for part in oname_rest: | |
1136 | try: |
|
1145 | try: | |
1137 | parent = obj |
|
1146 | parent = obj | |
1138 | obj = getattr(obj,part) |
|
1147 | obj = getattr(obj,part) | |
1139 | except: |
|
1148 | except: | |
1140 | # Blanket except b/c some badly implemented objects |
|
1149 | # Blanket except b/c some badly implemented objects | |
1141 | # allow __getattr__ to raise exceptions other than |
|
1150 | # allow __getattr__ to raise exceptions other than | |
1142 | # AttributeError, which then crashes IPython. |
|
1151 | # AttributeError, which then crashes IPython. | |
1143 | break |
|
1152 | break | |
1144 | else: |
|
1153 | else: | |
1145 | # If we finish the for loop (no break), we got all members |
|
1154 | # If we finish the for loop (no break), we got all members | |
1146 | found = True |
|
1155 | found = True | |
1147 | ospace = nsname |
|
1156 | ospace = nsname | |
1148 | if ns == alias_ns: |
|
1157 | if ns == alias_ns: | |
1149 | isalias = True |
|
1158 | isalias = True | |
1150 | break # namespace loop |
|
1159 | break # namespace loop | |
1151 |
|
1160 | |||
1152 | # Try to see if it's magic |
|
1161 | # Try to see if it's magic | |
1153 | if not found: |
|
1162 | if not found: | |
1154 | if oname.startswith(ESC_MAGIC): |
|
1163 | if oname.startswith(ESC_MAGIC): | |
1155 | oname = oname[1:] |
|
1164 | oname = oname[1:] | |
1156 | obj = getattr(self,'magic_'+oname,None) |
|
1165 | obj = getattr(self,'magic_'+oname,None) | |
1157 | if obj is not None: |
|
1166 | if obj is not None: | |
1158 | found = True |
|
1167 | found = True | |
1159 | ospace = 'IPython internal' |
|
1168 | ospace = 'IPython internal' | |
1160 | ismagic = True |
|
1169 | ismagic = True | |
1161 |
|
1170 | |||
1162 | # Last try: special-case some literals like '', [], {}, etc: |
|
1171 | # Last try: special-case some literals like '', [], {}, etc: | |
1163 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1172 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1164 | obj = eval(oname_head) |
|
1173 | obj = eval(oname_head) | |
1165 | found = True |
|
1174 | found = True | |
1166 | ospace = 'Interactive' |
|
1175 | ospace = 'Interactive' | |
1167 |
|
1176 | |||
1168 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1177 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1169 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1178 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1170 |
|
1179 | |||
1171 | def _ofind_property(self, oname, info): |
|
1180 | def _ofind_property(self, oname, info): | |
1172 | """Second part of object finding, to look for property details.""" |
|
1181 | """Second part of object finding, to look for property details.""" | |
1173 | if info.found: |
|
1182 | if info.found: | |
1174 | # Get the docstring of the class property if it exists. |
|
1183 | # Get the docstring of the class property if it exists. | |
1175 | path = oname.split('.') |
|
1184 | path = oname.split('.') | |
1176 | root = '.'.join(path[:-1]) |
|
1185 | root = '.'.join(path[:-1]) | |
1177 | if info.parent is not None: |
|
1186 | if info.parent is not None: | |
1178 | try: |
|
1187 | try: | |
1179 | target = getattr(info.parent, '__class__') |
|
1188 | target = getattr(info.parent, '__class__') | |
1180 | # The object belongs to a class instance. |
|
1189 | # The object belongs to a class instance. | |
1181 | try: |
|
1190 | try: | |
1182 | target = getattr(target, path[-1]) |
|
1191 | target = getattr(target, path[-1]) | |
1183 | # The class defines the object. |
|
1192 | # The class defines the object. | |
1184 | if isinstance(target, property): |
|
1193 | if isinstance(target, property): | |
1185 | oname = root + '.__class__.' + path[-1] |
|
1194 | oname = root + '.__class__.' + path[-1] | |
1186 | info = Struct(self._ofind(oname)) |
|
1195 | info = Struct(self._ofind(oname)) | |
1187 | except AttributeError: pass |
|
1196 | except AttributeError: pass | |
1188 | except AttributeError: pass |
|
1197 | except AttributeError: pass | |
1189 |
|
1198 | |||
1190 | # We return either the new info or the unmodified input if the object |
|
1199 | # We return either the new info or the unmodified input if the object | |
1191 | # hadn't been found |
|
1200 | # hadn't been found | |
1192 | return info |
|
1201 | return info | |
1193 |
|
1202 | |||
1194 | def _object_find(self, oname, namespaces=None): |
|
1203 | def _object_find(self, oname, namespaces=None): | |
1195 | """Find an object and return a struct with info about it.""" |
|
1204 | """Find an object and return a struct with info about it.""" | |
1196 | inf = Struct(self._ofind(oname, namespaces)) |
|
1205 | inf = Struct(self._ofind(oname, namespaces)) | |
1197 | return Struct(self._ofind_property(oname, inf)) |
|
1206 | return Struct(self._ofind_property(oname, inf)) | |
1198 |
|
1207 | |||
1199 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1208 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1200 | """Generic interface to the inspector system. |
|
1209 | """Generic interface to the inspector system. | |
1201 |
|
1210 | |||
1202 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1211 | This function is meant to be called by pdef, pdoc & friends.""" | |
1203 | info = self._object_find(oname) |
|
1212 | info = self._object_find(oname) | |
1204 | if info.found: |
|
1213 | if info.found: | |
1205 | pmethod = getattr(self.inspector, meth) |
|
1214 | pmethod = getattr(self.inspector, meth) | |
1206 | formatter = format_screen if info.ismagic else None |
|
1215 | formatter = format_screen if info.ismagic else None | |
1207 | if meth == 'pdoc': |
|
1216 | if meth == 'pdoc': | |
1208 | pmethod(info.obj, oname, formatter) |
|
1217 | pmethod(info.obj, oname, formatter) | |
1209 | elif meth == 'pinfo': |
|
1218 | elif meth == 'pinfo': | |
1210 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1219 | pmethod(info.obj, oname, formatter, info, **kw) | |
1211 | else: |
|
1220 | else: | |
1212 | pmethod(info.obj, oname) |
|
1221 | pmethod(info.obj, oname) | |
1213 | else: |
|
1222 | else: | |
1214 | print 'Object `%s` not found.' % oname |
|
1223 | print 'Object `%s` not found.' % oname | |
1215 | return 'not found' # so callers can take other action |
|
1224 | return 'not found' # so callers can take other action | |
1216 |
|
1225 | |||
1217 | def object_inspect(self, oname): |
|
1226 | def object_inspect(self, oname): | |
1218 | info = self._object_find(oname) |
|
1227 | info = self._object_find(oname) | |
1219 | if info.found: |
|
1228 | if info.found: | |
1220 | return self.inspector.info(info.obj, oname, info=info) |
|
1229 | return self.inspector.info(info.obj, oname, info=info) | |
1221 | else: |
|
1230 | else: | |
1222 | return oinspect.object_info(name=oname, found=False) |
|
1231 | return oinspect.object_info(name=oname, found=False) | |
1223 |
|
1232 | |||
1224 | #------------------------------------------------------------------------- |
|
1233 | #------------------------------------------------------------------------- | |
1225 | # Things related to history management |
|
1234 | # Things related to history management | |
1226 | #------------------------------------------------------------------------- |
|
1235 | #------------------------------------------------------------------------- | |
1227 |
|
1236 | |||
1228 | def init_history(self): |
|
1237 | def init_history(self): | |
1229 | self.history_manager = HistoryManager(shell=self) |
|
1238 | self.history_manager = HistoryManager(shell=self) | |
1230 |
|
1239 | |||
1231 | def save_hist(self): |
|
1240 | def save_history(self): | |
1232 | """Save input history to a file (via readline library).""" |
|
1241 | """Save input history to a file (via readline library).""" | |
1233 | self.history_manager.save_hist() |
|
1242 | self.history_manager.save_history() | |
1234 |
|
1243 | |||
1235 | # For backwards compatibility |
|
1244 | def reload_history(self): | |
1236 | savehist = save_hist |
|
|||
1237 |
|
||||
1238 | def reload_hist(self): |
|
|||
1239 | """Reload the input history from disk file.""" |
|
1245 | """Reload the input history from disk file.""" | |
1240 | self.history_manager.reload_hist() |
|
1246 | self.history_manager.reload_history() | |
1241 |
|
||||
1242 | # For backwards compatibility |
|
|||
1243 | reloadhist = reload_hist |
|
|||
1244 |
|
1247 | |||
1245 | def history_saving_wrapper(self, func): |
|
1248 | def history_saving_wrapper(self, func): | |
1246 | """ Wrap func for readline history saving |
|
1249 | """ Wrap func for readline history saving | |
1247 |
|
1250 | |||
1248 | Convert func into callable that saves & restores |
|
1251 | Convert func into callable that saves & restores | |
1249 | history around the call """ |
|
1252 | history around the call """ | |
1250 |
|
1253 | |||
1251 | if self.has_readline: |
|
1254 | if self.has_readline: | |
1252 | from IPython.utils import rlineimpl as readline |
|
1255 | from IPython.utils import rlineimpl as readline | |
1253 | else: |
|
1256 | else: | |
1254 | return func |
|
1257 | return func | |
1255 |
|
1258 | |||
1256 | def wrapper(): |
|
1259 | def wrapper(): | |
1257 | self.save_hist() |
|
1260 | self.save_history() | |
1258 | try: |
|
1261 | try: | |
1259 | func() |
|
1262 | func() | |
1260 | finally: |
|
1263 | finally: | |
1261 |
|
|
1264 | self.reload_history() | |
1262 | return wrapper |
|
1265 | return wrapper | |
1263 |
|
1266 | |||
1264 | #------------------------------------------------------------------------- |
|
1267 | #------------------------------------------------------------------------- | |
1265 | # Things related to exception handling and tracebacks (not debugging) |
|
1268 | # Things related to exception handling and tracebacks (not debugging) | |
1266 | #------------------------------------------------------------------------- |
|
1269 | #------------------------------------------------------------------------- | |
1267 |
|
1270 | |||
1268 | def init_traceback_handlers(self, custom_exceptions): |
|
1271 | def init_traceback_handlers(self, custom_exceptions): | |
1269 | # Syntax error handler. |
|
1272 | # Syntax error handler. | |
1270 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1273 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1271 |
|
1274 | |||
1272 | # The interactive one is initialized with an offset, meaning we always |
|
1275 | # The interactive one is initialized with an offset, meaning we always | |
1273 | # want to remove the topmost item in the traceback, which is our own |
|
1276 | # want to remove the topmost item in the traceback, which is our own | |
1274 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1277 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1275 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1278 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1276 | color_scheme='NoColor', |
|
1279 | color_scheme='NoColor', | |
1277 | tb_offset = 1, |
|
1280 | tb_offset = 1, | |
1278 | check_cache=self.compile.check_cache) |
|
1281 | check_cache=self.compile.check_cache) | |
1279 |
|
1282 | |||
1280 | # The instance will store a pointer to the system-wide exception hook, |
|
1283 | # The instance will store a pointer to the system-wide exception hook, | |
1281 | # so that runtime code (such as magics) can access it. This is because |
|
1284 | # so that runtime code (such as magics) can access it. This is because | |
1282 | # during the read-eval loop, it may get temporarily overwritten. |
|
1285 | # during the read-eval loop, it may get temporarily overwritten. | |
1283 | self.sys_excepthook = sys.excepthook |
|
1286 | self.sys_excepthook = sys.excepthook | |
1284 |
|
1287 | |||
1285 | # and add any custom exception handlers the user may have specified |
|
1288 | # and add any custom exception handlers the user may have specified | |
1286 | self.set_custom_exc(*custom_exceptions) |
|
1289 | self.set_custom_exc(*custom_exceptions) | |
1287 |
|
1290 | |||
1288 | # Set the exception mode |
|
1291 | # Set the exception mode | |
1289 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1292 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1290 |
|
1293 | |||
1291 | def set_custom_exc(self, exc_tuple, handler): |
|
1294 | def set_custom_exc(self, exc_tuple, handler): | |
1292 | """set_custom_exc(exc_tuple,handler) |
|
1295 | """set_custom_exc(exc_tuple,handler) | |
1293 |
|
1296 | |||
1294 | Set a custom exception handler, which will be called if any of the |
|
1297 | Set a custom exception handler, which will be called if any of the | |
1295 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1298 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1296 | run_code() method. |
|
1299 | run_code() method. | |
1297 |
|
1300 | |||
1298 | Inputs: |
|
1301 | Inputs: | |
1299 |
|
1302 | |||
1300 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1303 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1301 | handler for. It is very important that you use a tuple, and NOT A |
|
1304 | handler for. It is very important that you use a tuple, and NOT A | |
1302 | LIST here, because of the way Python's except statement works. If |
|
1305 | LIST here, because of the way Python's except statement works. If | |
1303 | you only want to trap a single exception, use a singleton tuple: |
|
1306 | you only want to trap a single exception, use a singleton tuple: | |
1304 |
|
1307 | |||
1305 | exc_tuple == (MyCustomException,) |
|
1308 | exc_tuple == (MyCustomException,) | |
1306 |
|
1309 | |||
1307 | - handler: this must be defined as a function with the following |
|
1310 | - handler: this must be defined as a function with the following | |
1308 | basic interface:: |
|
1311 | basic interface:: | |
1309 |
|
1312 | |||
1310 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1313 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1311 | ... |
|
1314 | ... | |
1312 | # The return value must be |
|
1315 | # The return value must be | |
1313 | return structured_traceback |
|
1316 | return structured_traceback | |
1314 |
|
1317 | |||
1315 | This will be made into an instance method (via types.MethodType) |
|
1318 | This will be made into an instance method (via types.MethodType) | |
1316 | of IPython itself, and it will be called if any of the exceptions |
|
1319 | of IPython itself, and it will be called if any of the exceptions | |
1317 | listed in the exc_tuple are caught. If the handler is None, an |
|
1320 | listed in the exc_tuple are caught. If the handler is None, an | |
1318 | internal basic one is used, which just prints basic info. |
|
1321 | internal basic one is used, which just prints basic info. | |
1319 |
|
1322 | |||
1320 | WARNING: by putting in your own exception handler into IPython's main |
|
1323 | WARNING: by putting in your own exception handler into IPython's main | |
1321 | execution loop, you run a very good chance of nasty crashes. This |
|
1324 | execution loop, you run a very good chance of nasty crashes. This | |
1322 | facility should only be used if you really know what you are doing.""" |
|
1325 | facility should only be used if you really know what you are doing.""" | |
1323 |
|
1326 | |||
1324 | assert type(exc_tuple)==type(()) , \ |
|
1327 | assert type(exc_tuple)==type(()) , \ | |
1325 | "The custom exceptions must be given AS A TUPLE." |
|
1328 | "The custom exceptions must be given AS A TUPLE." | |
1326 |
|
1329 | |||
1327 | def dummy_handler(self,etype,value,tb): |
|
1330 | def dummy_handler(self,etype,value,tb): | |
1328 | print '*** Simple custom exception handler ***' |
|
1331 | print '*** Simple custom exception handler ***' | |
1329 | print 'Exception type :',etype |
|
1332 | print 'Exception type :',etype | |
1330 | print 'Exception value:',value |
|
1333 | print 'Exception value:',value | |
1331 | print 'Traceback :',tb |
|
1334 | print 'Traceback :',tb | |
1332 | print 'Source code :','\n'.join(self.buffer) |
|
1335 | print 'Source code :','\n'.join(self.buffer) | |
1333 |
|
1336 | |||
1334 | if handler is None: handler = dummy_handler |
|
1337 | if handler is None: handler = dummy_handler | |
1335 |
|
1338 | |||
1336 | self.CustomTB = types.MethodType(handler,self) |
|
1339 | self.CustomTB = types.MethodType(handler,self) | |
1337 | self.custom_exceptions = exc_tuple |
|
1340 | self.custom_exceptions = exc_tuple | |
1338 |
|
1341 | |||
1339 | def excepthook(self, etype, value, tb): |
|
1342 | def excepthook(self, etype, value, tb): | |
1340 | """One more defense for GUI apps that call sys.excepthook. |
|
1343 | """One more defense for GUI apps that call sys.excepthook. | |
1341 |
|
1344 | |||
1342 | GUI frameworks like wxPython trap exceptions and call |
|
1345 | GUI frameworks like wxPython trap exceptions and call | |
1343 | sys.excepthook themselves. I guess this is a feature that |
|
1346 | sys.excepthook themselves. I guess this is a feature that | |
1344 | enables them to keep running after exceptions that would |
|
1347 | enables them to keep running after exceptions that would | |
1345 | otherwise kill their mainloop. This is a bother for IPython |
|
1348 | otherwise kill their mainloop. This is a bother for IPython | |
1346 | which excepts to catch all of the program exceptions with a try: |
|
1349 | which excepts to catch all of the program exceptions with a try: | |
1347 | except: statement. |
|
1350 | except: statement. | |
1348 |
|
1351 | |||
1349 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1352 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1350 | any app directly invokes sys.excepthook, it will look to the user like |
|
1353 | any app directly invokes sys.excepthook, it will look to the user like | |
1351 | IPython crashed. In order to work around this, we can disable the |
|
1354 | IPython crashed. In order to work around this, we can disable the | |
1352 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1355 | CrashHandler and replace it with this excepthook instead, which prints a | |
1353 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1356 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1354 | call sys.excepthook will generate a regular-looking exception from |
|
1357 | call sys.excepthook will generate a regular-looking exception from | |
1355 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1358 | IPython, and the CrashHandler will only be triggered by real IPython | |
1356 | crashes. |
|
1359 | crashes. | |
1357 |
|
1360 | |||
1358 | This hook should be used sparingly, only in places which are not likely |
|
1361 | This hook should be used sparingly, only in places which are not likely | |
1359 | to be true IPython errors. |
|
1362 | to be true IPython errors. | |
1360 | """ |
|
1363 | """ | |
1361 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1364 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1362 |
|
1365 | |||
1363 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1366 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1364 | exception_only=False): |
|
1367 | exception_only=False): | |
1365 | """Display the exception that just occurred. |
|
1368 | """Display the exception that just occurred. | |
1366 |
|
1369 | |||
1367 | If nothing is known about the exception, this is the method which |
|
1370 | If nothing is known about the exception, this is the method which | |
1368 | should be used throughout the code for presenting user tracebacks, |
|
1371 | should be used throughout the code for presenting user tracebacks, | |
1369 | rather than directly invoking the InteractiveTB object. |
|
1372 | rather than directly invoking the InteractiveTB object. | |
1370 |
|
1373 | |||
1371 | A specific showsyntaxerror() also exists, but this method can take |
|
1374 | A specific showsyntaxerror() also exists, but this method can take | |
1372 | care of calling it if needed, so unless you are explicitly catching a |
|
1375 | care of calling it if needed, so unless you are explicitly catching a | |
1373 | SyntaxError exception, don't try to analyze the stack manually and |
|
1376 | SyntaxError exception, don't try to analyze the stack manually and | |
1374 | simply call this method.""" |
|
1377 | simply call this method.""" | |
1375 |
|
1378 | |||
1376 | try: |
|
1379 | try: | |
1377 | if exc_tuple is None: |
|
1380 | if exc_tuple is None: | |
1378 | etype, value, tb = sys.exc_info() |
|
1381 | etype, value, tb = sys.exc_info() | |
1379 | else: |
|
1382 | else: | |
1380 | etype, value, tb = exc_tuple |
|
1383 | etype, value, tb = exc_tuple | |
1381 |
|
1384 | |||
1382 | if etype is None: |
|
1385 | if etype is None: | |
1383 | if hasattr(sys, 'last_type'): |
|
1386 | if hasattr(sys, 'last_type'): | |
1384 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1387 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1385 | sys.last_traceback |
|
1388 | sys.last_traceback | |
1386 | else: |
|
1389 | else: | |
1387 | self.write_err('No traceback available to show.\n') |
|
1390 | self.write_err('No traceback available to show.\n') | |
1388 | return |
|
1391 | return | |
1389 |
|
1392 | |||
1390 | if etype is SyntaxError: |
|
1393 | if etype is SyntaxError: | |
1391 | # Though this won't be called by syntax errors in the input |
|
1394 | # Though this won't be called by syntax errors in the input | |
1392 | # line, there may be SyntaxError cases whith imported code. |
|
1395 | # line, there may be SyntaxError cases whith imported code. | |
1393 | self.showsyntaxerror(filename) |
|
1396 | self.showsyntaxerror(filename) | |
1394 | elif etype is UsageError: |
|
1397 | elif etype is UsageError: | |
1395 | print "UsageError:", value |
|
1398 | print "UsageError:", value | |
1396 | else: |
|
1399 | else: | |
1397 | # WARNING: these variables are somewhat deprecated and not |
|
1400 | # WARNING: these variables are somewhat deprecated and not | |
1398 | # necessarily safe to use in a threaded environment, but tools |
|
1401 | # necessarily safe to use in a threaded environment, but tools | |
1399 | # like pdb depend on their existence, so let's set them. If we |
|
1402 | # like pdb depend on their existence, so let's set them. If we | |
1400 | # find problems in the field, we'll need to revisit their use. |
|
1403 | # find problems in the field, we'll need to revisit their use. | |
1401 | sys.last_type = etype |
|
1404 | sys.last_type = etype | |
1402 | sys.last_value = value |
|
1405 | sys.last_value = value | |
1403 | sys.last_traceback = tb |
|
1406 | sys.last_traceback = tb | |
1404 |
|
1407 | |||
1405 | if etype in self.custom_exceptions: |
|
1408 | if etype in self.custom_exceptions: | |
1406 | # FIXME: Old custom traceback objects may just return a |
|
1409 | # FIXME: Old custom traceback objects may just return a | |
1407 | # string, in that case we just put it into a list |
|
1410 | # string, in that case we just put it into a list | |
1408 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1411 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1409 | if isinstance(ctb, basestring): |
|
1412 | if isinstance(ctb, basestring): | |
1410 | stb = [stb] |
|
1413 | stb = [stb] | |
1411 | else: |
|
1414 | else: | |
1412 | if exception_only: |
|
1415 | if exception_only: | |
1413 | stb = ['An exception has occurred, use %tb to see ' |
|
1416 | stb = ['An exception has occurred, use %tb to see ' | |
1414 | 'the full traceback.\n'] |
|
1417 | 'the full traceback.\n'] | |
1415 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1418 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1416 | value)) |
|
1419 | value)) | |
1417 | else: |
|
1420 | else: | |
1418 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1421 | stb = self.InteractiveTB.structured_traceback(etype, | |
1419 | value, tb, tb_offset=tb_offset) |
|
1422 | value, tb, tb_offset=tb_offset) | |
1420 | # FIXME: the pdb calling should be done by us, not by |
|
1423 | # FIXME: the pdb calling should be done by us, not by | |
1421 | # the code computing the traceback. |
|
1424 | # the code computing the traceback. | |
1422 | if self.InteractiveTB.call_pdb: |
|
1425 | if self.InteractiveTB.call_pdb: | |
1423 | # pdb mucks up readline, fix it back |
|
1426 | # pdb mucks up readline, fix it back | |
1424 | self.set_readline_completer() |
|
1427 | self.set_readline_completer() | |
1425 |
|
1428 | |||
1426 | # Actually show the traceback |
|
1429 | # Actually show the traceback | |
1427 | self._showtraceback(etype, value, stb) |
|
1430 | self._showtraceback(etype, value, stb) | |
1428 |
|
1431 | |||
1429 | except KeyboardInterrupt: |
|
1432 | except KeyboardInterrupt: | |
1430 | self.write_err("\nKeyboardInterrupt\n") |
|
1433 | self.write_err("\nKeyboardInterrupt\n") | |
1431 |
|
1434 | |||
1432 | def _showtraceback(self, etype, evalue, stb): |
|
1435 | def _showtraceback(self, etype, evalue, stb): | |
1433 | """Actually show a traceback. |
|
1436 | """Actually show a traceback. | |
1434 |
|
1437 | |||
1435 | Subclasses may override this method to put the traceback on a different |
|
1438 | Subclasses may override this method to put the traceback on a different | |
1436 | place, like a side channel. |
|
1439 | place, like a side channel. | |
1437 | """ |
|
1440 | """ | |
1438 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1441 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1439 |
|
1442 | |||
1440 | def showsyntaxerror(self, filename=None): |
|
1443 | def showsyntaxerror(self, filename=None): | |
1441 | """Display the syntax error that just occurred. |
|
1444 | """Display the syntax error that just occurred. | |
1442 |
|
1445 | |||
1443 | This doesn't display a stack trace because there isn't one. |
|
1446 | This doesn't display a stack trace because there isn't one. | |
1444 |
|
1447 | |||
1445 | If a filename is given, it is stuffed in the exception instead |
|
1448 | If a filename is given, it is stuffed in the exception instead | |
1446 | of what was there before (because Python's parser always uses |
|
1449 | of what was there before (because Python's parser always uses | |
1447 | "<string>" when reading from a string). |
|
1450 | "<string>" when reading from a string). | |
1448 | """ |
|
1451 | """ | |
1449 | etype, value, last_traceback = sys.exc_info() |
|
1452 | etype, value, last_traceback = sys.exc_info() | |
1450 |
|
1453 | |||
1451 | # See note about these variables in showtraceback() above |
|
1454 | # See note about these variables in showtraceback() above | |
1452 | sys.last_type = etype |
|
1455 | sys.last_type = etype | |
1453 | sys.last_value = value |
|
1456 | sys.last_value = value | |
1454 | sys.last_traceback = last_traceback |
|
1457 | sys.last_traceback = last_traceback | |
1455 |
|
1458 | |||
1456 | if filename and etype is SyntaxError: |
|
1459 | if filename and etype is SyntaxError: | |
1457 | # Work hard to stuff the correct filename in the exception |
|
1460 | # Work hard to stuff the correct filename in the exception | |
1458 | try: |
|
1461 | try: | |
1459 | msg, (dummy_filename, lineno, offset, line) = value |
|
1462 | msg, (dummy_filename, lineno, offset, line) = value | |
1460 | except: |
|
1463 | except: | |
1461 | # Not the format we expect; leave it alone |
|
1464 | # Not the format we expect; leave it alone | |
1462 | pass |
|
1465 | pass | |
1463 | else: |
|
1466 | else: | |
1464 | # Stuff in the right filename |
|
1467 | # Stuff in the right filename | |
1465 | try: |
|
1468 | try: | |
1466 | # Assume SyntaxError is a class exception |
|
1469 | # Assume SyntaxError is a class exception | |
1467 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1470 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1468 | except: |
|
1471 | except: | |
1469 | # If that failed, assume SyntaxError is a string |
|
1472 | # If that failed, assume SyntaxError is a string | |
1470 | value = msg, (filename, lineno, offset, line) |
|
1473 | value = msg, (filename, lineno, offset, line) | |
1471 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1474 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1472 | self._showtraceback(etype, value, stb) |
|
1475 | self._showtraceback(etype, value, stb) | |
1473 |
|
1476 | |||
1474 | #------------------------------------------------------------------------- |
|
1477 | #------------------------------------------------------------------------- | |
1475 | # Things related to readline |
|
1478 | # Things related to readline | |
1476 | #------------------------------------------------------------------------- |
|
1479 | #------------------------------------------------------------------------- | |
1477 |
|
1480 | |||
1478 | def init_readline(self): |
|
1481 | def init_readline(self): | |
1479 | """Command history completion/saving/reloading.""" |
|
1482 | """Command history completion/saving/reloading.""" | |
1480 |
|
1483 | |||
1481 | if self.readline_use: |
|
1484 | if self.readline_use: | |
1482 | import IPython.utils.rlineimpl as readline |
|
1485 | import IPython.utils.rlineimpl as readline | |
1483 |
|
1486 | |||
1484 | self.rl_next_input = None |
|
1487 | self.rl_next_input = None | |
1485 | self.rl_do_indent = False |
|
1488 | self.rl_do_indent = False | |
1486 |
|
1489 | |||
1487 | if not self.readline_use or not readline.have_readline: |
|
1490 | if not self.readline_use or not readline.have_readline: | |
1488 | self.has_readline = False |
|
1491 | self.has_readline = False | |
1489 | self.readline = None |
|
1492 | self.readline = None | |
1490 | # Set a number of methods that depend on readline to be no-op |
|
1493 | # Set a number of methods that depend on readline to be no-op | |
1491 | self.save_hist = no_op |
|
|||
1492 | self.reload_hist = no_op |
|
|||
1493 | self.set_readline_completer = no_op |
|
1494 | self.set_readline_completer = no_op | |
1494 | self.set_custom_completer = no_op |
|
1495 | self.set_custom_completer = no_op | |
1495 | self.set_completer_frame = no_op |
|
1496 | self.set_completer_frame = no_op | |
1496 | warn('Readline services not available or not loaded.') |
|
1497 | warn('Readline services not available or not loaded.') | |
1497 | else: |
|
1498 | else: | |
1498 | self.has_readline = True |
|
1499 | self.has_readline = True | |
1499 | self.readline = readline |
|
1500 | self.readline = readline | |
1500 | sys.modules['readline'] = readline |
|
1501 | sys.modules['readline'] = readline | |
1501 |
|
1502 | |||
1502 | # Platform-specific configuration |
|
1503 | # Platform-specific configuration | |
1503 | if os.name == 'nt': |
|
1504 | if os.name == 'nt': | |
1504 | # FIXME - check with Frederick to see if we can harmonize |
|
1505 | # FIXME - check with Frederick to see if we can harmonize | |
1505 | # naming conventions with pyreadline to avoid this |
|
1506 | # naming conventions with pyreadline to avoid this | |
1506 | # platform-dependent check |
|
1507 | # platform-dependent check | |
1507 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1508 | self.readline_startup_hook = readline.set_pre_input_hook | |
1508 | else: |
|
1509 | else: | |
1509 | self.readline_startup_hook = readline.set_startup_hook |
|
1510 | self.readline_startup_hook = readline.set_startup_hook | |
1510 |
|
1511 | |||
1511 | # Load user's initrc file (readline config) |
|
1512 | # Load user's initrc file (readline config) | |
1512 | # Or if libedit is used, load editrc. |
|
1513 | # Or if libedit is used, load editrc. | |
1513 | inputrc_name = os.environ.get('INPUTRC') |
|
1514 | inputrc_name = os.environ.get('INPUTRC') | |
1514 | if inputrc_name is None: |
|
1515 | if inputrc_name is None: | |
1515 | home_dir = get_home_dir() |
|
1516 | home_dir = get_home_dir() | |
1516 | if home_dir is not None: |
|
1517 | if home_dir is not None: | |
1517 | inputrc_name = '.inputrc' |
|
1518 | inputrc_name = '.inputrc' | |
1518 | if readline.uses_libedit: |
|
1519 | if readline.uses_libedit: | |
1519 | inputrc_name = '.editrc' |
|
1520 | inputrc_name = '.editrc' | |
1520 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1521 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1521 | if os.path.isfile(inputrc_name): |
|
1522 | if os.path.isfile(inputrc_name): | |
1522 | try: |
|
1523 | try: | |
1523 | readline.read_init_file(inputrc_name) |
|
1524 | readline.read_init_file(inputrc_name) | |
1524 | except: |
|
1525 | except: | |
1525 | warn('Problems reading readline initialization file <%s>' |
|
1526 | warn('Problems reading readline initialization file <%s>' | |
1526 | % inputrc_name) |
|
1527 | % inputrc_name) | |
1527 |
|
1528 | |||
1528 | # Configure readline according to user's prefs |
|
1529 | # Configure readline according to user's prefs | |
1529 | # This is only done if GNU readline is being used. If libedit |
|
1530 | # This is only done if GNU readline is being used. If libedit | |
1530 | # is being used (as on Leopard) the readline config is |
|
1531 | # is being used (as on Leopard) the readline config is | |
1531 | # not run as the syntax for libedit is different. |
|
1532 | # not run as the syntax for libedit is different. | |
1532 | if not readline.uses_libedit: |
|
1533 | if not readline.uses_libedit: | |
1533 | for rlcommand in self.readline_parse_and_bind: |
|
1534 | for rlcommand in self.readline_parse_and_bind: | |
1534 | #print "loading rl:",rlcommand # dbg |
|
1535 | #print "loading rl:",rlcommand # dbg | |
1535 | readline.parse_and_bind(rlcommand) |
|
1536 | readline.parse_and_bind(rlcommand) | |
1536 |
|
1537 | |||
1537 | # Remove some chars from the delimiters list. If we encounter |
|
1538 | # Remove some chars from the delimiters list. If we encounter | |
1538 | # unicode chars, discard them. |
|
1539 | # unicode chars, discard them. | |
1539 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1540 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1540 | delims = delims.translate(None, self.readline_remove_delims) |
|
1541 | delims = delims.translate(None, self.readline_remove_delims) | |
1541 | delims = delims.replace(ESC_MAGIC, '') |
|
1542 | delims = delims.replace(ESC_MAGIC, '') | |
1542 | readline.set_completer_delims(delims) |
|
1543 | readline.set_completer_delims(delims) | |
1543 | # otherwise we end up with a monster history after a while: |
|
1544 | # otherwise we end up with a monster history after a while: | |
1544 |
readline.set_history_length( |
|
1545 | readline.set_history_length(self.history_length) | |
1545 | try: |
|
1546 | try: | |
1546 | #print '*** Reading readline history' # dbg |
|
1547 | #print '*** Reading readline history' # dbg | |
1547 |
|
|
1548 | self.reload_history() | |
1548 | except IOError: |
|
1549 | except IOError: | |
1549 | pass # It doesn't exist yet. |
|
1550 | pass # It doesn't exist yet. | |
1550 |
|
1551 | |||
1551 | # If we have readline, we want our history saved upon ipython |
|
|||
1552 | # exiting. |
|
|||
1553 | atexit.register(self.save_hist) |
|
|||
1554 |
|
||||
1555 | # Configure auto-indent for all platforms |
|
1552 | # Configure auto-indent for all platforms | |
1556 | self.set_autoindent(self.autoindent) |
|
1553 | self.set_autoindent(self.autoindent) | |
1557 |
|
1554 | |||
1558 | def set_next_input(self, s): |
|
1555 | def set_next_input(self, s): | |
1559 | """ Sets the 'default' input string for the next command line. |
|
1556 | """ Sets the 'default' input string for the next command line. | |
1560 |
|
1557 | |||
1561 | Requires readline. |
|
1558 | Requires readline. | |
1562 |
|
1559 | |||
1563 | Example: |
|
1560 | Example: | |
1564 |
|
1561 | |||
1565 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1562 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1566 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1563 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1567 | """ |
|
1564 | """ | |
1568 |
|
1565 | |||
1569 | self.rl_next_input = s |
|
1566 | self.rl_next_input = s | |
1570 |
|
1567 | |||
1571 | # Maybe move this to the terminal subclass? |
|
1568 | # Maybe move this to the terminal subclass? | |
1572 | def pre_readline(self): |
|
1569 | def pre_readline(self): | |
1573 | """readline hook to be used at the start of each line. |
|
1570 | """readline hook to be used at the start of each line. | |
1574 |
|
1571 | |||
1575 | Currently it handles auto-indent only.""" |
|
1572 | Currently it handles auto-indent only.""" | |
1576 |
|
1573 | |||
1577 | if self.rl_do_indent: |
|
1574 | if self.rl_do_indent: | |
1578 | self.readline.insert_text(self._indent_current_str()) |
|
1575 | self.readline.insert_text(self._indent_current_str()) | |
1579 | if self.rl_next_input is not None: |
|
1576 | if self.rl_next_input is not None: | |
1580 | self.readline.insert_text(self.rl_next_input) |
|
1577 | self.readline.insert_text(self.rl_next_input) | |
1581 | self.rl_next_input = None |
|
1578 | self.rl_next_input = None | |
1582 |
|
1579 | |||
1583 | def _indent_current_str(self): |
|
1580 | def _indent_current_str(self): | |
1584 | """return the current level of indentation as a string""" |
|
1581 | """return the current level of indentation as a string""" | |
1585 | return self.input_splitter.indent_spaces * ' ' |
|
1582 | return self.input_splitter.indent_spaces * ' ' | |
1586 |
|
1583 | |||
1587 | #------------------------------------------------------------------------- |
|
1584 | #------------------------------------------------------------------------- | |
1588 | # Things related to text completion |
|
1585 | # Things related to text completion | |
1589 | #------------------------------------------------------------------------- |
|
1586 | #------------------------------------------------------------------------- | |
1590 |
|
1587 | |||
1591 | def init_completer(self): |
|
1588 | def init_completer(self): | |
1592 | """Initialize the completion machinery. |
|
1589 | """Initialize the completion machinery. | |
1593 |
|
1590 | |||
1594 | This creates completion machinery that can be used by client code, |
|
1591 | This creates completion machinery that can be used by client code, | |
1595 | either interactively in-process (typically triggered by the readline |
|
1592 | either interactively in-process (typically triggered by the readline | |
1596 | library), programatically (such as in test suites) or out-of-prcess |
|
1593 | library), programatically (such as in test suites) or out-of-prcess | |
1597 | (typically over the network by remote frontends). |
|
1594 | (typically over the network by remote frontends). | |
1598 | """ |
|
1595 | """ | |
1599 | from IPython.core.completer import IPCompleter |
|
1596 | from IPython.core.completer import IPCompleter | |
1600 | from IPython.core.completerlib import (module_completer, |
|
1597 | from IPython.core.completerlib import (module_completer, | |
1601 | magic_run_completer, cd_completer) |
|
1598 | magic_run_completer, cd_completer) | |
1602 |
|
1599 | |||
1603 | self.Completer = IPCompleter(self, |
|
1600 | self.Completer = IPCompleter(self, | |
1604 | self.user_ns, |
|
1601 | self.user_ns, | |
1605 | self.user_global_ns, |
|
1602 | self.user_global_ns, | |
1606 | self.readline_omit__names, |
|
1603 | self.readline_omit__names, | |
1607 | self.alias_manager.alias_table, |
|
1604 | self.alias_manager.alias_table, | |
1608 | self.has_readline) |
|
1605 | self.has_readline) | |
1609 |
|
1606 | |||
1610 | # Add custom completers to the basic ones built into IPCompleter |
|
1607 | # Add custom completers to the basic ones built into IPCompleter | |
1611 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1608 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1612 | self.strdispatchers['complete_command'] = sdisp |
|
1609 | self.strdispatchers['complete_command'] = sdisp | |
1613 | self.Completer.custom_completers = sdisp |
|
1610 | self.Completer.custom_completers = sdisp | |
1614 |
|
1611 | |||
1615 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1612 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1616 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1613 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1617 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1614 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1618 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1615 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1619 |
|
1616 | |||
1620 | # Only configure readline if we truly are using readline. IPython can |
|
1617 | # Only configure readline if we truly are using readline. IPython can | |
1621 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1618 | # do tab-completion over the network, in GUIs, etc, where readline | |
1622 | # itself may be absent |
|
1619 | # itself may be absent | |
1623 | if self.has_readline: |
|
1620 | if self.has_readline: | |
1624 | self.set_readline_completer() |
|
1621 | self.set_readline_completer() | |
1625 |
|
1622 | |||
1626 | def complete(self, text, line=None, cursor_pos=None): |
|
1623 | def complete(self, text, line=None, cursor_pos=None): | |
1627 | """Return the completed text and a list of completions. |
|
1624 | """Return the completed text and a list of completions. | |
1628 |
|
1625 | |||
1629 | Parameters |
|
1626 | Parameters | |
1630 | ---------- |
|
1627 | ---------- | |
1631 |
|
1628 | |||
1632 | text : string |
|
1629 | text : string | |
1633 | A string of text to be completed on. It can be given as empty and |
|
1630 | A string of text to be completed on. It can be given as empty and | |
1634 | instead a line/position pair are given. In this case, the |
|
1631 | instead a line/position pair are given. In this case, the | |
1635 | completer itself will split the line like readline does. |
|
1632 | completer itself will split the line like readline does. | |
1636 |
|
1633 | |||
1637 | line : string, optional |
|
1634 | line : string, optional | |
1638 | The complete line that text is part of. |
|
1635 | The complete line that text is part of. | |
1639 |
|
1636 | |||
1640 | cursor_pos : int, optional |
|
1637 | cursor_pos : int, optional | |
1641 | The position of the cursor on the input line. |
|
1638 | The position of the cursor on the input line. | |
1642 |
|
1639 | |||
1643 | Returns |
|
1640 | Returns | |
1644 | ------- |
|
1641 | ------- | |
1645 | text : string |
|
1642 | text : string | |
1646 | The actual text that was completed. |
|
1643 | The actual text that was completed. | |
1647 |
|
1644 | |||
1648 | matches : list |
|
1645 | matches : list | |
1649 | A sorted list with all possible completions. |
|
1646 | A sorted list with all possible completions. | |
1650 |
|
1647 | |||
1651 | The optional arguments allow the completion to take more context into |
|
1648 | The optional arguments allow the completion to take more context into | |
1652 | account, and are part of the low-level completion API. |
|
1649 | account, and are part of the low-level completion API. | |
1653 |
|
1650 | |||
1654 | This is a wrapper around the completion mechanism, similar to what |
|
1651 | This is a wrapper around the completion mechanism, similar to what | |
1655 | readline does at the command line when the TAB key is hit. By |
|
1652 | readline does at the command line when the TAB key is hit. By | |
1656 | exposing it as a method, it can be used by other non-readline |
|
1653 | exposing it as a method, it can be used by other non-readline | |
1657 | environments (such as GUIs) for text completion. |
|
1654 | environments (such as GUIs) for text completion. | |
1658 |
|
1655 | |||
1659 | Simple usage example: |
|
1656 | Simple usage example: | |
1660 |
|
1657 | |||
1661 | In [1]: x = 'hello' |
|
1658 | In [1]: x = 'hello' | |
1662 |
|
1659 | |||
1663 | In [2]: _ip.complete('x.l') |
|
1660 | In [2]: _ip.complete('x.l') | |
1664 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1661 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1665 | """ |
|
1662 | """ | |
1666 |
|
1663 | |||
1667 | # Inject names into __builtin__ so we can complete on the added names. |
|
1664 | # Inject names into __builtin__ so we can complete on the added names. | |
1668 | with self.builtin_trap: |
|
1665 | with self.builtin_trap: | |
1669 | return self.Completer.complete(text, line, cursor_pos) |
|
1666 | return self.Completer.complete(text, line, cursor_pos) | |
1670 |
|
1667 | |||
1671 | def set_custom_completer(self, completer, pos=0): |
|
1668 | def set_custom_completer(self, completer, pos=0): | |
1672 | """Adds a new custom completer function. |
|
1669 | """Adds a new custom completer function. | |
1673 |
|
1670 | |||
1674 | The position argument (defaults to 0) is the index in the completers |
|
1671 | The position argument (defaults to 0) is the index in the completers | |
1675 | list where you want the completer to be inserted.""" |
|
1672 | list where you want the completer to be inserted.""" | |
1676 |
|
1673 | |||
1677 | newcomp = types.MethodType(completer,self.Completer) |
|
1674 | newcomp = types.MethodType(completer,self.Completer) | |
1678 | self.Completer.matchers.insert(pos,newcomp) |
|
1675 | self.Completer.matchers.insert(pos,newcomp) | |
1679 |
|
1676 | |||
1680 | def set_readline_completer(self): |
|
1677 | def set_readline_completer(self): | |
1681 | """Reset readline's completer to be our own.""" |
|
1678 | """Reset readline's completer to be our own.""" | |
1682 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1679 | self.readline.set_completer(self.Completer.rlcomplete) | |
1683 |
|
1680 | |||
1684 | def set_completer_frame(self, frame=None): |
|
1681 | def set_completer_frame(self, frame=None): | |
1685 | """Set the frame of the completer.""" |
|
1682 | """Set the frame of the completer.""" | |
1686 | if frame: |
|
1683 | if frame: | |
1687 | self.Completer.namespace = frame.f_locals |
|
1684 | self.Completer.namespace = frame.f_locals | |
1688 | self.Completer.global_namespace = frame.f_globals |
|
1685 | self.Completer.global_namespace = frame.f_globals | |
1689 | else: |
|
1686 | else: | |
1690 | self.Completer.namespace = self.user_ns |
|
1687 | self.Completer.namespace = self.user_ns | |
1691 | self.Completer.global_namespace = self.user_global_ns |
|
1688 | self.Completer.global_namespace = self.user_global_ns | |
1692 |
|
1689 | |||
1693 | #------------------------------------------------------------------------- |
|
1690 | #------------------------------------------------------------------------- | |
1694 | # Things related to magics |
|
1691 | # Things related to magics | |
1695 | #------------------------------------------------------------------------- |
|
1692 | #------------------------------------------------------------------------- | |
1696 |
|
1693 | |||
1697 | def init_magics(self): |
|
1694 | def init_magics(self): | |
1698 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1695 | # FIXME: Move the color initialization to the DisplayHook, which | |
1699 | # should be split into a prompt manager and displayhook. We probably |
|
1696 | # should be split into a prompt manager and displayhook. We probably | |
1700 | # even need a centralize colors management object. |
|
1697 | # even need a centralize colors management object. | |
1701 | self.magic_colors(self.colors) |
|
1698 | self.magic_colors(self.colors) | |
1702 | # History was moved to a separate module |
|
1699 | # History was moved to a separate module | |
1703 | from . import history |
|
1700 | from . import history | |
1704 | history.init_ipython(self) |
|
1701 | history.init_ipython(self) | |
1705 |
|
1702 | |||
1706 | def magic(self,arg_s): |
|
1703 | def magic(self,arg_s): | |
1707 | """Call a magic function by name. |
|
1704 | """Call a magic function by name. | |
1708 |
|
1705 | |||
1709 | Input: a string containing the name of the magic function to call and |
|
1706 | Input: a string containing the name of the magic function to call and | |
1710 | any additional arguments to be passed to the magic. |
|
1707 | any additional arguments to be passed to the magic. | |
1711 |
|
1708 | |||
1712 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1709 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1713 | prompt: |
|
1710 | prompt: | |
1714 |
|
1711 | |||
1715 | In[1]: %name -opt foo bar |
|
1712 | In[1]: %name -opt foo bar | |
1716 |
|
1713 | |||
1717 | To call a magic without arguments, simply use magic('name'). |
|
1714 | To call a magic without arguments, simply use magic('name'). | |
1718 |
|
1715 | |||
1719 | This provides a proper Python function to call IPython's magics in any |
|
1716 | This provides a proper Python function to call IPython's magics in any | |
1720 | valid Python code you can type at the interpreter, including loops and |
|
1717 | valid Python code you can type at the interpreter, including loops and | |
1721 | compound statements. |
|
1718 | compound statements. | |
1722 | """ |
|
1719 | """ | |
1723 | args = arg_s.split(' ',1) |
|
1720 | args = arg_s.split(' ',1) | |
1724 | magic_name = args[0] |
|
1721 | magic_name = args[0] | |
1725 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1722 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1726 |
|
1723 | |||
1727 | try: |
|
1724 | try: | |
1728 | magic_args = args[1] |
|
1725 | magic_args = args[1] | |
1729 | except IndexError: |
|
1726 | except IndexError: | |
1730 | magic_args = '' |
|
1727 | magic_args = '' | |
1731 | fn = getattr(self,'magic_'+magic_name,None) |
|
1728 | fn = getattr(self,'magic_'+magic_name,None) | |
1732 | if fn is None: |
|
1729 | if fn is None: | |
1733 | error("Magic function `%s` not found." % magic_name) |
|
1730 | error("Magic function `%s` not found." % magic_name) | |
1734 | else: |
|
1731 | else: | |
1735 | magic_args = self.var_expand(magic_args,1) |
|
1732 | magic_args = self.var_expand(magic_args,1) | |
1736 | with nested(self.builtin_trap,): |
|
1733 | with nested(self.builtin_trap,): | |
1737 | result = fn(magic_args) |
|
1734 | result = fn(magic_args) | |
1738 | return result |
|
1735 | return result | |
1739 |
|
1736 | |||
1740 | def define_magic(self, magicname, func): |
|
1737 | def define_magic(self, magicname, func): | |
1741 | """Expose own function as magic function for ipython |
|
1738 | """Expose own function as magic function for ipython | |
1742 |
|
1739 | |||
1743 | def foo_impl(self,parameter_s=''): |
|
1740 | def foo_impl(self,parameter_s=''): | |
1744 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1741 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1745 | print 'Magic function. Passed parameter is between < >:' |
|
1742 | print 'Magic function. Passed parameter is between < >:' | |
1746 | print '<%s>' % parameter_s |
|
1743 | print '<%s>' % parameter_s | |
1747 | print 'The self object is:',self |
|
1744 | print 'The self object is:',self | |
1748 |
|
1745 | |||
1749 | self.define_magic('foo',foo_impl) |
|
1746 | self.define_magic('foo',foo_impl) | |
1750 | """ |
|
1747 | """ | |
1751 |
|
1748 | |||
1752 | import new |
|
1749 | import new | |
1753 | im = types.MethodType(func,self) |
|
1750 | im = types.MethodType(func,self) | |
1754 | old = getattr(self, "magic_" + magicname, None) |
|
1751 | old = getattr(self, "magic_" + magicname, None) | |
1755 | setattr(self, "magic_" + magicname, im) |
|
1752 | setattr(self, "magic_" + magicname, im) | |
1756 | return old |
|
1753 | return old | |
1757 |
|
1754 | |||
1758 | #------------------------------------------------------------------------- |
|
1755 | #------------------------------------------------------------------------- | |
1759 | # Things related to macros |
|
1756 | # Things related to macros | |
1760 | #------------------------------------------------------------------------- |
|
1757 | #------------------------------------------------------------------------- | |
1761 |
|
1758 | |||
1762 | def define_macro(self, name, themacro): |
|
1759 | def define_macro(self, name, themacro): | |
1763 | """Define a new macro |
|
1760 | """Define a new macro | |
1764 |
|
1761 | |||
1765 | Parameters |
|
1762 | Parameters | |
1766 | ---------- |
|
1763 | ---------- | |
1767 | name : str |
|
1764 | name : str | |
1768 | The name of the macro. |
|
1765 | The name of the macro. | |
1769 | themacro : str or Macro |
|
1766 | themacro : str or Macro | |
1770 | The action to do upon invoking the macro. If a string, a new |
|
1767 | The action to do upon invoking the macro. If a string, a new | |
1771 | Macro object is created by passing the string to it. |
|
1768 | Macro object is created by passing the string to it. | |
1772 | """ |
|
1769 | """ | |
1773 |
|
1770 | |||
1774 | from IPython.core import macro |
|
1771 | from IPython.core import macro | |
1775 |
|
1772 | |||
1776 | if isinstance(themacro, basestring): |
|
1773 | if isinstance(themacro, basestring): | |
1777 | themacro = macro.Macro(themacro) |
|
1774 | themacro = macro.Macro(themacro) | |
1778 | if not isinstance(themacro, macro.Macro): |
|
1775 | if not isinstance(themacro, macro.Macro): | |
1779 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1776 | raise ValueError('A macro must be a string or a Macro instance.') | |
1780 | self.user_ns[name] = themacro |
|
1777 | self.user_ns[name] = themacro | |
1781 |
|
1778 | |||
1782 | #------------------------------------------------------------------------- |
|
1779 | #------------------------------------------------------------------------- | |
1783 | # Things related to the running of system commands |
|
1780 | # Things related to the running of system commands | |
1784 | #------------------------------------------------------------------------- |
|
1781 | #------------------------------------------------------------------------- | |
1785 |
|
1782 | |||
1786 | def system(self, cmd): |
|
1783 | def system(self, cmd): | |
1787 | """Call the given cmd in a subprocess. |
|
1784 | """Call the given cmd in a subprocess. | |
1788 |
|
1785 | |||
1789 | Parameters |
|
1786 | Parameters | |
1790 | ---------- |
|
1787 | ---------- | |
1791 | cmd : str |
|
1788 | cmd : str | |
1792 | Command to execute (can not end in '&', as bacground processes are |
|
1789 | Command to execute (can not end in '&', as bacground processes are | |
1793 | not supported. |
|
1790 | not supported. | |
1794 | """ |
|
1791 | """ | |
1795 | # We do not support backgrounding processes because we either use |
|
1792 | # We do not support backgrounding processes because we either use | |
1796 | # pexpect or pipes to read from. Users can always just call |
|
1793 | # pexpect or pipes to read from. Users can always just call | |
1797 | # os.system() if they really want a background process. |
|
1794 | # os.system() if they really want a background process. | |
1798 | if cmd.endswith('&'): |
|
1795 | if cmd.endswith('&'): | |
1799 | raise OSError("Background processes not supported.") |
|
1796 | raise OSError("Background processes not supported.") | |
1800 |
|
1797 | |||
1801 | return system(self.var_expand(cmd, depth=2)) |
|
1798 | return system(self.var_expand(cmd, depth=2)) | |
1802 |
|
1799 | |||
1803 | def getoutput(self, cmd, split=True): |
|
1800 | def getoutput(self, cmd, split=True): | |
1804 | """Get output (possibly including stderr) from a subprocess. |
|
1801 | """Get output (possibly including stderr) from a subprocess. | |
1805 |
|
1802 | |||
1806 | Parameters |
|
1803 | Parameters | |
1807 | ---------- |
|
1804 | ---------- | |
1808 | cmd : str |
|
1805 | cmd : str | |
1809 | Command to execute (can not end in '&', as background processes are |
|
1806 | Command to execute (can not end in '&', as background processes are | |
1810 | not supported. |
|
1807 | not supported. | |
1811 | split : bool, optional |
|
1808 | split : bool, optional | |
1812 |
|
1809 | |||
1813 | If True, split the output into an IPython SList. Otherwise, an |
|
1810 | If True, split the output into an IPython SList. Otherwise, an | |
1814 | IPython LSString is returned. These are objects similar to normal |
|
1811 | IPython LSString is returned. These are objects similar to normal | |
1815 | lists and strings, with a few convenience attributes for easier |
|
1812 | lists and strings, with a few convenience attributes for easier | |
1816 | manipulation of line-based output. You can use '?' on them for |
|
1813 | manipulation of line-based output. You can use '?' on them for | |
1817 | details. |
|
1814 | details. | |
1818 | """ |
|
1815 | """ | |
1819 | if cmd.endswith('&'): |
|
1816 | if cmd.endswith('&'): | |
1820 | raise OSError("Background processes not supported.") |
|
1817 | raise OSError("Background processes not supported.") | |
1821 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1818 | out = getoutput(self.var_expand(cmd, depth=2)) | |
1822 | if split: |
|
1819 | if split: | |
1823 | out = SList(out.splitlines()) |
|
1820 | out = SList(out.splitlines()) | |
1824 | else: |
|
1821 | else: | |
1825 | out = LSString(out) |
|
1822 | out = LSString(out) | |
1826 | return out |
|
1823 | return out | |
1827 |
|
1824 | |||
1828 | #------------------------------------------------------------------------- |
|
1825 | #------------------------------------------------------------------------- | |
1829 | # Things related to aliases |
|
1826 | # Things related to aliases | |
1830 | #------------------------------------------------------------------------- |
|
1827 | #------------------------------------------------------------------------- | |
1831 |
|
1828 | |||
1832 | def init_alias(self): |
|
1829 | def init_alias(self): | |
1833 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1830 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1834 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1831 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1835 |
|
1832 | |||
1836 | #------------------------------------------------------------------------- |
|
1833 | #------------------------------------------------------------------------- | |
1837 | # Things related to extensions and plugins |
|
1834 | # Things related to extensions and plugins | |
1838 | #------------------------------------------------------------------------- |
|
1835 | #------------------------------------------------------------------------- | |
1839 |
|
1836 | |||
1840 | def init_extension_manager(self): |
|
1837 | def init_extension_manager(self): | |
1841 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1838 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1842 |
|
1839 | |||
1843 | def init_plugin_manager(self): |
|
1840 | def init_plugin_manager(self): | |
1844 | self.plugin_manager = PluginManager(config=self.config) |
|
1841 | self.plugin_manager = PluginManager(config=self.config) | |
1845 |
|
1842 | |||
1846 | #------------------------------------------------------------------------- |
|
1843 | #------------------------------------------------------------------------- | |
1847 | # Things related to payloads |
|
1844 | # Things related to payloads | |
1848 | #------------------------------------------------------------------------- |
|
1845 | #------------------------------------------------------------------------- | |
1849 |
|
1846 | |||
1850 | def init_payload(self): |
|
1847 | def init_payload(self): | |
1851 | self.payload_manager = PayloadManager(config=self.config) |
|
1848 | self.payload_manager = PayloadManager(config=self.config) | |
1852 |
|
1849 | |||
1853 | #------------------------------------------------------------------------- |
|
1850 | #------------------------------------------------------------------------- | |
1854 | # Things related to the prefilter |
|
1851 | # Things related to the prefilter | |
1855 | #------------------------------------------------------------------------- |
|
1852 | #------------------------------------------------------------------------- | |
1856 |
|
1853 | |||
1857 | def init_prefilter(self): |
|
1854 | def init_prefilter(self): | |
1858 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1855 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1859 | # Ultimately this will be refactored in the new interpreter code, but |
|
1856 | # Ultimately this will be refactored in the new interpreter code, but | |
1860 | # for now, we should expose the main prefilter method (there's legacy |
|
1857 | # for now, we should expose the main prefilter method (there's legacy | |
1861 | # code out there that may rely on this). |
|
1858 | # code out there that may rely on this). | |
1862 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1859 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1863 |
|
1860 | |||
1864 | def auto_rewrite_input(self, cmd): |
|
1861 | def auto_rewrite_input(self, cmd): | |
1865 | """Print to the screen the rewritten form of the user's command. |
|
1862 | """Print to the screen the rewritten form of the user's command. | |
1866 |
|
1863 | |||
1867 | This shows visual feedback by rewriting input lines that cause |
|
1864 | This shows visual feedback by rewriting input lines that cause | |
1868 | automatic calling to kick in, like:: |
|
1865 | automatic calling to kick in, like:: | |
1869 |
|
1866 | |||
1870 | /f x |
|
1867 | /f x | |
1871 |
|
1868 | |||
1872 | into:: |
|
1869 | into:: | |
1873 |
|
1870 | |||
1874 | ------> f(x) |
|
1871 | ------> f(x) | |
1875 |
|
1872 | |||
1876 | after the user's input prompt. This helps the user understand that the |
|
1873 | after the user's input prompt. This helps the user understand that the | |
1877 | input line was transformed automatically by IPython. |
|
1874 | input line was transformed automatically by IPython. | |
1878 | """ |
|
1875 | """ | |
1879 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1876 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1880 |
|
1877 | |||
1881 | try: |
|
1878 | try: | |
1882 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1879 | # plain ascii works better w/ pyreadline, on some machines, so | |
1883 | # we use it and only print uncolored rewrite if we have unicode |
|
1880 | # we use it and only print uncolored rewrite if we have unicode | |
1884 | rw = str(rw) |
|
1881 | rw = str(rw) | |
1885 | print >> IPython.utils.io.Term.cout, rw |
|
1882 | print >> IPython.utils.io.Term.cout, rw | |
1886 | except UnicodeEncodeError: |
|
1883 | except UnicodeEncodeError: | |
1887 | print "------> " + cmd |
|
1884 | print "------> " + cmd | |
1888 |
|
1885 | |||
1889 | #------------------------------------------------------------------------- |
|
1886 | #------------------------------------------------------------------------- | |
1890 | # Things related to extracting values/expressions from kernel and user_ns |
|
1887 | # Things related to extracting values/expressions from kernel and user_ns | |
1891 | #------------------------------------------------------------------------- |
|
1888 | #------------------------------------------------------------------------- | |
1892 |
|
1889 | |||
1893 | def _simple_error(self): |
|
1890 | def _simple_error(self): | |
1894 | etype, value = sys.exc_info()[:2] |
|
1891 | etype, value = sys.exc_info()[:2] | |
1895 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1892 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1896 |
|
1893 | |||
1897 | def user_variables(self, names): |
|
1894 | def user_variables(self, names): | |
1898 | """Get a list of variable names from the user's namespace. |
|
1895 | """Get a list of variable names from the user's namespace. | |
1899 |
|
1896 | |||
1900 | Parameters |
|
1897 | Parameters | |
1901 | ---------- |
|
1898 | ---------- | |
1902 | names : list of strings |
|
1899 | names : list of strings | |
1903 | A list of names of variables to be read from the user namespace. |
|
1900 | A list of names of variables to be read from the user namespace. | |
1904 |
|
1901 | |||
1905 | Returns |
|
1902 | Returns | |
1906 | ------- |
|
1903 | ------- | |
1907 | A dict, keyed by the input names and with the repr() of each value. |
|
1904 | A dict, keyed by the input names and with the repr() of each value. | |
1908 | """ |
|
1905 | """ | |
1909 | out = {} |
|
1906 | out = {} | |
1910 | user_ns = self.user_ns |
|
1907 | user_ns = self.user_ns | |
1911 | for varname in names: |
|
1908 | for varname in names: | |
1912 | try: |
|
1909 | try: | |
1913 | value = repr(user_ns[varname]) |
|
1910 | value = repr(user_ns[varname]) | |
1914 | except: |
|
1911 | except: | |
1915 | value = self._simple_error() |
|
1912 | value = self._simple_error() | |
1916 | out[varname] = value |
|
1913 | out[varname] = value | |
1917 | return out |
|
1914 | return out | |
1918 |
|
1915 | |||
1919 | def user_expressions(self, expressions): |
|
1916 | def user_expressions(self, expressions): | |
1920 | """Evaluate a dict of expressions in the user's namespace. |
|
1917 | """Evaluate a dict of expressions in the user's namespace. | |
1921 |
|
1918 | |||
1922 | Parameters |
|
1919 | Parameters | |
1923 | ---------- |
|
1920 | ---------- | |
1924 | expressions : dict |
|
1921 | expressions : dict | |
1925 | A dict with string keys and string values. The expression values |
|
1922 | A dict with string keys and string values. The expression values | |
1926 | should be valid Python expressions, each of which will be evaluated |
|
1923 | should be valid Python expressions, each of which will be evaluated | |
1927 | in the user namespace. |
|
1924 | in the user namespace. | |
1928 |
|
1925 | |||
1929 | Returns |
|
1926 | Returns | |
1930 | ------- |
|
1927 | ------- | |
1931 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1928 | A dict, keyed like the input expressions dict, with the repr() of each | |
1932 | value. |
|
1929 | value. | |
1933 | """ |
|
1930 | """ | |
1934 | out = {} |
|
1931 | out = {} | |
1935 | user_ns = self.user_ns |
|
1932 | user_ns = self.user_ns | |
1936 | global_ns = self.user_global_ns |
|
1933 | global_ns = self.user_global_ns | |
1937 | for key, expr in expressions.iteritems(): |
|
1934 | for key, expr in expressions.iteritems(): | |
1938 | try: |
|
1935 | try: | |
1939 | value = repr(eval(expr, global_ns, user_ns)) |
|
1936 | value = repr(eval(expr, global_ns, user_ns)) | |
1940 | except: |
|
1937 | except: | |
1941 | value = self._simple_error() |
|
1938 | value = self._simple_error() | |
1942 | out[key] = value |
|
1939 | out[key] = value | |
1943 | return out |
|
1940 | return out | |
1944 |
|
1941 | |||
1945 | #------------------------------------------------------------------------- |
|
1942 | #------------------------------------------------------------------------- | |
1946 | # Things related to the running of code |
|
1943 | # Things related to the running of code | |
1947 | #------------------------------------------------------------------------- |
|
1944 | #------------------------------------------------------------------------- | |
1948 |
|
1945 | |||
1949 | def ex(self, cmd): |
|
1946 | def ex(self, cmd): | |
1950 | """Execute a normal python statement in user namespace.""" |
|
1947 | """Execute a normal python statement in user namespace.""" | |
1951 | with nested(self.builtin_trap,): |
|
1948 | with nested(self.builtin_trap,): | |
1952 | exec cmd in self.user_global_ns, self.user_ns |
|
1949 | exec cmd in self.user_global_ns, self.user_ns | |
1953 |
|
1950 | |||
1954 | def ev(self, expr): |
|
1951 | def ev(self, expr): | |
1955 | """Evaluate python expression expr in user namespace. |
|
1952 | """Evaluate python expression expr in user namespace. | |
1956 |
|
1953 | |||
1957 | Returns the result of evaluation |
|
1954 | Returns the result of evaluation | |
1958 | """ |
|
1955 | """ | |
1959 | with nested(self.builtin_trap,): |
|
1956 | with nested(self.builtin_trap,): | |
1960 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1957 | return eval(expr, self.user_global_ns, self.user_ns) | |
1961 |
|
1958 | |||
1962 | def safe_execfile(self, fname, *where, **kw): |
|
1959 | def safe_execfile(self, fname, *where, **kw): | |
1963 | """A safe version of the builtin execfile(). |
|
1960 | """A safe version of the builtin execfile(). | |
1964 |
|
1961 | |||
1965 | This version will never throw an exception, but instead print |
|
1962 | This version will never throw an exception, but instead print | |
1966 | helpful error messages to the screen. This only works on pure |
|
1963 | helpful error messages to the screen. This only works on pure | |
1967 | Python files with the .py extension. |
|
1964 | Python files with the .py extension. | |
1968 |
|
1965 | |||
1969 | Parameters |
|
1966 | Parameters | |
1970 | ---------- |
|
1967 | ---------- | |
1971 | fname : string |
|
1968 | fname : string | |
1972 | The name of the file to be executed. |
|
1969 | The name of the file to be executed. | |
1973 | where : tuple |
|
1970 | where : tuple | |
1974 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1971 | One or two namespaces, passed to execfile() as (globals,locals). | |
1975 | If only one is given, it is passed as both. |
|
1972 | If only one is given, it is passed as both. | |
1976 | exit_ignore : bool (False) |
|
1973 | exit_ignore : bool (False) | |
1977 | If True, then silence SystemExit for non-zero status (it is always |
|
1974 | If True, then silence SystemExit for non-zero status (it is always | |
1978 | silenced for zero status, as it is so common). |
|
1975 | silenced for zero status, as it is so common). | |
1979 | """ |
|
1976 | """ | |
1980 | kw.setdefault('exit_ignore', False) |
|
1977 | kw.setdefault('exit_ignore', False) | |
1981 |
|
1978 | |||
1982 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1979 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1983 |
|
1980 | |||
1984 | # Make sure we have a .py file |
|
1981 | # Make sure we have a .py file | |
1985 | if not fname.endswith('.py'): |
|
1982 | if not fname.endswith('.py'): | |
1986 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1983 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1987 |
|
1984 | |||
1988 | # Make sure we can open the file |
|
1985 | # Make sure we can open the file | |
1989 | try: |
|
1986 | try: | |
1990 | with open(fname) as thefile: |
|
1987 | with open(fname) as thefile: | |
1991 | pass |
|
1988 | pass | |
1992 | except: |
|
1989 | except: | |
1993 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1990 | warn('Could not open file <%s> for safe execution.' % fname) | |
1994 | return |
|
1991 | return | |
1995 |
|
1992 | |||
1996 | # Find things also in current directory. This is needed to mimic the |
|
1993 | # Find things also in current directory. This is needed to mimic the | |
1997 | # behavior of running a script from the system command line, where |
|
1994 | # behavior of running a script from the system command line, where | |
1998 | # Python inserts the script's directory into sys.path |
|
1995 | # Python inserts the script's directory into sys.path | |
1999 | dname = os.path.dirname(fname) |
|
1996 | dname = os.path.dirname(fname) | |
2000 |
|
1997 | |||
2001 | with prepended_to_syspath(dname): |
|
1998 | with prepended_to_syspath(dname): | |
2002 | try: |
|
1999 | try: | |
2003 | execfile(fname,*where) |
|
2000 | execfile(fname,*where) | |
2004 | except SystemExit, status: |
|
2001 | except SystemExit, status: | |
2005 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2002 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2006 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2003 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2007 | # these are considered normal by the OS: |
|
2004 | # these are considered normal by the OS: | |
2008 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2005 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2009 | # 0 |
|
2006 | # 0 | |
2010 | # > python -c'import sys;sys.exit()'; echo $? |
|
2007 | # > python -c'import sys;sys.exit()'; echo $? | |
2011 | # 0 |
|
2008 | # 0 | |
2012 | # For other exit status, we show the exception unless |
|
2009 | # For other exit status, we show the exception unless | |
2013 | # explicitly silenced, but only in short form. |
|
2010 | # explicitly silenced, but only in short form. | |
2014 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2011 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2015 | self.showtraceback(exception_only=True) |
|
2012 | self.showtraceback(exception_only=True) | |
2016 | except: |
|
2013 | except: | |
2017 | self.showtraceback() |
|
2014 | self.showtraceback() | |
2018 |
|
2015 | |||
2019 | def safe_execfile_ipy(self, fname): |
|
2016 | def safe_execfile_ipy(self, fname): | |
2020 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2017 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2021 |
|
2018 | |||
2022 | Parameters |
|
2019 | Parameters | |
2023 | ---------- |
|
2020 | ---------- | |
2024 | fname : str |
|
2021 | fname : str | |
2025 | The name of the file to execute. The filename must have a |
|
2022 | The name of the file to execute. The filename must have a | |
2026 | .ipy extension. |
|
2023 | .ipy extension. | |
2027 | """ |
|
2024 | """ | |
2028 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2025 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2029 |
|
2026 | |||
2030 | # Make sure we have a .py file |
|
2027 | # Make sure we have a .py file | |
2031 | if not fname.endswith('.ipy'): |
|
2028 | if not fname.endswith('.ipy'): | |
2032 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2029 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2033 |
|
2030 | |||
2034 | # Make sure we can open the file |
|
2031 | # Make sure we can open the file | |
2035 | try: |
|
2032 | try: | |
2036 | with open(fname) as thefile: |
|
2033 | with open(fname) as thefile: | |
2037 | pass |
|
2034 | pass | |
2038 | except: |
|
2035 | except: | |
2039 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2036 | warn('Could not open file <%s> for safe execution.' % fname) | |
2040 | return |
|
2037 | return | |
2041 |
|
2038 | |||
2042 | # Find things also in current directory. This is needed to mimic the |
|
2039 | # Find things also in current directory. This is needed to mimic the | |
2043 | # behavior of running a script from the system command line, where |
|
2040 | # behavior of running a script from the system command line, where | |
2044 | # Python inserts the script's directory into sys.path |
|
2041 | # Python inserts the script's directory into sys.path | |
2045 | dname = os.path.dirname(fname) |
|
2042 | dname = os.path.dirname(fname) | |
2046 |
|
2043 | |||
2047 | with prepended_to_syspath(dname): |
|
2044 | with prepended_to_syspath(dname): | |
2048 | try: |
|
2045 | try: | |
2049 | with open(fname) as thefile: |
|
2046 | with open(fname) as thefile: | |
2050 | # self.run_cell currently captures all exceptions |
|
2047 | # self.run_cell currently captures all exceptions | |
2051 | # raised in user code. It would be nice if there were |
|
2048 | # raised in user code. It would be nice if there were | |
2052 | # versions of runlines, execfile that did raise, so |
|
2049 | # versions of runlines, execfile that did raise, so | |
2053 | # we could catch the errors. |
|
2050 | # we could catch the errors. | |
2054 | self.run_cell(thefile.read()) |
|
2051 | self.run_cell(thefile.read()) | |
2055 | except: |
|
2052 | except: | |
2056 | self.showtraceback() |
|
2053 | self.showtraceback() | |
2057 | warn('Unknown failure executing file: <%s>' % fname) |
|
2054 | warn('Unknown failure executing file: <%s>' % fname) | |
2058 |
|
2055 | |||
2059 | def run_cell(self, cell): |
|
2056 | def run_cell(self, cell): | |
2060 | """Run the contents of an entire multiline 'cell' of code. |
|
2057 | """Run the contents of an entire multiline 'cell' of code. | |
2061 |
|
2058 | |||
2062 | The cell is split into separate blocks which can be executed |
|
2059 | The cell is split into separate blocks which can be executed | |
2063 | individually. Then, based on how many blocks there are, they are |
|
2060 | individually. Then, based on how many blocks there are, they are | |
2064 | executed as follows: |
|
2061 | executed as follows: | |
2065 |
|
2062 | |||
2066 | - A single block: 'single' mode. |
|
2063 | - A single block: 'single' mode. | |
2067 |
|
2064 | |||
2068 | If there's more than one block, it depends: |
|
2065 | If there's more than one block, it depends: | |
2069 |
|
2066 | |||
2070 | - if the last one is no more than two lines long, run all but the last |
|
2067 | - if the last one is no more than two lines long, run all but the last | |
2071 | in 'exec' mode and the very last one in 'single' mode. This makes it |
|
2068 | in 'exec' mode and the very last one in 'single' mode. This makes it | |
2072 | easy to type simple expressions at the end to see computed values. - |
|
2069 | easy to type simple expressions at the end to see computed values. - | |
2073 | otherwise (last one is also multiline), run all in 'exec' mode |
|
2070 | otherwise (last one is also multiline), run all in 'exec' mode | |
2074 |
|
2071 | |||
2075 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2072 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2076 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2073 | results are displayed and output prompts are computed. In 'exec' mode, | |
2077 | no results are displayed unless :func:`print` is called explicitly; |
|
2074 | no results are displayed unless :func:`print` is called explicitly; | |
2078 | this mode is more akin to running a script. |
|
2075 | this mode is more akin to running a script. | |
2079 |
|
2076 | |||
2080 | Parameters |
|
2077 | Parameters | |
2081 | ---------- |
|
2078 | ---------- | |
2082 | cell : str |
|
2079 | cell : str | |
2083 | A single or multiline string. |
|
2080 | A single or multiline string. | |
2084 | """ |
|
2081 | """ | |
2085 |
|
2082 | |||
2086 | # We need to break up the input into executable blocks that can be run |
|
2083 | # We need to break up the input into executable blocks that can be run | |
2087 | # in 'single' mode, to provide comfortable user behavior. |
|
2084 | # in 'single' mode, to provide comfortable user behavior. | |
2088 | blocks = self.input_splitter.split_blocks(cell) |
|
2085 | blocks = self.input_splitter.split_blocks(cell) | |
2089 |
|
2086 | |||
2090 | if not blocks: |
|
2087 | if not blocks: | |
2091 | return |
|
2088 | return | |
2092 |
|
2089 | |||
2093 | # Store the 'ipython' version of the cell as well, since that's what |
|
2090 | # Store the 'ipython' version of the cell as well, since that's what | |
2094 | # needs to go into the translated history and get executed (the |
|
2091 | # needs to go into the translated history and get executed (the | |
2095 | # original cell may contain non-python syntax). |
|
2092 | # original cell may contain non-python syntax). | |
2096 | ipy_cell = ''.join(blocks) |
|
2093 | ipy_cell = ''.join(blocks) | |
2097 |
|
2094 | |||
2098 | # Store raw and processed history |
|
2095 | # Store raw and processed history | |
2099 | self.history_manager.store_inputs(ipy_cell, cell) |
|
2096 | self.history_manager.store_inputs(ipy_cell, cell) | |
2100 |
|
2097 | |||
2101 | self.logger.log(ipy_cell, cell) |
|
2098 | self.logger.log(ipy_cell, cell) | |
2102 | # dbg code!!! |
|
2099 | # dbg code!!! | |
2103 | if 0: |
|
2100 | if 0: | |
2104 | def myapp(self, val): # dbg |
|
2101 | def myapp(self, val): # dbg | |
2105 | import traceback as tb |
|
2102 | import traceback as tb | |
2106 | stack = ''.join(tb.format_stack()) |
|
2103 | stack = ''.join(tb.format_stack()) | |
2107 | print 'Value:', val |
|
2104 | print 'Value:', val | |
2108 | print 'Stack:\n', stack |
|
2105 | print 'Stack:\n', stack | |
2109 | list.append(self, val) |
|
2106 | list.append(self, val) | |
2110 |
|
2107 | |||
2111 | import new |
|
2108 | import new | |
2112 |
self.input_hist.append = types.MethodType(myapp, |
|
2109 | self.history_manager.input_hist_parsed.append = types.MethodType(myapp, | |
|
2110 | self.history_manager.input_hist_parsed) | |||
2113 | # End dbg |
|
2111 | # End dbg | |
2114 |
|
2112 | |||
2115 | # All user code execution must happen with our context managers active |
|
2113 | # All user code execution must happen with our context managers active | |
2116 | with nested(self.builtin_trap, self.display_trap): |
|
2114 | with nested(self.builtin_trap, self.display_trap): | |
2117 |
|
2115 | |||
2118 | # Single-block input should behave like an interactive prompt |
|
2116 | # Single-block input should behave like an interactive prompt | |
2119 | if len(blocks) == 1: |
|
2117 | if len(blocks) == 1: | |
2120 | # since we return here, we need to update the execution count |
|
2118 | # since we return here, we need to update the execution count | |
2121 | out = self.run_one_block(blocks[0]) |
|
2119 | out = self.run_one_block(blocks[0]) | |
2122 | self.execution_count += 1 |
|
2120 | self.execution_count += 1 | |
2123 | return out |
|
2121 | return out | |
2124 |
|
2122 | |||
2125 | # In multi-block input, if the last block is a simple (one-two |
|
2123 | # In multi-block input, if the last block is a simple (one-two | |
2126 | # lines) expression, run it in single mode so it produces output. |
|
2124 | # lines) expression, run it in single mode so it produces output. | |
2127 | # Otherwise just feed the whole thing to run_code. This seems like |
|
2125 | # Otherwise just feed the whole thing to run_code. This seems like | |
2128 | # a reasonable usability design. |
|
2126 | # a reasonable usability design. | |
2129 | last = blocks[-1] |
|
2127 | last = blocks[-1] | |
2130 | last_nlines = len(last.splitlines()) |
|
2128 | last_nlines = len(last.splitlines()) | |
2131 |
|
2129 | |||
2132 | # Note: below, whenever we call run_code, we must sync history |
|
2130 | # Note: below, whenever we call run_code, we must sync history | |
2133 | # ourselves, because run_code is NOT meant to manage history at all. |
|
2131 | # ourselves, because run_code is NOT meant to manage history at all. | |
2134 | if last_nlines < 2: |
|
2132 | if last_nlines < 2: | |
2135 | # Here we consider the cell split between 'body' and 'last', |
|
2133 | # Here we consider the cell split between 'body' and 'last', | |
2136 | # store all history and execute 'body', and if successful, then |
|
2134 | # store all history and execute 'body', and if successful, then | |
2137 | # proceed to execute 'last'. |
|
2135 | # proceed to execute 'last'. | |
2138 |
|
2136 | |||
2139 | # Get the main body to run as a cell |
|
2137 | # Get the main body to run as a cell | |
2140 | ipy_body = ''.join(blocks[:-1]) |
|
2138 | ipy_body = ''.join(blocks[:-1]) | |
2141 | retcode = self.run_source(ipy_body, symbol='exec', |
|
2139 | retcode = self.run_source(ipy_body, symbol='exec', | |
2142 | post_execute=False) |
|
2140 | post_execute=False) | |
2143 | if retcode==0: |
|
2141 | if retcode==0: | |
2144 | # And the last expression via runlines so it produces output |
|
2142 | # And the last expression via runlines so it produces output | |
2145 | self.run_one_block(last) |
|
2143 | self.run_one_block(last) | |
2146 | else: |
|
2144 | else: | |
2147 | # Run the whole cell as one entity, storing both raw and |
|
2145 | # Run the whole cell as one entity, storing both raw and | |
2148 | # processed input in history |
|
2146 | # processed input in history | |
2149 | self.run_source(ipy_cell, symbol='exec') |
|
2147 | self.run_source(ipy_cell, symbol='exec') | |
2150 |
|
2148 | |||
2151 | # Each cell is a *single* input, regardless of how many lines it has |
|
2149 | # Each cell is a *single* input, regardless of how many lines it has | |
2152 | self.execution_count += 1 |
|
2150 | self.execution_count += 1 | |
2153 |
|
2151 | |||
2154 | def run_one_block(self, block): |
|
2152 | def run_one_block(self, block): | |
2155 | """Run a single interactive block. |
|
2153 | """Run a single interactive block. | |
2156 |
|
2154 | |||
2157 | If the block is single-line, dynamic transformations are applied to it |
|
2155 | If the block is single-line, dynamic transformations are applied to it | |
2158 | (like automagics, autocall and alias recognition). |
|
2156 | (like automagics, autocall and alias recognition). | |
2159 | """ |
|
2157 | """ | |
2160 | if len(block.splitlines()) <= 1: |
|
2158 | if len(block.splitlines()) <= 1: | |
2161 | out = self.run_single_line(block) |
|
2159 | out = self.run_single_line(block) | |
2162 | else: |
|
2160 | else: | |
2163 | out = self.run_code(block) |
|
2161 | out = self.run_code(block) | |
2164 | return out |
|
2162 | return out | |
2165 |
|
2163 | |||
2166 | def run_single_line(self, line): |
|
2164 | def run_single_line(self, line): | |
2167 | """Run a single-line interactive statement. |
|
2165 | """Run a single-line interactive statement. | |
2168 |
|
2166 | |||
2169 | This assumes the input has been transformed to IPython syntax by |
|
2167 | This assumes the input has been transformed to IPython syntax by | |
2170 | applying all static transformations (those with an explicit prefix like |
|
2168 | applying all static transformations (those with an explicit prefix like | |
2171 | % or !), but it will further try to apply the dynamic ones. |
|
2169 | % or !), but it will further try to apply the dynamic ones. | |
2172 |
|
2170 | |||
2173 | It does not update history. |
|
2171 | It does not update history. | |
2174 | """ |
|
2172 | """ | |
2175 | tline = self.prefilter_manager.prefilter_line(line) |
|
2173 | tline = self.prefilter_manager.prefilter_line(line) | |
2176 | return self.run_source(tline) |
|
2174 | return self.run_source(tline) | |
2177 |
|
2175 | |||
2178 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2176 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2179 | # input logic has been 100% moved to frontends and is stable. |
|
2177 | # input logic has been 100% moved to frontends and is stable. | |
2180 | def runlines(self, lines, clean=False): |
|
2178 | def runlines(self, lines, clean=False): | |
2181 | """Run a string of one or more lines of source. |
|
2179 | """Run a string of one or more lines of source. | |
2182 |
|
2180 | |||
2183 | This method is capable of running a string containing multiple source |
|
2181 | This method is capable of running a string containing multiple source | |
2184 | lines, as if they had been entered at the IPython prompt. Since it |
|
2182 | lines, as if they had been entered at the IPython prompt. Since it | |
2185 | exposes IPython's processing machinery, the given strings can contain |
|
2183 | exposes IPython's processing machinery, the given strings can contain | |
2186 | magic calls (%magic), special shell access (!cmd), etc. |
|
2184 | magic calls (%magic), special shell access (!cmd), etc. | |
2187 | """ |
|
2185 | """ | |
2188 |
|
2186 | |||
2189 | if isinstance(lines, (list, tuple)): |
|
2187 | if isinstance(lines, (list, tuple)): | |
2190 | lines = '\n'.join(lines) |
|
2188 | lines = '\n'.join(lines) | |
2191 |
|
2189 | |||
2192 | if clean: |
|
2190 | if clean: | |
2193 | lines = self._cleanup_ipy_script(lines) |
|
2191 | lines = self._cleanup_ipy_script(lines) | |
2194 |
|
2192 | |||
2195 | # We must start with a clean buffer, in case this is run from an |
|
2193 | # We must start with a clean buffer, in case this is run from an | |
2196 | # interactive IPython session (via a magic, for example). |
|
2194 | # interactive IPython session (via a magic, for example). | |
2197 | self.reset_buffer() |
|
2195 | self.reset_buffer() | |
2198 | lines = lines.splitlines() |
|
2196 | lines = lines.splitlines() | |
2199 |
|
2197 | |||
2200 | # Since we will prefilter all lines, store the user's raw input too |
|
2198 | # Since we will prefilter all lines, store the user's raw input too | |
2201 | # before we apply any transformations |
|
2199 | # before we apply any transformations | |
2202 | self.buffer_raw[:] = [ l+'\n' for l in lines] |
|
2200 | self.buffer_raw[:] = [ l+'\n' for l in lines] | |
2203 |
|
2201 | |||
2204 | more = False |
|
2202 | more = False | |
2205 | prefilter_lines = self.prefilter_manager.prefilter_lines |
|
2203 | prefilter_lines = self.prefilter_manager.prefilter_lines | |
2206 | with nested(self.builtin_trap, self.display_trap): |
|
2204 | with nested(self.builtin_trap, self.display_trap): | |
2207 | for line in lines: |
|
2205 | for line in lines: | |
2208 | # skip blank lines so we don't mess up the prompt counter, but |
|
2206 | # skip blank lines so we don't mess up the prompt counter, but | |
2209 | # do NOT skip even a blank line if we are in a code block (more |
|
2207 | # do NOT skip even a blank line if we are in a code block (more | |
2210 | # is true) |
|
2208 | # is true) | |
2211 |
|
2209 | |||
2212 | if line or more: |
|
2210 | if line or more: | |
2213 | more = self.push_line(prefilter_lines(line, more)) |
|
2211 | more = self.push_line(prefilter_lines(line, more)) | |
2214 | # IPython's run_source returns None if there was an error |
|
2212 | # IPython's run_source returns None if there was an error | |
2215 | # compiling the code. This allows us to stop processing |
|
2213 | # compiling the code. This allows us to stop processing | |
2216 | # right away, so the user gets the error message at the |
|
2214 | # right away, so the user gets the error message at the | |
2217 | # right place. |
|
2215 | # right place. | |
2218 | if more is None: |
|
2216 | if more is None: | |
2219 | break |
|
2217 | break | |
2220 | # final newline in case the input didn't have it, so that the code |
|
2218 | # final newline in case the input didn't have it, so that the code | |
2221 | # actually does get executed |
|
2219 | # actually does get executed | |
2222 | if more: |
|
2220 | if more: | |
2223 | self.push_line('\n') |
|
2221 | self.push_line('\n') | |
2224 |
|
2222 | |||
2225 | def run_source(self, source, filename=None, |
|
2223 | def run_source(self, source, filename=None, | |
2226 | symbol='single', post_execute=True): |
|
2224 | symbol='single', post_execute=True): | |
2227 | """Compile and run some source in the interpreter. |
|
2225 | """Compile and run some source in the interpreter. | |
2228 |
|
2226 | |||
2229 | Arguments are as for compile_command(). |
|
2227 | Arguments are as for compile_command(). | |
2230 |
|
2228 | |||
2231 | One several things can happen: |
|
2229 | One several things can happen: | |
2232 |
|
2230 | |||
2233 | 1) The input is incorrect; compile_command() raised an |
|
2231 | 1) The input is incorrect; compile_command() raised an | |
2234 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2232 | exception (SyntaxError or OverflowError). A syntax traceback | |
2235 | will be printed by calling the showsyntaxerror() method. |
|
2233 | will be printed by calling the showsyntaxerror() method. | |
2236 |
|
2234 | |||
2237 | 2) The input is incomplete, and more input is required; |
|
2235 | 2) The input is incomplete, and more input is required; | |
2238 | compile_command() returned None. Nothing happens. |
|
2236 | compile_command() returned None. Nothing happens. | |
2239 |
|
2237 | |||
2240 | 3) The input is complete; compile_command() returned a code |
|
2238 | 3) The input is complete; compile_command() returned a code | |
2241 | object. The code is executed by calling self.run_code() (which |
|
2239 | object. The code is executed by calling self.run_code() (which | |
2242 | also handles run-time exceptions, except for SystemExit). |
|
2240 | also handles run-time exceptions, except for SystemExit). | |
2243 |
|
2241 | |||
2244 | The return value is: |
|
2242 | The return value is: | |
2245 |
|
2243 | |||
2246 | - True in case 2 |
|
2244 | - True in case 2 | |
2247 |
|
2245 | |||
2248 | - False in the other cases, unless an exception is raised, where |
|
2246 | - False in the other cases, unless an exception is raised, where | |
2249 | None is returned instead. This can be used by external callers to |
|
2247 | None is returned instead. This can be used by external callers to | |
2250 | know whether to continue feeding input or not. |
|
2248 | know whether to continue feeding input or not. | |
2251 |
|
2249 | |||
2252 | The return value can be used to decide whether to use sys.ps1 or |
|
2250 | The return value can be used to decide whether to use sys.ps1 or | |
2253 | sys.ps2 to prompt the next line.""" |
|
2251 | sys.ps2 to prompt the next line.""" | |
2254 |
|
2252 | |||
2255 | # We need to ensure that the source is unicode from here on. |
|
2253 | # We need to ensure that the source is unicode from here on. | |
2256 | if type(source)==str: |
|
2254 | if type(source)==str: | |
2257 | usource = source.decode(self.stdin_encoding) |
|
2255 | usource = source.decode(self.stdin_encoding) | |
2258 | else: |
|
2256 | else: | |
2259 | usource = source |
|
2257 | usource = source | |
2260 |
|
2258 | |||
2261 | if 0: # dbg |
|
2259 | if 0: # dbg | |
2262 | print 'Source:', repr(source) # dbg |
|
2260 | print 'Source:', repr(source) # dbg | |
2263 | print 'USource:', repr(usource) # dbg |
|
2261 | print 'USource:', repr(usource) # dbg | |
2264 | print 'type:', type(source) # dbg |
|
2262 | print 'type:', type(source) # dbg | |
2265 | print 'encoding', self.stdin_encoding # dbg |
|
2263 | print 'encoding', self.stdin_encoding # dbg | |
2266 |
|
2264 | |||
2267 | try: |
|
2265 | try: | |
2268 | code = self.compile(usource, symbol, self.execution_count) |
|
2266 | code = self.compile(usource, symbol, self.execution_count) | |
2269 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2267 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2270 | # Case 1 |
|
2268 | # Case 1 | |
2271 | self.showsyntaxerror(filename) |
|
2269 | self.showsyntaxerror(filename) | |
2272 | return None |
|
2270 | return None | |
2273 |
|
2271 | |||
2274 | if code is None: |
|
2272 | if code is None: | |
2275 | # Case 2 |
|
2273 | # Case 2 | |
2276 | return True |
|
2274 | return True | |
2277 |
|
2275 | |||
2278 | # Case 3 |
|
2276 | # Case 3 | |
2279 | # We store the code object so that threaded shells and |
|
2277 | # We store the code object so that threaded shells and | |
2280 | # custom exception handlers can access all this info if needed. |
|
2278 | # custom exception handlers can access all this info if needed. | |
2281 | # The source corresponding to this can be obtained from the |
|
2279 | # The source corresponding to this can be obtained from the | |
2282 | # buffer attribute as '\n'.join(self.buffer). |
|
2280 | # buffer attribute as '\n'.join(self.buffer). | |
2283 | self.code_to_run = code |
|
2281 | self.code_to_run = code | |
2284 | # now actually execute the code object |
|
2282 | # now actually execute the code object | |
2285 | if self.run_code(code, post_execute) == 0: |
|
2283 | if self.run_code(code, post_execute) == 0: | |
2286 | return False |
|
2284 | return False | |
2287 | else: |
|
2285 | else: | |
2288 | return None |
|
2286 | return None | |
2289 |
|
2287 | |||
2290 | # For backwards compatibility |
|
2288 | # For backwards compatibility | |
2291 | runsource = run_source |
|
2289 | runsource = run_source | |
2292 |
|
2290 | |||
2293 | def run_code(self, code_obj, post_execute=True): |
|
2291 | def run_code(self, code_obj, post_execute=True): | |
2294 | """Execute a code object. |
|
2292 | """Execute a code object. | |
2295 |
|
2293 | |||
2296 | When an exception occurs, self.showtraceback() is called to display a |
|
2294 | When an exception occurs, self.showtraceback() is called to display a | |
2297 | traceback. |
|
2295 | traceback. | |
2298 |
|
2296 | |||
2299 | Return value: a flag indicating whether the code to be run completed |
|
2297 | Return value: a flag indicating whether the code to be run completed | |
2300 | successfully: |
|
2298 | successfully: | |
2301 |
|
2299 | |||
2302 | - 0: successful execution. |
|
2300 | - 0: successful execution. | |
2303 | - 1: an error occurred. |
|
2301 | - 1: an error occurred. | |
2304 | """ |
|
2302 | """ | |
2305 |
|
2303 | |||
2306 | # Set our own excepthook in case the user code tries to call it |
|
2304 | # Set our own excepthook in case the user code tries to call it | |
2307 | # directly, so that the IPython crash handler doesn't get triggered |
|
2305 | # directly, so that the IPython crash handler doesn't get triggered | |
2308 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2306 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2309 |
|
2307 | |||
2310 | # we save the original sys.excepthook in the instance, in case config |
|
2308 | # we save the original sys.excepthook in the instance, in case config | |
2311 | # code (such as magics) needs access to it. |
|
2309 | # code (such as magics) needs access to it. | |
2312 | self.sys_excepthook = old_excepthook |
|
2310 | self.sys_excepthook = old_excepthook | |
2313 | outflag = 1 # happens in more places, so it's easier as default |
|
2311 | outflag = 1 # happens in more places, so it's easier as default | |
2314 | try: |
|
2312 | try: | |
2315 | try: |
|
2313 | try: | |
2316 | self.hooks.pre_run_code_hook() |
|
2314 | self.hooks.pre_run_code_hook() | |
2317 | #rprint('Running code') # dbg |
|
2315 | #rprint('Running code') # dbg | |
2318 | exec code_obj in self.user_global_ns, self.user_ns |
|
2316 | exec code_obj in self.user_global_ns, self.user_ns | |
2319 | finally: |
|
2317 | finally: | |
2320 | # Reset our crash handler in place |
|
2318 | # Reset our crash handler in place | |
2321 | sys.excepthook = old_excepthook |
|
2319 | sys.excepthook = old_excepthook | |
2322 | except SystemExit: |
|
2320 | except SystemExit: | |
2323 | self.reset_buffer() |
|
2321 | self.reset_buffer() | |
2324 | self.showtraceback(exception_only=True) |
|
2322 | self.showtraceback(exception_only=True) | |
2325 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2323 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2326 | except self.custom_exceptions: |
|
2324 | except self.custom_exceptions: | |
2327 | etype,value,tb = sys.exc_info() |
|
2325 | etype,value,tb = sys.exc_info() | |
2328 | self.CustomTB(etype,value,tb) |
|
2326 | self.CustomTB(etype,value,tb) | |
2329 | except: |
|
2327 | except: | |
2330 | self.showtraceback() |
|
2328 | self.showtraceback() | |
2331 | else: |
|
2329 | else: | |
2332 | outflag = 0 |
|
2330 | outflag = 0 | |
2333 | if softspace(sys.stdout, 0): |
|
2331 | if softspace(sys.stdout, 0): | |
2334 |
|
2332 | |||
2335 |
|
2333 | |||
2336 | # Execute any registered post-execution functions. Here, any errors |
|
2334 | # Execute any registered post-execution functions. Here, any errors | |
2337 | # are reported only minimally and just on the terminal, because the |
|
2335 | # are reported only minimally and just on the terminal, because the | |
2338 | # main exception channel may be occupied with a user traceback. |
|
2336 | # main exception channel may be occupied with a user traceback. | |
2339 | # FIXME: we need to think this mechanism a little more carefully. |
|
2337 | # FIXME: we need to think this mechanism a little more carefully. | |
2340 | if post_execute: |
|
2338 | if post_execute: | |
2341 | for func in self._post_execute: |
|
2339 | for func in self._post_execute: | |
2342 | try: |
|
2340 | try: | |
2343 | func() |
|
2341 | func() | |
2344 | except: |
|
2342 | except: | |
2345 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2343 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2346 | func |
|
2344 | func | |
2347 | print >> io.Term.cout, head |
|
2345 | print >> io.Term.cout, head | |
2348 | print >> io.Term.cout, self._simple_error() |
|
2346 | print >> io.Term.cout, self._simple_error() | |
2349 | print >> io.Term.cout, 'Removing from post_execute' |
|
2347 | print >> io.Term.cout, 'Removing from post_execute' | |
2350 | self._post_execute.remove(func) |
|
2348 | self._post_execute.remove(func) | |
2351 |
|
2349 | |||
2352 | # Flush out code object which has been run (and source) |
|
2350 | # Flush out code object which has been run (and source) | |
2353 | self.code_to_run = None |
|
2351 | self.code_to_run = None | |
2354 | return outflag |
|
2352 | return outflag | |
2355 |
|
2353 | |||
2356 | # For backwards compatibility |
|
2354 | # For backwards compatibility | |
2357 | runcode = run_code |
|
2355 | runcode = run_code | |
2358 |
|
2356 | |||
2359 | # PENDING REMOVAL: this method is slated for deletion, once our new |
|
2357 | # PENDING REMOVAL: this method is slated for deletion, once our new | |
2360 | # input logic has been 100% moved to frontends and is stable. |
|
2358 | # input logic has been 100% moved to frontends and is stable. | |
2361 | def push_line(self, line): |
|
2359 | def push_line(self, line): | |
2362 | """Push a line to the interpreter. |
|
2360 | """Push a line to the interpreter. | |
2363 |
|
2361 | |||
2364 | The line should not have a trailing newline; it may have |
|
2362 | The line should not have a trailing newline; it may have | |
2365 | internal newlines. The line is appended to a buffer and the |
|
2363 | internal newlines. The line is appended to a buffer and the | |
2366 | interpreter's run_source() method is called with the |
|
2364 | interpreter's run_source() method is called with the | |
2367 | concatenated contents of the buffer as source. If this |
|
2365 | concatenated contents of the buffer as source. If this | |
2368 | indicates that the command was executed or invalid, the buffer |
|
2366 | indicates that the command was executed or invalid, the buffer | |
2369 | is reset; otherwise, the command is incomplete, and the buffer |
|
2367 | is reset; otherwise, the command is incomplete, and the buffer | |
2370 | is left as it was after the line was appended. The return |
|
2368 | is left as it was after the line was appended. The return | |
2371 | value is 1 if more input is required, 0 if the line was dealt |
|
2369 | value is 1 if more input is required, 0 if the line was dealt | |
2372 | with in some way (this is the same as run_source()). |
|
2370 | with in some way (this is the same as run_source()). | |
2373 | """ |
|
2371 | """ | |
2374 |
|
2372 | |||
2375 | # autoindent management should be done here, and not in the |
|
2373 | # autoindent management should be done here, and not in the | |
2376 | # interactive loop, since that one is only seen by keyboard input. We |
|
2374 | # interactive loop, since that one is only seen by keyboard input. We | |
2377 | # need this done correctly even for code run via runlines (which uses |
|
2375 | # need this done correctly even for code run via runlines (which uses | |
2378 | # push). |
|
2376 | # push). | |
2379 |
|
2377 | |||
2380 | #print 'push line: <%s>' % line # dbg |
|
2378 | #print 'push line: <%s>' % line # dbg | |
2381 | self.buffer.append(line) |
|
2379 | self.buffer.append(line) | |
2382 | full_source = '\n'.join(self.buffer) |
|
2380 | full_source = '\n'.join(self.buffer) | |
2383 | more = self.run_source(full_source, self.filename) |
|
2381 | more = self.run_source(full_source, self.filename) | |
2384 | if not more: |
|
2382 | if not more: | |
2385 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), |
|
2383 | self.history_manager.store_inputs('\n'.join(self.buffer_raw), | |
2386 | full_source) |
|
2384 | full_source) | |
2387 | self.reset_buffer() |
|
2385 | self.reset_buffer() | |
2388 | self.execution_count += 1 |
|
2386 | self.execution_count += 1 | |
2389 | return more |
|
2387 | return more | |
2390 |
|
2388 | |||
2391 | def reset_buffer(self): |
|
2389 | def reset_buffer(self): | |
2392 | """Reset the input buffer.""" |
|
2390 | """Reset the input buffer.""" | |
2393 | self.buffer[:] = [] |
|
2391 | self.buffer[:] = [] | |
2394 | self.buffer_raw[:] = [] |
|
2392 | self.buffer_raw[:] = [] | |
2395 | self.input_splitter.reset() |
|
2393 | self.input_splitter.reset() | |
2396 |
|
2394 | |||
2397 | # For backwards compatibility |
|
2395 | # For backwards compatibility | |
2398 | resetbuffer = reset_buffer |
|
2396 | resetbuffer = reset_buffer | |
2399 |
|
2397 | |||
2400 | def _is_secondary_block_start(self, s): |
|
2398 | def _is_secondary_block_start(self, s): | |
2401 | if not s.endswith(':'): |
|
2399 | if not s.endswith(':'): | |
2402 | return False |
|
2400 | return False | |
2403 | if (s.startswith('elif') or |
|
2401 | if (s.startswith('elif') or | |
2404 | s.startswith('else') or |
|
2402 | s.startswith('else') or | |
2405 | s.startswith('except') or |
|
2403 | s.startswith('except') or | |
2406 | s.startswith('finally')): |
|
2404 | s.startswith('finally')): | |
2407 | return True |
|
2405 | return True | |
2408 |
|
2406 | |||
2409 | def _cleanup_ipy_script(self, script): |
|
2407 | def _cleanup_ipy_script(self, script): | |
2410 | """Make a script safe for self.runlines() |
|
2408 | """Make a script safe for self.runlines() | |
2411 |
|
2409 | |||
2412 | Currently, IPython is lines based, with blocks being detected by |
|
2410 | Currently, IPython is lines based, with blocks being detected by | |
2413 | empty lines. This is a problem for block based scripts that may |
|
2411 | empty lines. This is a problem for block based scripts that may | |
2414 | not have empty lines after blocks. This script adds those empty |
|
2412 | not have empty lines after blocks. This script adds those empty | |
2415 | lines to make scripts safe for running in the current line based |
|
2413 | lines to make scripts safe for running in the current line based | |
2416 | IPython. |
|
2414 | IPython. | |
2417 | """ |
|
2415 | """ | |
2418 | res = [] |
|
2416 | res = [] | |
2419 | lines = script.splitlines() |
|
2417 | lines = script.splitlines() | |
2420 | level = 0 |
|
2418 | level = 0 | |
2421 |
|
2419 | |||
2422 | for l in lines: |
|
2420 | for l in lines: | |
2423 | lstripped = l.lstrip() |
|
2421 | lstripped = l.lstrip() | |
2424 | stripped = l.strip() |
|
2422 | stripped = l.strip() | |
2425 | if not stripped: |
|
2423 | if not stripped: | |
2426 | continue |
|
2424 | continue | |
2427 | newlevel = len(l) - len(lstripped) |
|
2425 | newlevel = len(l) - len(lstripped) | |
2428 | if level > 0 and newlevel == 0 and \ |
|
2426 | if level > 0 and newlevel == 0 and \ | |
2429 | not self._is_secondary_block_start(stripped): |
|
2427 | not self._is_secondary_block_start(stripped): | |
2430 | # add empty line |
|
2428 | # add empty line | |
2431 | res.append('') |
|
2429 | res.append('') | |
2432 | res.append(l) |
|
2430 | res.append(l) | |
2433 | level = newlevel |
|
2431 | level = newlevel | |
2434 |
|
2432 | |||
2435 | return '\n'.join(res) + '\n' |
|
2433 | return '\n'.join(res) + '\n' | |
2436 |
|
2434 | |||
2437 | #------------------------------------------------------------------------- |
|
2435 | #------------------------------------------------------------------------- | |
2438 | # Things related to GUI support and pylab |
|
2436 | # Things related to GUI support and pylab | |
2439 | #------------------------------------------------------------------------- |
|
2437 | #------------------------------------------------------------------------- | |
2440 |
|
2438 | |||
2441 | def enable_pylab(self, gui=None): |
|
2439 | def enable_pylab(self, gui=None): | |
2442 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2440 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2443 |
|
2441 | |||
2444 | #------------------------------------------------------------------------- |
|
2442 | #------------------------------------------------------------------------- | |
2445 | # Utilities |
|
2443 | # Utilities | |
2446 | #------------------------------------------------------------------------- |
|
2444 | #------------------------------------------------------------------------- | |
2447 |
|
2445 | |||
2448 | def var_expand(self,cmd,depth=0): |
|
2446 | def var_expand(self,cmd,depth=0): | |
2449 | """Expand python variables in a string. |
|
2447 | """Expand python variables in a string. | |
2450 |
|
2448 | |||
2451 | The depth argument indicates how many frames above the caller should |
|
2449 | The depth argument indicates how many frames above the caller should | |
2452 | be walked to look for the local namespace where to expand variables. |
|
2450 | be walked to look for the local namespace where to expand variables. | |
2453 |
|
2451 | |||
2454 | The global namespace for expansion is always the user's interactive |
|
2452 | The global namespace for expansion is always the user's interactive | |
2455 | namespace. |
|
2453 | namespace. | |
2456 | """ |
|
2454 | """ | |
2457 |
|
2455 | |||
2458 | return str(ItplNS(cmd, |
|
2456 | return str(ItplNS(cmd, | |
2459 | self.user_ns, # globals |
|
2457 | self.user_ns, # globals | |
2460 | # Skip our own frame in searching for locals: |
|
2458 | # Skip our own frame in searching for locals: | |
2461 | sys._getframe(depth+1).f_locals # locals |
|
2459 | sys._getframe(depth+1).f_locals # locals | |
2462 | )) |
|
2460 | )) | |
2463 |
|
2461 | |||
2464 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2462 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2465 | """Make a new tempfile and return its filename. |
|
2463 | """Make a new tempfile and return its filename. | |
2466 |
|
2464 | |||
2467 | This makes a call to tempfile.mktemp, but it registers the created |
|
2465 | This makes a call to tempfile.mktemp, but it registers the created | |
2468 | filename internally so ipython cleans it up at exit time. |
|
2466 | filename internally so ipython cleans it up at exit time. | |
2469 |
|
2467 | |||
2470 | Optional inputs: |
|
2468 | Optional inputs: | |
2471 |
|
2469 | |||
2472 | - data(None): if data is given, it gets written out to the temp file |
|
2470 | - data(None): if data is given, it gets written out to the temp file | |
2473 | immediately, and the file is closed again.""" |
|
2471 | immediately, and the file is closed again.""" | |
2474 |
|
2472 | |||
2475 | filename = tempfile.mktemp('.py', prefix) |
|
2473 | filename = tempfile.mktemp('.py', prefix) | |
2476 | self.tempfiles.append(filename) |
|
2474 | self.tempfiles.append(filename) | |
2477 |
|
2475 | |||
2478 | if data: |
|
2476 | if data: | |
2479 | tmp_file = open(filename,'w') |
|
2477 | tmp_file = open(filename,'w') | |
2480 | tmp_file.write(data) |
|
2478 | tmp_file.write(data) | |
2481 | tmp_file.close() |
|
2479 | tmp_file.close() | |
2482 | return filename |
|
2480 | return filename | |
2483 |
|
2481 | |||
2484 | # TODO: This should be removed when Term is refactored. |
|
2482 | # TODO: This should be removed when Term is refactored. | |
2485 | def write(self,data): |
|
2483 | def write(self,data): | |
2486 | """Write a string to the default output""" |
|
2484 | """Write a string to the default output""" | |
2487 | io.Term.cout.write(data) |
|
2485 | io.Term.cout.write(data) | |
2488 |
|
2486 | |||
2489 | # TODO: This should be removed when Term is refactored. |
|
2487 | # TODO: This should be removed when Term is refactored. | |
2490 | def write_err(self,data): |
|
2488 | def write_err(self,data): | |
2491 | """Write a string to the default error output""" |
|
2489 | """Write a string to the default error output""" | |
2492 | io.Term.cerr.write(data) |
|
2490 | io.Term.cerr.write(data) | |
2493 |
|
2491 | |||
2494 | def ask_yes_no(self,prompt,default=True): |
|
2492 | def ask_yes_no(self,prompt,default=True): | |
2495 | if self.quiet: |
|
2493 | if self.quiet: | |
2496 | return True |
|
2494 | return True | |
2497 | return ask_yes_no(prompt,default) |
|
2495 | return ask_yes_no(prompt,default) | |
2498 |
|
2496 | |||
2499 | def show_usage(self): |
|
2497 | def show_usage(self): | |
2500 | """Show a usage message""" |
|
2498 | """Show a usage message""" | |
2501 | page.page(IPython.core.usage.interactive_usage) |
|
2499 | page.page(IPython.core.usage.interactive_usage) | |
2502 |
|
2500 | |||
2503 | #------------------------------------------------------------------------- |
|
2501 | #------------------------------------------------------------------------- | |
2504 | # Things related to IPython exiting |
|
2502 | # Things related to IPython exiting | |
2505 | #------------------------------------------------------------------------- |
|
2503 | #------------------------------------------------------------------------- | |
2506 | def atexit_operations(self): |
|
2504 | def atexit_operations(self): | |
2507 | """This will be executed at the time of exit. |
|
2505 | """This will be executed at the time of exit. | |
2508 |
|
2506 | |||
2509 | Cleanup operations and saving of persistent data that is done |
|
2507 | Cleanup operations and saving of persistent data that is done | |
2510 | unconditionally by IPython should be performed here. |
|
2508 | unconditionally by IPython should be performed here. | |
2511 |
|
2509 | |||
2512 | For things that may depend on startup flags or platform specifics (such |
|
2510 | For things that may depend on startup flags or platform specifics (such | |
2513 | as having readline or not), register a separate atexit function in the |
|
2511 | as having readline or not), register a separate atexit function in the | |
2514 | code that has the appropriate information, rather than trying to |
|
2512 | code that has the appropriate information, rather than trying to | |
2515 | clutter |
|
2513 | clutter | |
2516 | """ |
|
2514 | """ | |
2517 | # Cleanup all tempfiles left around |
|
2515 | # Cleanup all tempfiles left around | |
2518 | for tfile in self.tempfiles: |
|
2516 | for tfile in self.tempfiles: | |
2519 | try: |
|
2517 | try: | |
2520 | os.unlink(tfile) |
|
2518 | os.unlink(tfile) | |
2521 | except OSError: |
|
2519 | except OSError: | |
2522 | pass |
|
2520 | pass | |
2523 |
|
2521 | |||
|
2522 | ||||
|
2523 | self.save_history() | |||
|
2524 | ||||
2524 | # Clear all user namespaces to release all references cleanly. |
|
2525 | # Clear all user namespaces to release all references cleanly. | |
2525 | self.reset() |
|
2526 | self.reset() | |
2526 |
|
2527 | |||
2527 | # Run user hooks |
|
2528 | # Run user hooks | |
2528 | self.hooks.shutdown_hook() |
|
2529 | self.hooks.shutdown_hook() | |
2529 |
|
2530 | |||
2530 | def cleanup(self): |
|
2531 | def cleanup(self): | |
2531 | self.restore_sys_module_state() |
|
2532 | self.restore_sys_module_state() | |
2532 |
|
2533 | |||
2533 |
|
2534 | |||
2534 | class InteractiveShellABC(object): |
|
2535 | class InteractiveShellABC(object): | |
2535 | """An abstract base class for InteractiveShell.""" |
|
2536 | """An abstract base class for InteractiveShell.""" | |
2536 | __metaclass__ = abc.ABCMeta |
|
2537 | __metaclass__ = abc.ABCMeta | |
2537 |
|
2538 | |||
2538 | InteractiveShellABC.register(InteractiveShell) |
|
2539 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3367 +1,3367 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
50 | from IPython.core import page |
|
50 | from IPython.core import page | |
51 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
52 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
53 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
54 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
55 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
56 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
100 |
|
100 | |||
101 | class Magic: |
|
101 | class Magic: | |
102 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
103 |
|
103 | |||
104 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
105 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
107 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
108 |
|
108 | |||
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
110 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
111 |
|
111 | |||
112 | # class globals |
|
112 | # class globals | |
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
115 |
|
115 | |||
116 | #...................................................................... |
|
116 | #...................................................................... | |
117 | # some utility functions |
|
117 | # some utility functions | |
118 |
|
118 | |||
119 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
120 |
|
120 | |||
121 | self.options_table = {} |
|
121 | self.options_table = {} | |
122 | if profile is None: |
|
122 | if profile is None: | |
123 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
124 | self.shell = shell |
|
124 | self.shell = shell | |
125 |
|
125 | |||
126 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
127 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
128 |
|
128 | |||
129 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
130 | error("""\ |
|
130 | error("""\ | |
131 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
132 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
133 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
134 |
|
134 | |||
135 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
136 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
137 |
|
137 | |||
138 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
139 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
140 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
141 |
|
141 | |||
142 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
143 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
144 |
|
144 | |||
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
146 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
147 |
|
147 | |||
148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
149 |
|
149 | |||
150 | # magics in class definition |
|
150 | # magics in class definition | |
151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
153 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
156 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
158 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
162 | out = [] |
|
162 | out = [] | |
163 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
164 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
165 | out.sort() |
|
165 | out.sort() | |
166 | return out |
|
166 | return out | |
167 |
|
167 | |||
168 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
169 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
174 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
175 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
176 |
|
176 | |||
177 | Optional inputs: |
|
177 | Optional inputs: | |
178 |
|
178 | |||
179 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
180 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
181 |
|
181 | |||
182 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
183 |
|
183 | |||
184 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
185 |
|
185 | |||
186 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
187 |
|
187 | |||
188 | if raw: |
|
188 | if raw: | |
189 | hist = self.shell.input_hist_raw |
|
189 | hist = self.shell.history_manager.input_hist_raw | |
190 | else: |
|
190 | else: | |
191 | hist = self.shell.input_hist |
|
191 | hist = self.shell.history_manager.input_hist_parsed | |
192 |
|
192 | |||
193 | cmds = [] |
|
193 | cmds = [] | |
194 | for chunk in slices: |
|
194 | for chunk in slices: | |
195 | if ':' in chunk: |
|
195 | if ':' in chunk: | |
196 | ini,fin = map(int,chunk.split(':')) |
|
196 | ini,fin = map(int,chunk.split(':')) | |
197 | elif '-' in chunk: |
|
197 | elif '-' in chunk: | |
198 | ini,fin = map(int,chunk.split('-')) |
|
198 | ini,fin = map(int,chunk.split('-')) | |
199 | fin += 1 |
|
199 | fin += 1 | |
200 | else: |
|
200 | else: | |
201 | ini = int(chunk) |
|
201 | ini = int(chunk) | |
202 | fin = ini+1 |
|
202 | fin = ini+1 | |
203 | cmds.append(hist[ini:fin]) |
|
203 | cmds.append(''.join(hist[ini:fin])) | |
204 | return cmds |
|
204 | return cmds | |
205 |
|
205 | |||
206 | def arg_err(self,func): |
|
206 | def arg_err(self,func): | |
207 | """Print docstring if incorrect arguments were passed""" |
|
207 | """Print docstring if incorrect arguments were passed""" | |
208 | print 'Error in arguments:' |
|
208 | print 'Error in arguments:' | |
209 | print oinspect.getdoc(func) |
|
209 | print oinspect.getdoc(func) | |
210 |
|
210 | |||
211 | def format_latex(self,strng): |
|
211 | def format_latex(self,strng): | |
212 | """Format a string for latex inclusion.""" |
|
212 | """Format a string for latex inclusion.""" | |
213 |
|
213 | |||
214 | # Characters that need to be escaped for latex: |
|
214 | # Characters that need to be escaped for latex: | |
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
216 | # Magic command names as headers: |
|
216 | # Magic command names as headers: | |
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
218 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
219 | # Magic commands |
|
219 | # Magic commands | |
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
221 | re.MULTILINE) |
|
221 | re.MULTILINE) | |
222 | # Paragraph continue |
|
222 | # Paragraph continue | |
223 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
223 | par_re = re.compile(r'\\$',re.MULTILINE) | |
224 |
|
224 | |||
225 | # The "\n" symbol |
|
225 | # The "\n" symbol | |
226 | newline_re = re.compile(r'\\n') |
|
226 | newline_re = re.compile(r'\\n') | |
227 |
|
227 | |||
228 | # Now build the string for output: |
|
228 | # Now build the string for output: | |
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
231 | strng) |
|
231 | strng) | |
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
233 | strng = par_re.sub(r'\\\\',strng) |
|
233 | strng = par_re.sub(r'\\\\',strng) | |
234 | strng = escape_re.sub(r'\\\1',strng) |
|
234 | strng = escape_re.sub(r'\\\1',strng) | |
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
236 | return strng |
|
236 | return strng | |
237 |
|
237 | |||
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
239 | """Parse options passed to an argument string. |
|
239 | """Parse options passed to an argument string. | |
240 |
|
240 | |||
241 | The interface is similar to that of getopt(), but it returns back a |
|
241 | The interface is similar to that of getopt(), but it returns back a | |
242 | Struct with the options as keys and the stripped argument string still |
|
242 | Struct with the options as keys and the stripped argument string still | |
243 | as a string. |
|
243 | as a string. | |
244 |
|
244 | |||
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
245 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
246 | This allows us to easily expand variables, glob files, quote |
|
246 | This allows us to easily expand variables, glob files, quote | |
247 | arguments, etc. |
|
247 | arguments, etc. | |
248 |
|
248 | |||
249 | Options: |
|
249 | Options: | |
250 | -mode: default 'string'. If given as 'list', the argument string is |
|
250 | -mode: default 'string'. If given as 'list', the argument string is | |
251 | returned as a list (split on whitespace) instead of a string. |
|
251 | returned as a list (split on whitespace) instead of a string. | |
252 |
|
252 | |||
253 | -list_all: put all option values in lists. Normally only options |
|
253 | -list_all: put all option values in lists. Normally only options | |
254 | appearing more than once are put in a list. |
|
254 | appearing more than once are put in a list. | |
255 |
|
255 | |||
256 | -posix (True): whether to split the input line in POSIX mode or not, |
|
256 | -posix (True): whether to split the input line in POSIX mode or not, | |
257 | as per the conventions outlined in the shlex module from the |
|
257 | as per the conventions outlined in the shlex module from the | |
258 | standard library.""" |
|
258 | standard library.""" | |
259 |
|
259 | |||
260 | # inject default options at the beginning of the input line |
|
260 | # inject default options at the beginning of the input line | |
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
263 |
|
263 | |||
264 | mode = kw.get('mode','string') |
|
264 | mode = kw.get('mode','string') | |
265 | if mode not in ['string','list']: |
|
265 | if mode not in ['string','list']: | |
266 | raise ValueError,'incorrect mode given: %s' % mode |
|
266 | raise ValueError,'incorrect mode given: %s' % mode | |
267 | # Get options |
|
267 | # Get options | |
268 | list_all = kw.get('list_all',0) |
|
268 | list_all = kw.get('list_all',0) | |
269 | posix = kw.get('posix', os.name == 'posix') |
|
269 | posix = kw.get('posix', os.name == 'posix') | |
270 |
|
270 | |||
271 | # Check if we have more than one argument to warrant extra processing: |
|
271 | # Check if we have more than one argument to warrant extra processing: | |
272 | odict = {} # Dictionary with options |
|
272 | odict = {} # Dictionary with options | |
273 | args = arg_str.split() |
|
273 | args = arg_str.split() | |
274 | if len(args) >= 1: |
|
274 | if len(args) >= 1: | |
275 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
275 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
276 | # need to look for options |
|
276 | # need to look for options | |
277 | argv = arg_split(arg_str,posix) |
|
277 | argv = arg_split(arg_str,posix) | |
278 | # Do regular option processing |
|
278 | # Do regular option processing | |
279 | try: |
|
279 | try: | |
280 | opts,args = getopt(argv,opt_str,*long_opts) |
|
280 | opts,args = getopt(argv,opt_str,*long_opts) | |
281 | except GetoptError,e: |
|
281 | except GetoptError,e: | |
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
283 | " ".join(long_opts))) |
|
283 | " ".join(long_opts))) | |
284 | for o,a in opts: |
|
284 | for o,a in opts: | |
285 | if o.startswith('--'): |
|
285 | if o.startswith('--'): | |
286 | o = o[2:] |
|
286 | o = o[2:] | |
287 | else: |
|
287 | else: | |
288 | o = o[1:] |
|
288 | o = o[1:] | |
289 | try: |
|
289 | try: | |
290 | odict[o].append(a) |
|
290 | odict[o].append(a) | |
291 | except AttributeError: |
|
291 | except AttributeError: | |
292 | odict[o] = [odict[o],a] |
|
292 | odict[o] = [odict[o],a] | |
293 | except KeyError: |
|
293 | except KeyError: | |
294 | if list_all: |
|
294 | if list_all: | |
295 | odict[o] = [a] |
|
295 | odict[o] = [a] | |
296 | else: |
|
296 | else: | |
297 | odict[o] = a |
|
297 | odict[o] = a | |
298 |
|
298 | |||
299 | # Prepare opts,args for return |
|
299 | # Prepare opts,args for return | |
300 | opts = Struct(odict) |
|
300 | opts = Struct(odict) | |
301 | if mode == 'string': |
|
301 | if mode == 'string': | |
302 | args = ' '.join(args) |
|
302 | args = ' '.join(args) | |
303 |
|
303 | |||
304 | return opts,args |
|
304 | return opts,args | |
305 |
|
305 | |||
306 | #...................................................................... |
|
306 | #...................................................................... | |
307 | # And now the actual magic functions |
|
307 | # And now the actual magic functions | |
308 |
|
308 | |||
309 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
309 | # Functions for IPython shell work (vars,funcs, config, etc) | |
310 | def magic_lsmagic(self, parameter_s = ''): |
|
310 | def magic_lsmagic(self, parameter_s = ''): | |
311 | """List currently available magic functions.""" |
|
311 | """List currently available magic functions.""" | |
312 | mesc = ESC_MAGIC |
|
312 | mesc = ESC_MAGIC | |
313 | print 'Available magic functions:\n'+mesc+\ |
|
313 | print 'Available magic functions:\n'+mesc+\ | |
314 | (' '+mesc).join(self.lsmagic()) |
|
314 | (' '+mesc).join(self.lsmagic()) | |
315 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
315 | print '\n' + Magic.auto_status[self.shell.automagic] | |
316 | return None |
|
316 | return None | |
317 |
|
317 | |||
318 | def magic_magic(self, parameter_s = ''): |
|
318 | def magic_magic(self, parameter_s = ''): | |
319 | """Print information about the magic function system. |
|
319 | """Print information about the magic function system. | |
320 |
|
320 | |||
321 | Supported formats: -latex, -brief, -rest |
|
321 | Supported formats: -latex, -brief, -rest | |
322 | """ |
|
322 | """ | |
323 |
|
323 | |||
324 | mode = '' |
|
324 | mode = '' | |
325 | try: |
|
325 | try: | |
326 | if parameter_s.split()[0] == '-latex': |
|
326 | if parameter_s.split()[0] == '-latex': | |
327 | mode = 'latex' |
|
327 | mode = 'latex' | |
328 | if parameter_s.split()[0] == '-brief': |
|
328 | if parameter_s.split()[0] == '-brief': | |
329 | mode = 'brief' |
|
329 | mode = 'brief' | |
330 | if parameter_s.split()[0] == '-rest': |
|
330 | if parameter_s.split()[0] == '-rest': | |
331 | mode = 'rest' |
|
331 | mode = 'rest' | |
332 | rest_docs = [] |
|
332 | rest_docs = [] | |
333 | except: |
|
333 | except: | |
334 | pass |
|
334 | pass | |
335 |
|
335 | |||
336 | magic_docs = [] |
|
336 | magic_docs = [] | |
337 | for fname in self.lsmagic(): |
|
337 | for fname in self.lsmagic(): | |
338 | mname = 'magic_' + fname |
|
338 | mname = 'magic_' + fname | |
339 | for space in (Magic,self,self.__class__): |
|
339 | for space in (Magic,self,self.__class__): | |
340 | try: |
|
340 | try: | |
341 | fn = space.__dict__[mname] |
|
341 | fn = space.__dict__[mname] | |
342 | except KeyError: |
|
342 | except KeyError: | |
343 | pass |
|
343 | pass | |
344 | else: |
|
344 | else: | |
345 | break |
|
345 | break | |
346 | if mode == 'brief': |
|
346 | if mode == 'brief': | |
347 | # only first line |
|
347 | # only first line | |
348 | if fn.__doc__: |
|
348 | if fn.__doc__: | |
349 | fndoc = fn.__doc__.split('\n',1)[0] |
|
349 | fndoc = fn.__doc__.split('\n',1)[0] | |
350 | else: |
|
350 | else: | |
351 | fndoc = 'No documentation' |
|
351 | fndoc = 'No documentation' | |
352 | else: |
|
352 | else: | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.rstrip() |
|
354 | fndoc = fn.__doc__.rstrip() | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 |
|
357 | |||
358 |
|
358 | |||
359 | if mode == 'rest': |
|
359 | if mode == 'rest': | |
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
361 | fname,fndoc)) |
|
361 | fname,fndoc)) | |
362 |
|
362 | |||
363 | else: |
|
363 | else: | |
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
365 | fname,fndoc)) |
|
365 | fname,fndoc)) | |
366 |
|
366 | |||
367 | magic_docs = ''.join(magic_docs) |
|
367 | magic_docs = ''.join(magic_docs) | |
368 |
|
368 | |||
369 | if mode == 'rest': |
|
369 | if mode == 'rest': | |
370 | return "".join(rest_docs) |
|
370 | return "".join(rest_docs) | |
371 |
|
371 | |||
372 | if mode == 'latex': |
|
372 | if mode == 'latex': | |
373 | print self.format_latex(magic_docs) |
|
373 | print self.format_latex(magic_docs) | |
374 | return |
|
374 | return | |
375 | else: |
|
375 | else: | |
376 | magic_docs = format_screen(magic_docs) |
|
376 | magic_docs = format_screen(magic_docs) | |
377 | if mode == 'brief': |
|
377 | if mode == 'brief': | |
378 | return magic_docs |
|
378 | return magic_docs | |
379 |
|
379 | |||
380 | outmsg = """ |
|
380 | outmsg = """ | |
381 | IPython's 'magic' functions |
|
381 | IPython's 'magic' functions | |
382 | =========================== |
|
382 | =========================== | |
383 |
|
383 | |||
384 | The magic function system provides a series of functions which allow you to |
|
384 | The magic function system provides a series of functions which allow you to | |
385 | control the behavior of IPython itself, plus a lot of system-type |
|
385 | control the behavior of IPython itself, plus a lot of system-type | |
386 | features. All these functions are prefixed with a % character, but parameters |
|
386 | features. All these functions are prefixed with a % character, but parameters | |
387 | are given without parentheses or quotes. |
|
387 | are given without parentheses or quotes. | |
388 |
|
388 | |||
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
389 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
390 | %automagic function), you don't need to type in the % explicitly. By default, |
|
390 | %automagic function), you don't need to type in the % explicitly. By default, | |
391 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
391 | IPython ships with automagic on, so you should only rarely need the % escape. | |
392 |
|
392 | |||
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
393 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
394 | to 'mydir', if it exists. |
|
394 | to 'mydir', if it exists. | |
395 |
|
395 | |||
396 | You can define your own magic functions to extend the system. See the supplied |
|
396 | You can define your own magic functions to extend the system. See the supplied | |
397 | ipythonrc and example-magic.py files for details (in your ipython |
|
397 | ipythonrc and example-magic.py files for details (in your ipython | |
398 | configuration directory, typically $HOME/.ipython/). |
|
398 | configuration directory, typically $HOME/.ipython/). | |
399 |
|
399 | |||
400 | You can also define your own aliased names for magic functions. In your |
|
400 | You can also define your own aliased names for magic functions. In your | |
401 | ipythonrc file, placing a line like: |
|
401 | ipythonrc file, placing a line like: | |
402 |
|
402 | |||
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
404 |
|
404 | |||
405 | will define %pf as a new name for %profile. |
|
405 | will define %pf as a new name for %profile. | |
406 |
|
406 | |||
407 | You can also call magics in code using the magic() function, which IPython |
|
407 | You can also call magics in code using the magic() function, which IPython | |
408 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
408 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
409 |
|
409 | |||
410 | For a list of the available magic functions, use %lsmagic. For a description |
|
410 | For a list of the available magic functions, use %lsmagic. For a description | |
411 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
411 | of any of them, type %magic_name?, e.g. '%cd?'. | |
412 |
|
412 | |||
413 | Currently the magic system has the following functions:\n""" |
|
413 | Currently the magic system has the following functions:\n""" | |
414 |
|
414 | |||
415 | mesc = ESC_MAGIC |
|
415 | mesc = ESC_MAGIC | |
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
417 | "\n\n%s%s\n\n%s" % (outmsg, |
|
417 | "\n\n%s%s\n\n%s" % (outmsg, | |
418 | magic_docs,mesc,mesc, |
|
418 | magic_docs,mesc,mesc, | |
419 | (' '+mesc).join(self.lsmagic()), |
|
419 | (' '+mesc).join(self.lsmagic()), | |
420 | Magic.auto_status[self.shell.automagic] ) ) |
|
420 | Magic.auto_status[self.shell.automagic] ) ) | |
421 | page.page(outmsg) |
|
421 | page.page(outmsg) | |
422 |
|
422 | |||
423 | def magic_automagic(self, parameter_s = ''): |
|
423 | def magic_automagic(self, parameter_s = ''): | |
424 | """Make magic functions callable without having to type the initial %. |
|
424 | """Make magic functions callable without having to type the initial %. | |
425 |
|
425 | |||
426 | Without argumentsl toggles on/off (when off, you must call it as |
|
426 | Without argumentsl toggles on/off (when off, you must call it as | |
427 | %automagic, of course). With arguments it sets the value, and you can |
|
427 | %automagic, of course). With arguments it sets the value, and you can | |
428 | use any of (case insensitive): |
|
428 | use any of (case insensitive): | |
429 |
|
429 | |||
430 | - on,1,True: to activate |
|
430 | - on,1,True: to activate | |
431 |
|
431 | |||
432 | - off,0,False: to deactivate. |
|
432 | - off,0,False: to deactivate. | |
433 |
|
433 | |||
434 | Note that magic functions have lowest priority, so if there's a |
|
434 | Note that magic functions have lowest priority, so if there's a | |
435 | variable whose name collides with that of a magic fn, automagic won't |
|
435 | variable whose name collides with that of a magic fn, automagic won't | |
436 | work for that function (you get the variable instead). However, if you |
|
436 | work for that function (you get the variable instead). However, if you | |
437 | delete the variable (del var), the previously shadowed magic function |
|
437 | delete the variable (del var), the previously shadowed magic function | |
438 | becomes visible to automagic again.""" |
|
438 | becomes visible to automagic again.""" | |
439 |
|
439 | |||
440 | arg = parameter_s.lower() |
|
440 | arg = parameter_s.lower() | |
441 | if parameter_s in ('on','1','true'): |
|
441 | if parameter_s in ('on','1','true'): | |
442 | self.shell.automagic = True |
|
442 | self.shell.automagic = True | |
443 | elif parameter_s in ('off','0','false'): |
|
443 | elif parameter_s in ('off','0','false'): | |
444 | self.shell.automagic = False |
|
444 | self.shell.automagic = False | |
445 | else: |
|
445 | else: | |
446 | self.shell.automagic = not self.shell.automagic |
|
446 | self.shell.automagic = not self.shell.automagic | |
447 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
447 | print '\n' + Magic.auto_status[self.shell.automagic] | |
448 |
|
448 | |||
449 | @testdec.skip_doctest |
|
449 | @testdec.skip_doctest | |
450 | def magic_autocall(self, parameter_s = ''): |
|
450 | def magic_autocall(self, parameter_s = ''): | |
451 | """Make functions callable without having to type parentheses. |
|
451 | """Make functions callable without having to type parentheses. | |
452 |
|
452 | |||
453 | Usage: |
|
453 | Usage: | |
454 |
|
454 | |||
455 | %autocall [mode] |
|
455 | %autocall [mode] | |
456 |
|
456 | |||
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
458 | value is toggled on and off (remembering the previous state). |
|
458 | value is toggled on and off (remembering the previous state). | |
459 |
|
459 | |||
460 | In more detail, these values mean: |
|
460 | In more detail, these values mean: | |
461 |
|
461 | |||
462 | 0 -> fully disabled |
|
462 | 0 -> fully disabled | |
463 |
|
463 | |||
464 | 1 -> active, but do not apply if there are no arguments on the line. |
|
464 | 1 -> active, but do not apply if there are no arguments on the line. | |
465 |
|
465 | |||
466 | In this mode, you get: |
|
466 | In this mode, you get: | |
467 |
|
467 | |||
468 | In [1]: callable |
|
468 | In [1]: callable | |
469 | Out[1]: <built-in function callable> |
|
469 | Out[1]: <built-in function callable> | |
470 |
|
470 | |||
471 | In [2]: callable 'hello' |
|
471 | In [2]: callable 'hello' | |
472 | ------> callable('hello') |
|
472 | ------> callable('hello') | |
473 | Out[2]: False |
|
473 | Out[2]: False | |
474 |
|
474 | |||
475 | 2 -> Active always. Even if no arguments are present, the callable |
|
475 | 2 -> Active always. Even if no arguments are present, the callable | |
476 | object is called: |
|
476 | object is called: | |
477 |
|
477 | |||
478 | In [2]: float |
|
478 | In [2]: float | |
479 | ------> float() |
|
479 | ------> float() | |
480 | Out[2]: 0.0 |
|
480 | Out[2]: 0.0 | |
481 |
|
481 | |||
482 | Note that even with autocall off, you can still use '/' at the start of |
|
482 | Note that even with autocall off, you can still use '/' at the start of | |
483 | a line to treat the first argument on the command line as a function |
|
483 | a line to treat the first argument on the command line as a function | |
484 | and add parentheses to it: |
|
484 | and add parentheses to it: | |
485 |
|
485 | |||
486 | In [8]: /str 43 |
|
486 | In [8]: /str 43 | |
487 | ------> str(43) |
|
487 | ------> str(43) | |
488 | Out[8]: '43' |
|
488 | Out[8]: '43' | |
489 |
|
489 | |||
490 | # all-random (note for auto-testing) |
|
490 | # all-random (note for auto-testing) | |
491 | """ |
|
491 | """ | |
492 |
|
492 | |||
493 | if parameter_s: |
|
493 | if parameter_s: | |
494 | arg = int(parameter_s) |
|
494 | arg = int(parameter_s) | |
495 | else: |
|
495 | else: | |
496 | arg = 'toggle' |
|
496 | arg = 'toggle' | |
497 |
|
497 | |||
498 | if not arg in (0,1,2,'toggle'): |
|
498 | if not arg in (0,1,2,'toggle'): | |
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
500 | return |
|
500 | return | |
501 |
|
501 | |||
502 | if arg in (0,1,2): |
|
502 | if arg in (0,1,2): | |
503 | self.shell.autocall = arg |
|
503 | self.shell.autocall = arg | |
504 | else: # toggle |
|
504 | else: # toggle | |
505 | if self.shell.autocall: |
|
505 | if self.shell.autocall: | |
506 | self._magic_state.autocall_save = self.shell.autocall |
|
506 | self._magic_state.autocall_save = self.shell.autocall | |
507 | self.shell.autocall = 0 |
|
507 | self.shell.autocall = 0 | |
508 | else: |
|
508 | else: | |
509 | try: |
|
509 | try: | |
510 | self.shell.autocall = self._magic_state.autocall_save |
|
510 | self.shell.autocall = self._magic_state.autocall_save | |
511 | except AttributeError: |
|
511 | except AttributeError: | |
512 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
512 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
513 |
|
513 | |||
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
515 |
|
515 | |||
516 |
|
516 | |||
517 | def magic_page(self, parameter_s=''): |
|
517 | def magic_page(self, parameter_s=''): | |
518 | """Pretty print the object and display it through a pager. |
|
518 | """Pretty print the object and display it through a pager. | |
519 |
|
519 | |||
520 | %page [options] OBJECT |
|
520 | %page [options] OBJECT | |
521 |
|
521 | |||
522 | If no object is given, use _ (last output). |
|
522 | If no object is given, use _ (last output). | |
523 |
|
523 | |||
524 | Options: |
|
524 | Options: | |
525 |
|
525 | |||
526 | -r: page str(object), don't pretty-print it.""" |
|
526 | -r: page str(object), don't pretty-print it.""" | |
527 |
|
527 | |||
528 | # After a function contributed by Olivier Aubert, slightly modified. |
|
528 | # After a function contributed by Olivier Aubert, slightly modified. | |
529 |
|
529 | |||
530 | # Process options/args |
|
530 | # Process options/args | |
531 | opts,args = self.parse_options(parameter_s,'r') |
|
531 | opts,args = self.parse_options(parameter_s,'r') | |
532 | raw = 'r' in opts |
|
532 | raw = 'r' in opts | |
533 |
|
533 | |||
534 | oname = args and args or '_' |
|
534 | oname = args and args or '_' | |
535 | info = self._ofind(oname) |
|
535 | info = self._ofind(oname) | |
536 | if info['found']: |
|
536 | if info['found']: | |
537 | txt = (raw and str or pformat)( info['obj'] ) |
|
537 | txt = (raw and str or pformat)( info['obj'] ) | |
538 | page.page(txt) |
|
538 | page.page(txt) | |
539 | else: |
|
539 | else: | |
540 | print 'Object `%s` not found' % oname |
|
540 | print 'Object `%s` not found' % oname | |
541 |
|
541 | |||
542 | def magic_profile(self, parameter_s=''): |
|
542 | def magic_profile(self, parameter_s=''): | |
543 | """Print your currently active IPython profile.""" |
|
543 | """Print your currently active IPython profile.""" | |
544 | if self.shell.profile: |
|
544 | if self.shell.profile: | |
545 | printpl('Current IPython profile: $self.shell.profile.') |
|
545 | printpl('Current IPython profile: $self.shell.profile.') | |
546 | else: |
|
546 | else: | |
547 | print 'No profile active.' |
|
547 | print 'No profile active.' | |
548 |
|
548 | |||
549 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
549 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
550 | """Provide detailed information about an object. |
|
550 | """Provide detailed information about an object. | |
551 |
|
551 | |||
552 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
552 | '%pinfo object' is just a synonym for object? or ?object.""" | |
553 |
|
553 | |||
554 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
554 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
555 |
|
555 | |||
556 |
|
556 | |||
557 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
557 | # detail_level: 0 -> obj? , 1 -> obj?? | |
558 | detail_level = 0 |
|
558 | detail_level = 0 | |
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
559 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
560 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
560 | # happen if the user types 'pinfo foo?' at the cmd line. | |
561 | pinfo,qmark1,oname,qmark2 = \ |
|
561 | pinfo,qmark1,oname,qmark2 = \ | |
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
563 | if pinfo or qmark1 or qmark2: |
|
563 | if pinfo or qmark1 or qmark2: | |
564 | detail_level = 1 |
|
564 | detail_level = 1 | |
565 | if "*" in oname: |
|
565 | if "*" in oname: | |
566 | self.magic_psearch(oname) |
|
566 | self.magic_psearch(oname) | |
567 | else: |
|
567 | else: | |
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
569 | namespaces=namespaces) |
|
569 | namespaces=namespaces) | |
570 |
|
570 | |||
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
571 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
572 | """Provide extra detailed information about an object. |
|
572 | """Provide extra detailed information about an object. | |
573 |
|
573 | |||
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
576 | namespaces=namespaces) |
|
576 | namespaces=namespaces) | |
577 |
|
577 | |||
578 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
578 | def magic_pdef(self, parameter_s='', namespaces=None): | |
579 | """Print the definition header for any callable object. |
|
579 | """Print the definition header for any callable object. | |
580 |
|
580 | |||
581 | If the object is a class, print the constructor information.""" |
|
581 | If the object is a class, print the constructor information.""" | |
582 | self._inspect('pdef',parameter_s, namespaces) |
|
582 | self._inspect('pdef',parameter_s, namespaces) | |
583 |
|
583 | |||
584 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
584 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
585 | """Print the docstring for an object. |
|
585 | """Print the docstring for an object. | |
586 |
|
586 | |||
587 | If the given object is a class, it will print both the class and the |
|
587 | If the given object is a class, it will print both the class and the | |
588 | constructor docstrings.""" |
|
588 | constructor docstrings.""" | |
589 | self._inspect('pdoc',parameter_s, namespaces) |
|
589 | self._inspect('pdoc',parameter_s, namespaces) | |
590 |
|
590 | |||
591 | def magic_psource(self, parameter_s='', namespaces=None): |
|
591 | def magic_psource(self, parameter_s='', namespaces=None): | |
592 | """Print (or run through pager) the source code for an object.""" |
|
592 | """Print (or run through pager) the source code for an object.""" | |
593 | self._inspect('psource',parameter_s, namespaces) |
|
593 | self._inspect('psource',parameter_s, namespaces) | |
594 |
|
594 | |||
595 | def magic_pfile(self, parameter_s=''): |
|
595 | def magic_pfile(self, parameter_s=''): | |
596 | """Print (or run through pager) the file where an object is defined. |
|
596 | """Print (or run through pager) the file where an object is defined. | |
597 |
|
597 | |||
598 | The file opens at the line where the object definition begins. IPython |
|
598 | The file opens at the line where the object definition begins. IPython | |
599 | will honor the environment variable PAGER if set, and otherwise will |
|
599 | will honor the environment variable PAGER if set, and otherwise will | |
600 | do its best to print the file in a convenient form. |
|
600 | do its best to print the file in a convenient form. | |
601 |
|
601 | |||
602 | If the given argument is not an object currently defined, IPython will |
|
602 | If the given argument is not an object currently defined, IPython will | |
603 | try to interpret it as a filename (automatically adding a .py extension |
|
603 | try to interpret it as a filename (automatically adding a .py extension | |
604 | if needed). You can thus use %pfile as a syntax highlighting code |
|
604 | if needed). You can thus use %pfile as a syntax highlighting code | |
605 | viewer.""" |
|
605 | viewer.""" | |
606 |
|
606 | |||
607 | # first interpret argument as an object name |
|
607 | # first interpret argument as an object name | |
608 | out = self._inspect('pfile',parameter_s) |
|
608 | out = self._inspect('pfile',parameter_s) | |
609 | # if not, try the input as a filename |
|
609 | # if not, try the input as a filename | |
610 | if out == 'not found': |
|
610 | if out == 'not found': | |
611 | try: |
|
611 | try: | |
612 | filename = get_py_filename(parameter_s) |
|
612 | filename = get_py_filename(parameter_s) | |
613 | except IOError,msg: |
|
613 | except IOError,msg: | |
614 | print msg |
|
614 | print msg | |
615 | return |
|
615 | return | |
616 | page.page(self.shell.inspector.format(file(filename).read())) |
|
616 | page.page(self.shell.inspector.format(file(filename).read())) | |
617 |
|
617 | |||
618 | def magic_psearch(self, parameter_s=''): |
|
618 | def magic_psearch(self, parameter_s=''): | |
619 | """Search for object in namespaces by wildcard. |
|
619 | """Search for object in namespaces by wildcard. | |
620 |
|
620 | |||
621 | %psearch [options] PATTERN [OBJECT TYPE] |
|
621 | %psearch [options] PATTERN [OBJECT TYPE] | |
622 |
|
622 | |||
623 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
623 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
624 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
624 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
625 | rest of the command line must be unchanged (options come first), so |
|
625 | rest of the command line must be unchanged (options come first), so | |
626 | for example the following forms are equivalent |
|
626 | for example the following forms are equivalent | |
627 |
|
627 | |||
628 | %psearch -i a* function |
|
628 | %psearch -i a* function | |
629 | -i a* function? |
|
629 | -i a* function? | |
630 | ?-i a* function |
|
630 | ?-i a* function | |
631 |
|
631 | |||
632 | Arguments: |
|
632 | Arguments: | |
633 |
|
633 | |||
634 | PATTERN |
|
634 | PATTERN | |
635 |
|
635 | |||
636 | where PATTERN is a string containing * as a wildcard similar to its |
|
636 | where PATTERN is a string containing * as a wildcard similar to its | |
637 | use in a shell. The pattern is matched in all namespaces on the |
|
637 | use in a shell. The pattern is matched in all namespaces on the | |
638 | search path. By default objects starting with a single _ are not |
|
638 | search path. By default objects starting with a single _ are not | |
639 | matched, many IPython generated objects have a single |
|
639 | matched, many IPython generated objects have a single | |
640 | underscore. The default is case insensitive matching. Matching is |
|
640 | underscore. The default is case insensitive matching. Matching is | |
641 | also done on the attributes of objects and not only on the objects |
|
641 | also done on the attributes of objects and not only on the objects | |
642 | in a module. |
|
642 | in a module. | |
643 |
|
643 | |||
644 | [OBJECT TYPE] |
|
644 | [OBJECT TYPE] | |
645 |
|
645 | |||
646 | Is the name of a python type from the types module. The name is |
|
646 | Is the name of a python type from the types module. The name is | |
647 | given in lowercase without the ending type, ex. StringType is |
|
647 | given in lowercase without the ending type, ex. StringType is | |
648 | written string. By adding a type here only objects matching the |
|
648 | written string. By adding a type here only objects matching the | |
649 | given type are matched. Using all here makes the pattern match all |
|
649 | given type are matched. Using all here makes the pattern match all | |
650 | types (this is the default). |
|
650 | types (this is the default). | |
651 |
|
651 | |||
652 | Options: |
|
652 | Options: | |
653 |
|
653 | |||
654 | -a: makes the pattern match even objects whose names start with a |
|
654 | -a: makes the pattern match even objects whose names start with a | |
655 | single underscore. These names are normally ommitted from the |
|
655 | single underscore. These names are normally ommitted from the | |
656 | search. |
|
656 | search. | |
657 |
|
657 | |||
658 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
658 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
659 | these options is given, the default is read from your ipythonrc |
|
659 | these options is given, the default is read from your ipythonrc | |
660 | file. The option name which sets this value is |
|
660 | file. The option name which sets this value is | |
661 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
661 | 'wildcards_case_sensitive'. If this option is not specified in your | |
662 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
662 | ipythonrc file, IPython's internal default is to do a case sensitive | |
663 | search. |
|
663 | search. | |
664 |
|
664 | |||
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
666 | specifiy can be searched in any of the following namespaces: |
|
666 | specifiy can be searched in any of the following namespaces: | |
667 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
668 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 'builtin' and 'user' are the search defaults. Note that you should | |
669 | not use quotes when specifying namespaces. |
|
669 | not use quotes when specifying namespaces. | |
670 |
|
670 | |||
671 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 'Builtin' contains the python module builtin, 'user' contains all | |
672 | user data, 'alias' only contain the shell aliases and no python |
|
672 | user data, 'alias' only contain the shell aliases and no python | |
673 | objects, 'internal' contains objects used by IPython. The |
|
673 | objects, 'internal' contains objects used by IPython. The | |
674 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 'user_global' namespace is only used by embedded IPython instances, | |
675 | and it contains module-level globals. You can add namespaces to the |
|
675 | and it contains module-level globals. You can add namespaces to the | |
676 | search with -s or exclude them with -e (these options can be given |
|
676 | search with -s or exclude them with -e (these options can be given | |
677 | more than once). |
|
677 | more than once). | |
678 |
|
678 | |||
679 | Examples: |
|
679 | Examples: | |
680 |
|
680 | |||
681 | %psearch a* -> objects beginning with an a |
|
681 | %psearch a* -> objects beginning with an a | |
682 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
682 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
683 | %psearch a* function -> all functions beginning with an a |
|
683 | %psearch a* function -> all functions beginning with an a | |
684 | %psearch re.e* -> objects beginning with an e in module re |
|
684 | %psearch re.e* -> objects beginning with an e in module re | |
685 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
685 | %psearch r*.e* -> objects that start with e in modules starting in r | |
686 | %psearch r*.* string -> all strings in modules beginning with r |
|
686 | %psearch r*.* string -> all strings in modules beginning with r | |
687 |
|
687 | |||
688 | Case sensitve search: |
|
688 | Case sensitve search: | |
689 |
|
689 | |||
690 | %psearch -c a* list all object beginning with lower case a |
|
690 | %psearch -c a* list all object beginning with lower case a | |
691 |
|
691 | |||
692 | Show objects beginning with a single _: |
|
692 | Show objects beginning with a single _: | |
693 |
|
693 | |||
694 | %psearch -a _* list objects beginning with a single underscore""" |
|
694 | %psearch -a _* list objects beginning with a single underscore""" | |
695 | try: |
|
695 | try: | |
696 | parameter_s = parameter_s.encode('ascii') |
|
696 | parameter_s = parameter_s.encode('ascii') | |
697 | except UnicodeEncodeError: |
|
697 | except UnicodeEncodeError: | |
698 | print 'Python identifiers can only contain ascii characters.' |
|
698 | print 'Python identifiers can only contain ascii characters.' | |
699 | return |
|
699 | return | |
700 |
|
700 | |||
701 | # default namespaces to be searched |
|
701 | # default namespaces to be searched | |
702 | def_search = ['user','builtin'] |
|
702 | def_search = ['user','builtin'] | |
703 |
|
703 | |||
704 | # Process options/args |
|
704 | # Process options/args | |
705 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
705 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
706 | opt = opts.get |
|
706 | opt = opts.get | |
707 | shell = self.shell |
|
707 | shell = self.shell | |
708 | psearch = shell.inspector.psearch |
|
708 | psearch = shell.inspector.psearch | |
709 |
|
709 | |||
710 | # select case options |
|
710 | # select case options | |
711 | if opts.has_key('i'): |
|
711 | if opts.has_key('i'): | |
712 | ignore_case = True |
|
712 | ignore_case = True | |
713 | elif opts.has_key('c'): |
|
713 | elif opts.has_key('c'): | |
714 | ignore_case = False |
|
714 | ignore_case = False | |
715 | else: |
|
715 | else: | |
716 | ignore_case = not shell.wildcards_case_sensitive |
|
716 | ignore_case = not shell.wildcards_case_sensitive | |
717 |
|
717 | |||
718 | # Build list of namespaces to search from user options |
|
718 | # Build list of namespaces to search from user options | |
719 | def_search.extend(opt('s',[])) |
|
719 | def_search.extend(opt('s',[])) | |
720 | ns_exclude = ns_exclude=opt('e',[]) |
|
720 | ns_exclude = ns_exclude=opt('e',[]) | |
721 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
721 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
722 |
|
722 | |||
723 | # Call the actual search |
|
723 | # Call the actual search | |
724 | try: |
|
724 | try: | |
725 | psearch(args,shell.ns_table,ns_search, |
|
725 | psearch(args,shell.ns_table,ns_search, | |
726 | show_all=opt('a'),ignore_case=ignore_case) |
|
726 | show_all=opt('a'),ignore_case=ignore_case) | |
727 | except: |
|
727 | except: | |
728 | shell.showtraceback() |
|
728 | shell.showtraceback() | |
729 |
|
729 | |||
730 | def magic_who_ls(self, parameter_s=''): |
|
730 | def magic_who_ls(self, parameter_s=''): | |
731 | """Return a sorted list of all interactive variables. |
|
731 | """Return a sorted list of all interactive variables. | |
732 |
|
732 | |||
733 | If arguments are given, only variables of types matching these |
|
733 | If arguments are given, only variables of types matching these | |
734 | arguments are returned.""" |
|
734 | arguments are returned.""" | |
735 |
|
735 | |||
736 | user_ns = self.shell.user_ns |
|
736 | user_ns = self.shell.user_ns | |
737 | internal_ns = self.shell.internal_ns |
|
737 | internal_ns = self.shell.internal_ns | |
738 | user_ns_hidden = self.shell.user_ns_hidden |
|
738 | user_ns_hidden = self.shell.user_ns_hidden | |
739 | out = [ i for i in user_ns |
|
739 | out = [ i for i in user_ns | |
740 | if not i.startswith('_') \ |
|
740 | if not i.startswith('_') \ | |
741 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
741 | and not (i in internal_ns or i in user_ns_hidden) ] | |
742 |
|
742 | |||
743 | typelist = parameter_s.split() |
|
743 | typelist = parameter_s.split() | |
744 | if typelist: |
|
744 | if typelist: | |
745 | typeset = set(typelist) |
|
745 | typeset = set(typelist) | |
746 | out = [i for i in out if type(i).__name__ in typeset] |
|
746 | out = [i for i in out if type(i).__name__ in typeset] | |
747 |
|
747 | |||
748 | out.sort() |
|
748 | out.sort() | |
749 | return out |
|
749 | return out | |
750 |
|
750 | |||
751 | def magic_who(self, parameter_s=''): |
|
751 | def magic_who(self, parameter_s=''): | |
752 | """Print all interactive variables, with some minimal formatting. |
|
752 | """Print all interactive variables, with some minimal formatting. | |
753 |
|
753 | |||
754 | If any arguments are given, only variables whose type matches one of |
|
754 | If any arguments are given, only variables whose type matches one of | |
755 | these are printed. For example: |
|
755 | these are printed. For example: | |
756 |
|
756 | |||
757 | %who function str |
|
757 | %who function str | |
758 |
|
758 | |||
759 | will only list functions and strings, excluding all other types of |
|
759 | will only list functions and strings, excluding all other types of | |
760 | variables. To find the proper type names, simply use type(var) at a |
|
760 | variables. To find the proper type names, simply use type(var) at a | |
761 | command line to see how python prints type names. For example: |
|
761 | command line to see how python prints type names. For example: | |
762 |
|
762 | |||
763 | In [1]: type('hello')\\ |
|
763 | In [1]: type('hello')\\ | |
764 | Out[1]: <type 'str'> |
|
764 | Out[1]: <type 'str'> | |
765 |
|
765 | |||
766 | indicates that the type name for strings is 'str'. |
|
766 | indicates that the type name for strings is 'str'. | |
767 |
|
767 | |||
768 | %who always excludes executed names loaded through your configuration |
|
768 | %who always excludes executed names loaded through your configuration | |
769 | file and things which are internal to IPython. |
|
769 | file and things which are internal to IPython. | |
770 |
|
770 | |||
771 | This is deliberate, as typically you may load many modules and the |
|
771 | This is deliberate, as typically you may load many modules and the | |
772 | purpose of %who is to show you only what you've manually defined.""" |
|
772 | purpose of %who is to show you only what you've manually defined.""" | |
773 |
|
773 | |||
774 | varlist = self.magic_who_ls(parameter_s) |
|
774 | varlist = self.magic_who_ls(parameter_s) | |
775 | if not varlist: |
|
775 | if not varlist: | |
776 | if parameter_s: |
|
776 | if parameter_s: | |
777 | print 'No variables match your requested type.' |
|
777 | print 'No variables match your requested type.' | |
778 | else: |
|
778 | else: | |
779 | print 'Interactive namespace is empty.' |
|
779 | print 'Interactive namespace is empty.' | |
780 | return |
|
780 | return | |
781 |
|
781 | |||
782 | # if we have variables, move on... |
|
782 | # if we have variables, move on... | |
783 | count = 0 |
|
783 | count = 0 | |
784 | for i in varlist: |
|
784 | for i in varlist: | |
785 | print i+'\t', |
|
785 | print i+'\t', | |
786 | count += 1 |
|
786 | count += 1 | |
787 | if count > 8: |
|
787 | if count > 8: | |
788 | count = 0 |
|
788 | count = 0 | |
789 |
|
789 | |||
790 |
|
790 | |||
791 |
|
791 | |||
792 | def magic_whos(self, parameter_s=''): |
|
792 | def magic_whos(self, parameter_s=''): | |
793 | """Like %who, but gives some extra information about each variable. |
|
793 | """Like %who, but gives some extra information about each variable. | |
794 |
|
794 | |||
795 | The same type filtering of %who can be applied here. |
|
795 | The same type filtering of %who can be applied here. | |
796 |
|
796 | |||
797 | For all variables, the type is printed. Additionally it prints: |
|
797 | For all variables, the type is printed. Additionally it prints: | |
798 |
|
798 | |||
799 | - For {},[],(): their length. |
|
799 | - For {},[],(): their length. | |
800 |
|
800 | |||
801 | - For numpy and Numeric arrays, a summary with shape, number of |
|
801 | - For numpy and Numeric arrays, a summary with shape, number of | |
802 | elements, typecode and size in memory. |
|
802 | elements, typecode and size in memory. | |
803 |
|
803 | |||
804 | - Everything else: a string representation, snipping their middle if |
|
804 | - Everything else: a string representation, snipping their middle if | |
805 | too long.""" |
|
805 | too long.""" | |
806 |
|
806 | |||
807 | varnames = self.magic_who_ls(parameter_s) |
|
807 | varnames = self.magic_who_ls(parameter_s) | |
808 | if not varnames: |
|
808 | if not varnames: | |
809 | if parameter_s: |
|
809 | if parameter_s: | |
810 | print 'No variables match your requested type.' |
|
810 | print 'No variables match your requested type.' | |
811 | else: |
|
811 | else: | |
812 | print 'Interactive namespace is empty.' |
|
812 | print 'Interactive namespace is empty.' | |
813 | return |
|
813 | return | |
814 |
|
814 | |||
815 | # if we have variables, move on... |
|
815 | # if we have variables, move on... | |
816 |
|
816 | |||
817 | # for these types, show len() instead of data: |
|
817 | # for these types, show len() instead of data: | |
818 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
818 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
819 |
|
819 | |||
820 | # for numpy/Numeric arrays, display summary info |
|
820 | # for numpy/Numeric arrays, display summary info | |
821 | try: |
|
821 | try: | |
822 | import numpy |
|
822 | import numpy | |
823 | except ImportError: |
|
823 | except ImportError: | |
824 | ndarray_type = None |
|
824 | ndarray_type = None | |
825 | else: |
|
825 | else: | |
826 | ndarray_type = numpy.ndarray.__name__ |
|
826 | ndarray_type = numpy.ndarray.__name__ | |
827 | try: |
|
827 | try: | |
828 | import Numeric |
|
828 | import Numeric | |
829 | except ImportError: |
|
829 | except ImportError: | |
830 | array_type = None |
|
830 | array_type = None | |
831 | else: |
|
831 | else: | |
832 | array_type = Numeric.ArrayType.__name__ |
|
832 | array_type = Numeric.ArrayType.__name__ | |
833 |
|
833 | |||
834 | # Find all variable names and types so we can figure out column sizes |
|
834 | # Find all variable names and types so we can figure out column sizes | |
835 | def get_vars(i): |
|
835 | def get_vars(i): | |
836 | return self.shell.user_ns[i] |
|
836 | return self.shell.user_ns[i] | |
837 |
|
837 | |||
838 | # some types are well known and can be shorter |
|
838 | # some types are well known and can be shorter | |
839 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
839 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
840 | def type_name(v): |
|
840 | def type_name(v): | |
841 | tn = type(v).__name__ |
|
841 | tn = type(v).__name__ | |
842 | return abbrevs.get(tn,tn) |
|
842 | return abbrevs.get(tn,tn) | |
843 |
|
843 | |||
844 | varlist = map(get_vars,varnames) |
|
844 | varlist = map(get_vars,varnames) | |
845 |
|
845 | |||
846 | typelist = [] |
|
846 | typelist = [] | |
847 | for vv in varlist: |
|
847 | for vv in varlist: | |
848 | tt = type_name(vv) |
|
848 | tt = type_name(vv) | |
849 |
|
849 | |||
850 | if tt=='instance': |
|
850 | if tt=='instance': | |
851 | typelist.append( abbrevs.get(str(vv.__class__), |
|
851 | typelist.append( abbrevs.get(str(vv.__class__), | |
852 | str(vv.__class__))) |
|
852 | str(vv.__class__))) | |
853 | else: |
|
853 | else: | |
854 | typelist.append(tt) |
|
854 | typelist.append(tt) | |
855 |
|
855 | |||
856 | # column labels and # of spaces as separator |
|
856 | # column labels and # of spaces as separator | |
857 | varlabel = 'Variable' |
|
857 | varlabel = 'Variable' | |
858 | typelabel = 'Type' |
|
858 | typelabel = 'Type' | |
859 | datalabel = 'Data/Info' |
|
859 | datalabel = 'Data/Info' | |
860 | colsep = 3 |
|
860 | colsep = 3 | |
861 | # variable format strings |
|
861 | # variable format strings | |
862 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
862 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
863 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
863 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
864 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
864 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
865 | # find the size of the columns to format the output nicely |
|
865 | # find the size of the columns to format the output nicely | |
866 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
866 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
867 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
867 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
868 | # table header |
|
868 | # table header | |
869 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
869 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
870 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
870 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
871 | # and the table itself |
|
871 | # and the table itself | |
872 | kb = 1024 |
|
872 | kb = 1024 | |
873 | Mb = 1048576 # kb**2 |
|
873 | Mb = 1048576 # kb**2 | |
874 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
874 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
875 | print itpl(vformat), |
|
875 | print itpl(vformat), | |
876 | if vtype in seq_types: |
|
876 | if vtype in seq_types: | |
877 | print len(var) |
|
877 | print len(var) | |
878 | elif vtype in [array_type,ndarray_type]: |
|
878 | elif vtype in [array_type,ndarray_type]: | |
879 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
879 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
880 | if vtype==ndarray_type: |
|
880 | if vtype==ndarray_type: | |
881 | # numpy |
|
881 | # numpy | |
882 | vsize = var.size |
|
882 | vsize = var.size | |
883 | vbytes = vsize*var.itemsize |
|
883 | vbytes = vsize*var.itemsize | |
884 | vdtype = var.dtype |
|
884 | vdtype = var.dtype | |
885 | else: |
|
885 | else: | |
886 | # Numeric |
|
886 | # Numeric | |
887 | vsize = Numeric.size(var) |
|
887 | vsize = Numeric.size(var) | |
888 | vbytes = vsize*var.itemsize() |
|
888 | vbytes = vsize*var.itemsize() | |
889 | vdtype = var.typecode() |
|
889 | vdtype = var.typecode() | |
890 |
|
890 | |||
891 | if vbytes < 100000: |
|
891 | if vbytes < 100000: | |
892 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
892 | print aformat % (vshape,vsize,vdtype,vbytes) | |
893 | else: |
|
893 | else: | |
894 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
894 | print aformat % (vshape,vsize,vdtype,vbytes), | |
895 | if vbytes < Mb: |
|
895 | if vbytes < Mb: | |
896 | print '(%s kb)' % (vbytes/kb,) |
|
896 | print '(%s kb)' % (vbytes/kb,) | |
897 | else: |
|
897 | else: | |
898 | print '(%s Mb)' % (vbytes/Mb,) |
|
898 | print '(%s Mb)' % (vbytes/Mb,) | |
899 | else: |
|
899 | else: | |
900 | try: |
|
900 | try: | |
901 | vstr = str(var) |
|
901 | vstr = str(var) | |
902 | except UnicodeEncodeError: |
|
902 | except UnicodeEncodeError: | |
903 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
903 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
904 | 'backslashreplace') |
|
904 | 'backslashreplace') | |
905 | vstr = vstr.replace('\n','\\n') |
|
905 | vstr = vstr.replace('\n','\\n') | |
906 | if len(vstr) < 50: |
|
906 | if len(vstr) < 50: | |
907 | print vstr |
|
907 | print vstr | |
908 | else: |
|
908 | else: | |
909 | printpl(vfmt_short) |
|
909 | printpl(vfmt_short) | |
910 |
|
910 | |||
911 | def magic_reset(self, parameter_s=''): |
|
911 | def magic_reset(self, parameter_s=''): | |
912 | """Resets the namespace by removing all names defined by the user. |
|
912 | """Resets the namespace by removing all names defined by the user. | |
913 |
|
913 | |||
914 | Input/Output history are left around in case you need them. |
|
914 | Input/Output history are left around in case you need them. | |
915 |
|
915 | |||
916 | Parameters |
|
916 | Parameters | |
917 | ---------- |
|
917 | ---------- | |
918 | -y : force reset without asking for confirmation. |
|
918 | -y : force reset without asking for confirmation. | |
919 |
|
919 | |||
920 | Examples |
|
920 | Examples | |
921 | -------- |
|
921 | -------- | |
922 | In [6]: a = 1 |
|
922 | In [6]: a = 1 | |
923 |
|
923 | |||
924 | In [7]: a |
|
924 | In [7]: a | |
925 | Out[7]: 1 |
|
925 | Out[7]: 1 | |
926 |
|
926 | |||
927 | In [8]: 'a' in _ip.user_ns |
|
927 | In [8]: 'a' in _ip.user_ns | |
928 | Out[8]: True |
|
928 | Out[8]: True | |
929 |
|
929 | |||
930 | In [9]: %reset -f |
|
930 | In [9]: %reset -f | |
931 |
|
931 | |||
932 | In [10]: 'a' in _ip.user_ns |
|
932 | In [10]: 'a' in _ip.user_ns | |
933 | Out[10]: False |
|
933 | Out[10]: False | |
934 | """ |
|
934 | """ | |
935 |
|
935 | |||
936 | if parameter_s == '-f': |
|
936 | if parameter_s == '-f': | |
937 | ans = True |
|
937 | ans = True | |
938 | else: |
|
938 | else: | |
939 | ans = self.shell.ask_yes_no( |
|
939 | ans = self.shell.ask_yes_no( | |
940 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
940 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
941 | if not ans: |
|
941 | if not ans: | |
942 | print 'Nothing done.' |
|
942 | print 'Nothing done.' | |
943 | return |
|
943 | return | |
944 | user_ns = self.shell.user_ns |
|
944 | user_ns = self.shell.user_ns | |
945 | for i in self.magic_who_ls(): |
|
945 | for i in self.magic_who_ls(): | |
946 | del(user_ns[i]) |
|
946 | del(user_ns[i]) | |
947 |
|
947 | |||
948 | # Also flush the private list of module references kept for script |
|
948 | # Also flush the private list of module references kept for script | |
949 | # execution protection |
|
949 | # execution protection | |
950 | self.shell.clear_main_mod_cache() |
|
950 | self.shell.clear_main_mod_cache() | |
951 |
|
951 | |||
952 | def magic_reset_selective(self, parameter_s=''): |
|
952 | def magic_reset_selective(self, parameter_s=''): | |
953 | """Resets the namespace by removing names defined by the user. |
|
953 | """Resets the namespace by removing names defined by the user. | |
954 |
|
954 | |||
955 | Input/Output history are left around in case you need them. |
|
955 | Input/Output history are left around in case you need them. | |
956 |
|
956 | |||
957 | %reset_selective [-f] regex |
|
957 | %reset_selective [-f] regex | |
958 |
|
958 | |||
959 | No action is taken if regex is not included |
|
959 | No action is taken if regex is not included | |
960 |
|
960 | |||
961 | Options |
|
961 | Options | |
962 | -f : force reset without asking for confirmation. |
|
962 | -f : force reset without asking for confirmation. | |
963 |
|
963 | |||
964 | Examples |
|
964 | Examples | |
965 | -------- |
|
965 | -------- | |
966 |
|
966 | |||
967 | We first fully reset the namespace so your output looks identical to |
|
967 | We first fully reset the namespace so your output looks identical to | |
968 | this example for pedagogical reasons; in practice you do not need a |
|
968 | this example for pedagogical reasons; in practice you do not need a | |
969 | full reset. |
|
969 | full reset. | |
970 |
|
970 | |||
971 | In [1]: %reset -f |
|
971 | In [1]: %reset -f | |
972 |
|
972 | |||
973 | Now, with a clean namespace we can make a few variables and use |
|
973 | Now, with a clean namespace we can make a few variables and use | |
974 | %reset_selective to only delete names that match our regexp: |
|
974 | %reset_selective to only delete names that match our regexp: | |
975 |
|
975 | |||
976 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
976 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
977 |
|
977 | |||
978 | In [3]: who_ls |
|
978 | In [3]: who_ls | |
979 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
979 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
980 |
|
980 | |||
981 | In [4]: %reset_selective -f b[2-3]m |
|
981 | In [4]: %reset_selective -f b[2-3]m | |
982 |
|
982 | |||
983 | In [5]: who_ls |
|
983 | In [5]: who_ls | |
984 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
984 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
985 |
|
985 | |||
986 | In [6]: %reset_selective -f d |
|
986 | In [6]: %reset_selective -f d | |
987 |
|
987 | |||
988 | In [7]: who_ls |
|
988 | In [7]: who_ls | |
989 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
989 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
990 |
|
990 | |||
991 | In [8]: %reset_selective -f c |
|
991 | In [8]: %reset_selective -f c | |
992 |
|
992 | |||
993 | In [9]: who_ls |
|
993 | In [9]: who_ls | |
994 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
994 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
995 |
|
995 | |||
996 | In [10]: %reset_selective -f b |
|
996 | In [10]: %reset_selective -f b | |
997 |
|
997 | |||
998 | In [11]: who_ls |
|
998 | In [11]: who_ls | |
999 | Out[11]: ['a'] |
|
999 | Out[11]: ['a'] | |
1000 | """ |
|
1000 | """ | |
1001 |
|
1001 | |||
1002 | opts, regex = self.parse_options(parameter_s,'f') |
|
1002 | opts, regex = self.parse_options(parameter_s,'f') | |
1003 |
|
1003 | |||
1004 | if opts.has_key('f'): |
|
1004 | if opts.has_key('f'): | |
1005 | ans = True |
|
1005 | ans = True | |
1006 | else: |
|
1006 | else: | |
1007 | ans = self.shell.ask_yes_no( |
|
1007 | ans = self.shell.ask_yes_no( | |
1008 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1008 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1009 | if not ans: |
|
1009 | if not ans: | |
1010 | print 'Nothing done.' |
|
1010 | print 'Nothing done.' | |
1011 | return |
|
1011 | return | |
1012 | user_ns = self.shell.user_ns |
|
1012 | user_ns = self.shell.user_ns | |
1013 | if not regex: |
|
1013 | if not regex: | |
1014 | print 'No regex pattern specified. Nothing done.' |
|
1014 | print 'No regex pattern specified. Nothing done.' | |
1015 | return |
|
1015 | return | |
1016 | else: |
|
1016 | else: | |
1017 | try: |
|
1017 | try: | |
1018 | m = re.compile(regex) |
|
1018 | m = re.compile(regex) | |
1019 | except TypeError: |
|
1019 | except TypeError: | |
1020 | raise TypeError('regex must be a string or compiled pattern') |
|
1020 | raise TypeError('regex must be a string or compiled pattern') | |
1021 | for i in self.magic_who_ls(): |
|
1021 | for i in self.magic_who_ls(): | |
1022 | if m.search(i): |
|
1022 | if m.search(i): | |
1023 | del(user_ns[i]) |
|
1023 | del(user_ns[i]) | |
1024 |
|
1024 | |||
1025 | def magic_logstart(self,parameter_s=''): |
|
1025 | def magic_logstart(self,parameter_s=''): | |
1026 | """Start logging anywhere in a session. |
|
1026 | """Start logging anywhere in a session. | |
1027 |
|
1027 | |||
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1028 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1029 |
|
1029 | |||
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1030 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1031 | current directory, in 'rotate' mode (see below). |
|
1031 | current directory, in 'rotate' mode (see below). | |
1032 |
|
1032 | |||
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1033 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1034 | history up to that point and then continues logging. |
|
1034 | history up to that point and then continues logging. | |
1035 |
|
1035 | |||
1036 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1036 | %logstart takes a second optional parameter: logging mode. This can be one | |
1037 | of (note that the modes are given unquoted):\\ |
|
1037 | of (note that the modes are given unquoted):\\ | |
1038 | append: well, that says it.\\ |
|
1038 | append: well, that says it.\\ | |
1039 | backup: rename (if exists) to name~ and start name.\\ |
|
1039 | backup: rename (if exists) to name~ and start name.\\ | |
1040 | global: single logfile in your home dir, appended to.\\ |
|
1040 | global: single logfile in your home dir, appended to.\\ | |
1041 | over : overwrite existing log.\\ |
|
1041 | over : overwrite existing log.\\ | |
1042 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1042 | rotate: create rotating logs name.1~, name.2~, etc. | |
1043 |
|
1043 | |||
1044 | Options: |
|
1044 | Options: | |
1045 |
|
1045 | |||
1046 | -o: log also IPython's output. In this mode, all commands which |
|
1046 | -o: log also IPython's output. In this mode, all commands which | |
1047 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1047 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1048 | their corresponding input line. The output lines are always |
|
1048 | their corresponding input line. The output lines are always | |
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1049 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1050 | Python code. |
|
1050 | Python code. | |
1051 |
|
1051 | |||
1052 | Since this marker is always the same, filtering only the output from |
|
1052 | Since this marker is always the same, filtering only the output from | |
1053 | a log is very easy, using for example a simple awk call: |
|
1053 | a log is very easy, using for example a simple awk call: | |
1054 |
|
1054 | |||
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1055 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1056 |
|
1056 | |||
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1057 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1058 | input, so that user lines are logged in their final form, converted |
|
1058 | input, so that user lines are logged in their final form, converted | |
1059 | into valid Python. For example, %Exit is logged as |
|
1059 | into valid Python. For example, %Exit is logged as | |
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1060 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1061 | exactly as typed, with no transformations applied. |
|
1061 | exactly as typed, with no transformations applied. | |
1062 |
|
1062 | |||
1063 | -t: put timestamps before each input line logged (these are put in |
|
1063 | -t: put timestamps before each input line logged (these are put in | |
1064 | comments).""" |
|
1064 | comments).""" | |
1065 |
|
1065 | |||
1066 | opts,par = self.parse_options(parameter_s,'ort') |
|
1066 | opts,par = self.parse_options(parameter_s,'ort') | |
1067 | log_output = 'o' in opts |
|
1067 | log_output = 'o' in opts | |
1068 | log_raw_input = 'r' in opts |
|
1068 | log_raw_input = 'r' in opts | |
1069 | timestamp = 't' in opts |
|
1069 | timestamp = 't' in opts | |
1070 |
|
1070 | |||
1071 | logger = self.shell.logger |
|
1071 | logger = self.shell.logger | |
1072 |
|
1072 | |||
1073 | # if no args are given, the defaults set in the logger constructor by |
|
1073 | # if no args are given, the defaults set in the logger constructor by | |
1074 | # ipytohn remain valid |
|
1074 | # ipytohn remain valid | |
1075 | if par: |
|
1075 | if par: | |
1076 | try: |
|
1076 | try: | |
1077 | logfname,logmode = par.split() |
|
1077 | logfname,logmode = par.split() | |
1078 | except: |
|
1078 | except: | |
1079 | logfname = par |
|
1079 | logfname = par | |
1080 | logmode = 'backup' |
|
1080 | logmode = 'backup' | |
1081 | else: |
|
1081 | else: | |
1082 | logfname = logger.logfname |
|
1082 | logfname = logger.logfname | |
1083 | logmode = logger.logmode |
|
1083 | logmode = logger.logmode | |
1084 | # put logfname into rc struct as if it had been called on the command |
|
1084 | # put logfname into rc struct as if it had been called on the command | |
1085 | # line, so it ends up saved in the log header Save it in case we need |
|
1085 | # line, so it ends up saved in the log header Save it in case we need | |
1086 | # to restore it... |
|
1086 | # to restore it... | |
1087 | old_logfile = self.shell.logfile |
|
1087 | old_logfile = self.shell.logfile | |
1088 | if logfname: |
|
1088 | if logfname: | |
1089 | logfname = os.path.expanduser(logfname) |
|
1089 | logfname = os.path.expanduser(logfname) | |
1090 | self.shell.logfile = logfname |
|
1090 | self.shell.logfile = logfname | |
1091 |
|
1091 | |||
1092 | loghead = '# IPython log file\n\n' |
|
1092 | loghead = '# IPython log file\n\n' | |
1093 | try: |
|
1093 | try: | |
1094 | started = logger.logstart(logfname,loghead,logmode, |
|
1094 | started = logger.logstart(logfname,loghead,logmode, | |
1095 | log_output,timestamp,log_raw_input) |
|
1095 | log_output,timestamp,log_raw_input) | |
1096 | except: |
|
1096 | except: | |
1097 | self.shell.logfile = old_logfile |
|
1097 | self.shell.logfile = old_logfile | |
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1098 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1099 | else: |
|
1099 | else: | |
1100 | # log input history up to this point, optionally interleaving |
|
1100 | # log input history up to this point, optionally interleaving | |
1101 | # output if requested |
|
1101 | # output if requested | |
1102 |
|
1102 | |||
1103 | if timestamp: |
|
1103 | if timestamp: | |
1104 | # disable timestamping for the previous history, since we've |
|
1104 | # disable timestamping for the previous history, since we've | |
1105 | # lost those already (no time machine here). |
|
1105 | # lost those already (no time machine here). | |
1106 | logger.timestamp = False |
|
1106 | logger.timestamp = False | |
1107 |
|
1107 | |||
1108 | if log_raw_input: |
|
1108 | if log_raw_input: | |
1109 | input_hist = self.shell.input_hist_raw |
|
1109 | input_hist = self.shell.history_manager.input_hist_raw | |
1110 | else: |
|
1110 | else: | |
1111 | input_hist = self.shell.input_hist |
|
1111 | input_hist = self.shell.history_manager.input_hist_parsed | |
1112 |
|
1112 | |||
1113 | if log_output: |
|
1113 | if log_output: | |
1114 | log_write = logger.log_write |
|
1114 | log_write = logger.log_write | |
1115 | output_hist = self.shell.output_hist |
|
1115 | output_hist = self.shell.history_manager.output_hist | |
1116 | for n in range(1,len(input_hist)-1): |
|
1116 | for n in range(1,len(input_hist)-1): | |
1117 | log_write(input_hist[n].rstrip()) |
|
1117 | log_write(input_hist[n].rstrip()) | |
1118 | if n in output_hist: |
|
1118 | if n in output_hist: | |
1119 | log_write(repr(output_hist[n]),'output') |
|
1119 | log_write(repr(output_hist[n]),'output') | |
1120 | else: |
|
1120 | else: | |
1121 | logger.log_write(input_hist[1:]) |
|
1121 | logger.log_write(''.join(input_hist[1:])) | |
1122 | if timestamp: |
|
1122 | if timestamp: | |
1123 | # re-enable timestamping |
|
1123 | # re-enable timestamping | |
1124 | logger.timestamp = True |
|
1124 | logger.timestamp = True | |
1125 |
|
1125 | |||
1126 | print ('Activating auto-logging. ' |
|
1126 | print ('Activating auto-logging. ' | |
1127 | 'Current session state plus future input saved.') |
|
1127 | 'Current session state plus future input saved.') | |
1128 | logger.logstate() |
|
1128 | logger.logstate() | |
1129 |
|
1129 | |||
1130 | def magic_logstop(self,parameter_s=''): |
|
1130 | def magic_logstop(self,parameter_s=''): | |
1131 | """Fully stop logging and close log file. |
|
1131 | """Fully stop logging and close log file. | |
1132 |
|
1132 | |||
1133 | In order to start logging again, a new %logstart call needs to be made, |
|
1133 | In order to start logging again, a new %logstart call needs to be made, | |
1134 | possibly (though not necessarily) with a new filename, mode and other |
|
1134 | possibly (though not necessarily) with a new filename, mode and other | |
1135 | options.""" |
|
1135 | options.""" | |
1136 | self.logger.logstop() |
|
1136 | self.logger.logstop() | |
1137 |
|
1137 | |||
1138 | def magic_logoff(self,parameter_s=''): |
|
1138 | def magic_logoff(self,parameter_s=''): | |
1139 | """Temporarily stop logging. |
|
1139 | """Temporarily stop logging. | |
1140 |
|
1140 | |||
1141 | You must have previously started logging.""" |
|
1141 | You must have previously started logging.""" | |
1142 | self.shell.logger.switch_log(0) |
|
1142 | self.shell.logger.switch_log(0) | |
1143 |
|
1143 | |||
1144 | def magic_logon(self,parameter_s=''): |
|
1144 | def magic_logon(self,parameter_s=''): | |
1145 | """Restart logging. |
|
1145 | """Restart logging. | |
1146 |
|
1146 | |||
1147 | This function is for restarting logging which you've temporarily |
|
1147 | This function is for restarting logging which you've temporarily | |
1148 | stopped with %logoff. For starting logging for the first time, you |
|
1148 | stopped with %logoff. For starting logging for the first time, you | |
1149 | must use the %logstart function, which allows you to specify an |
|
1149 | must use the %logstart function, which allows you to specify an | |
1150 | optional log filename.""" |
|
1150 | optional log filename.""" | |
1151 |
|
1151 | |||
1152 | self.shell.logger.switch_log(1) |
|
1152 | self.shell.logger.switch_log(1) | |
1153 |
|
1153 | |||
1154 | def magic_logstate(self,parameter_s=''): |
|
1154 | def magic_logstate(self,parameter_s=''): | |
1155 | """Print the status of the logging system.""" |
|
1155 | """Print the status of the logging system.""" | |
1156 |
|
1156 | |||
1157 | self.shell.logger.logstate() |
|
1157 | self.shell.logger.logstate() | |
1158 |
|
1158 | |||
1159 | def magic_pdb(self, parameter_s=''): |
|
1159 | def magic_pdb(self, parameter_s=''): | |
1160 | """Control the automatic calling of the pdb interactive debugger. |
|
1160 | """Control the automatic calling of the pdb interactive debugger. | |
1161 |
|
1161 | |||
1162 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1162 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1163 | argument it works as a toggle. |
|
1163 | argument it works as a toggle. | |
1164 |
|
1164 | |||
1165 | When an exception is triggered, IPython can optionally call the |
|
1165 | When an exception is triggered, IPython can optionally call the | |
1166 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1166 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1167 | this feature on and off. |
|
1167 | this feature on and off. | |
1168 |
|
1168 | |||
1169 | The initial state of this feature is set in your ipythonrc |
|
1169 | The initial state of this feature is set in your ipythonrc | |
1170 | configuration file (the variable is called 'pdb'). |
|
1170 | configuration file (the variable is called 'pdb'). | |
1171 |
|
1171 | |||
1172 | If you want to just activate the debugger AFTER an exception has fired, |
|
1172 | If you want to just activate the debugger AFTER an exception has fired, | |
1173 | without having to type '%pdb on' and rerunning your code, you can use |
|
1173 | without having to type '%pdb on' and rerunning your code, you can use | |
1174 | the %debug magic.""" |
|
1174 | the %debug magic.""" | |
1175 |
|
1175 | |||
1176 | par = parameter_s.strip().lower() |
|
1176 | par = parameter_s.strip().lower() | |
1177 |
|
1177 | |||
1178 | if par: |
|
1178 | if par: | |
1179 | try: |
|
1179 | try: | |
1180 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1180 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1181 | except KeyError: |
|
1181 | except KeyError: | |
1182 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1182 | print ('Incorrect argument. Use on/1, off/0, ' | |
1183 | 'or nothing for a toggle.') |
|
1183 | 'or nothing for a toggle.') | |
1184 | return |
|
1184 | return | |
1185 | else: |
|
1185 | else: | |
1186 | # toggle |
|
1186 | # toggle | |
1187 | new_pdb = not self.shell.call_pdb |
|
1187 | new_pdb = not self.shell.call_pdb | |
1188 |
|
1188 | |||
1189 | # set on the shell |
|
1189 | # set on the shell | |
1190 | self.shell.call_pdb = new_pdb |
|
1190 | self.shell.call_pdb = new_pdb | |
1191 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1191 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1192 |
|
1192 | |||
1193 | def magic_debug(self, parameter_s=''): |
|
1193 | def magic_debug(self, parameter_s=''): | |
1194 | """Activate the interactive debugger in post-mortem mode. |
|
1194 | """Activate the interactive debugger in post-mortem mode. | |
1195 |
|
1195 | |||
1196 | If an exception has just occurred, this lets you inspect its stack |
|
1196 | If an exception has just occurred, this lets you inspect its stack | |
1197 | frames interactively. Note that this will always work only on the last |
|
1197 | frames interactively. Note that this will always work only on the last | |
1198 | traceback that occurred, so you must call this quickly after an |
|
1198 | traceback that occurred, so you must call this quickly after an | |
1199 | exception that you wish to inspect has fired, because if another one |
|
1199 | exception that you wish to inspect has fired, because if another one | |
1200 | occurs, it clobbers the previous one. |
|
1200 | occurs, it clobbers the previous one. | |
1201 |
|
1201 | |||
1202 | If you want IPython to automatically do this on every exception, see |
|
1202 | If you want IPython to automatically do this on every exception, see | |
1203 | the %pdb magic for more details. |
|
1203 | the %pdb magic for more details. | |
1204 | """ |
|
1204 | """ | |
1205 | self.shell.debugger(force=True) |
|
1205 | self.shell.debugger(force=True) | |
1206 |
|
1206 | |||
1207 | @testdec.skip_doctest |
|
1207 | @testdec.skip_doctest | |
1208 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1208 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1209 | opts=None,arg_lst=None,prog_ns=None): |
|
1209 | opts=None,arg_lst=None,prog_ns=None): | |
1210 |
|
1210 | |||
1211 | """Run a statement through the python code profiler. |
|
1211 | """Run a statement through the python code profiler. | |
1212 |
|
1212 | |||
1213 | Usage: |
|
1213 | Usage: | |
1214 | %prun [options] statement |
|
1214 | %prun [options] statement | |
1215 |
|
1215 | |||
1216 | The given statement (which doesn't require quote marks) is run via the |
|
1216 | The given statement (which doesn't require quote marks) is run via the | |
1217 | python profiler in a manner similar to the profile.run() function. |
|
1217 | python profiler in a manner similar to the profile.run() function. | |
1218 | Namespaces are internally managed to work correctly; profile.run |
|
1218 | Namespaces are internally managed to work correctly; profile.run | |
1219 | cannot be used in IPython because it makes certain assumptions about |
|
1219 | cannot be used in IPython because it makes certain assumptions about | |
1220 | namespaces which do not hold under IPython. |
|
1220 | namespaces which do not hold under IPython. | |
1221 |
|
1221 | |||
1222 | Options: |
|
1222 | Options: | |
1223 |
|
1223 | |||
1224 | -l <limit>: you can place restrictions on what or how much of the |
|
1224 | -l <limit>: you can place restrictions on what or how much of the | |
1225 | profile gets printed. The limit value can be: |
|
1225 | profile gets printed. The limit value can be: | |
1226 |
|
1226 | |||
1227 | * A string: only information for function names containing this string |
|
1227 | * A string: only information for function names containing this string | |
1228 | is printed. |
|
1228 | is printed. | |
1229 |
|
1229 | |||
1230 | * An integer: only these many lines are printed. |
|
1230 | * An integer: only these many lines are printed. | |
1231 |
|
1231 | |||
1232 | * A float (between 0 and 1): this fraction of the report is printed |
|
1232 | * A float (between 0 and 1): this fraction of the report is printed | |
1233 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1233 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1234 |
|
1234 | |||
1235 | You can combine several limits with repeated use of the option. For |
|
1235 | You can combine several limits with repeated use of the option. For | |
1236 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1236 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1237 | information about class constructors. |
|
1237 | information about class constructors. | |
1238 |
|
1238 | |||
1239 | -r: return the pstats.Stats object generated by the profiling. This |
|
1239 | -r: return the pstats.Stats object generated by the profiling. This | |
1240 | object has all the information about the profile in it, and you can |
|
1240 | object has all the information about the profile in it, and you can | |
1241 | later use it for further analysis or in other functions. |
|
1241 | later use it for further analysis or in other functions. | |
1242 |
|
1242 | |||
1243 | -s <key>: sort profile by given key. You can provide more than one key |
|
1243 | -s <key>: sort profile by given key. You can provide more than one key | |
1244 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1244 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1245 | default sorting key is 'time'. |
|
1245 | default sorting key is 'time'. | |
1246 |
|
1246 | |||
1247 | The following is copied verbatim from the profile documentation |
|
1247 | The following is copied verbatim from the profile documentation | |
1248 | referenced below: |
|
1248 | referenced below: | |
1249 |
|
1249 | |||
1250 | When more than one key is provided, additional keys are used as |
|
1250 | When more than one key is provided, additional keys are used as | |
1251 | secondary criteria when the there is equality in all keys selected |
|
1251 | secondary criteria when the there is equality in all keys selected | |
1252 | before them. |
|
1252 | before them. | |
1253 |
|
1253 | |||
1254 | Abbreviations can be used for any key names, as long as the |
|
1254 | Abbreviations can be used for any key names, as long as the | |
1255 | abbreviation is unambiguous. The following are the keys currently |
|
1255 | abbreviation is unambiguous. The following are the keys currently | |
1256 | defined: |
|
1256 | defined: | |
1257 |
|
1257 | |||
1258 | Valid Arg Meaning |
|
1258 | Valid Arg Meaning | |
1259 | "calls" call count |
|
1259 | "calls" call count | |
1260 | "cumulative" cumulative time |
|
1260 | "cumulative" cumulative time | |
1261 | "file" file name |
|
1261 | "file" file name | |
1262 | "module" file name |
|
1262 | "module" file name | |
1263 | "pcalls" primitive call count |
|
1263 | "pcalls" primitive call count | |
1264 | "line" line number |
|
1264 | "line" line number | |
1265 | "name" function name |
|
1265 | "name" function name | |
1266 | "nfl" name/file/line |
|
1266 | "nfl" name/file/line | |
1267 | "stdname" standard name |
|
1267 | "stdname" standard name | |
1268 | "time" internal time |
|
1268 | "time" internal time | |
1269 |
|
1269 | |||
1270 | Note that all sorts on statistics are in descending order (placing |
|
1270 | Note that all sorts on statistics are in descending order (placing | |
1271 | most time consuming items first), where as name, file, and line number |
|
1271 | most time consuming items first), where as name, file, and line number | |
1272 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1272 | searches are in ascending order (i.e., alphabetical). The subtle | |
1273 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1273 | distinction between "nfl" and "stdname" is that the standard name is a | |
1274 | sort of the name as printed, which means that the embedded line |
|
1274 | sort of the name as printed, which means that the embedded line | |
1275 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1275 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1276 | would (if the file names were the same) appear in the string order |
|
1276 | would (if the file names were the same) appear in the string order | |
1277 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1277 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1278 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1278 | line numbers. In fact, sort_stats("nfl") is the same as | |
1279 | sort_stats("name", "file", "line"). |
|
1279 | sort_stats("name", "file", "line"). | |
1280 |
|
1280 | |||
1281 | -T <filename>: save profile results as shown on screen to a text |
|
1281 | -T <filename>: save profile results as shown on screen to a text | |
1282 | file. The profile is still shown on screen. |
|
1282 | file. The profile is still shown on screen. | |
1283 |
|
1283 | |||
1284 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1284 | -D <filename>: save (via dump_stats) profile statistics to given | |
1285 | filename. This data is in a format understod by the pstats module, and |
|
1285 | filename. This data is in a format understod by the pstats module, and | |
1286 | is generated by a call to the dump_stats() method of profile |
|
1286 | is generated by a call to the dump_stats() method of profile | |
1287 | objects. The profile is still shown on screen. |
|
1287 | objects. The profile is still shown on screen. | |
1288 |
|
1288 | |||
1289 | If you want to run complete programs under the profiler's control, use |
|
1289 | If you want to run complete programs under the profiler's control, use | |
1290 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1290 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1291 | contains profiler specific options as described here. |
|
1291 | contains profiler specific options as described here. | |
1292 |
|
1292 | |||
1293 | You can read the complete documentation for the profile module with:: |
|
1293 | You can read the complete documentation for the profile module with:: | |
1294 |
|
1294 | |||
1295 | In [1]: import profile; profile.help() |
|
1295 | In [1]: import profile; profile.help() | |
1296 | """ |
|
1296 | """ | |
1297 |
|
1297 | |||
1298 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1298 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1299 | # protect user quote marks |
|
1299 | # protect user quote marks | |
1300 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1300 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1301 |
|
1301 | |||
1302 | if user_mode: # regular user call |
|
1302 | if user_mode: # regular user call | |
1303 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1303 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1304 | list_all=1) |
|
1304 | list_all=1) | |
1305 | namespace = self.shell.user_ns |
|
1305 | namespace = self.shell.user_ns | |
1306 | else: # called to run a program by %run -p |
|
1306 | else: # called to run a program by %run -p | |
1307 | try: |
|
1307 | try: | |
1308 | filename = get_py_filename(arg_lst[0]) |
|
1308 | filename = get_py_filename(arg_lst[0]) | |
1309 | except IOError,msg: |
|
1309 | except IOError,msg: | |
1310 | error(msg) |
|
1310 | error(msg) | |
1311 | return |
|
1311 | return | |
1312 |
|
1312 | |||
1313 | arg_str = 'execfile(filename,prog_ns)' |
|
1313 | arg_str = 'execfile(filename,prog_ns)' | |
1314 | namespace = locals() |
|
1314 | namespace = locals() | |
1315 |
|
1315 | |||
1316 | opts.merge(opts_def) |
|
1316 | opts.merge(opts_def) | |
1317 |
|
1317 | |||
1318 | prof = profile.Profile() |
|
1318 | prof = profile.Profile() | |
1319 | try: |
|
1319 | try: | |
1320 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1320 | prof = prof.runctx(arg_str,namespace,namespace) | |
1321 | sys_exit = '' |
|
1321 | sys_exit = '' | |
1322 | except SystemExit: |
|
1322 | except SystemExit: | |
1323 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1323 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1324 |
|
1324 | |||
1325 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1325 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1326 |
|
1326 | |||
1327 | lims = opts.l |
|
1327 | lims = opts.l | |
1328 | if lims: |
|
1328 | if lims: | |
1329 | lims = [] # rebuild lims with ints/floats/strings |
|
1329 | lims = [] # rebuild lims with ints/floats/strings | |
1330 | for lim in opts.l: |
|
1330 | for lim in opts.l: | |
1331 | try: |
|
1331 | try: | |
1332 | lims.append(int(lim)) |
|
1332 | lims.append(int(lim)) | |
1333 | except ValueError: |
|
1333 | except ValueError: | |
1334 | try: |
|
1334 | try: | |
1335 | lims.append(float(lim)) |
|
1335 | lims.append(float(lim)) | |
1336 | except ValueError: |
|
1336 | except ValueError: | |
1337 | lims.append(lim) |
|
1337 | lims.append(lim) | |
1338 |
|
1338 | |||
1339 | # Trap output. |
|
1339 | # Trap output. | |
1340 | stdout_trap = StringIO() |
|
1340 | stdout_trap = StringIO() | |
1341 |
|
1341 | |||
1342 | if hasattr(stats,'stream'): |
|
1342 | if hasattr(stats,'stream'): | |
1343 | # In newer versions of python, the stats object has a 'stream' |
|
1343 | # In newer versions of python, the stats object has a 'stream' | |
1344 | # attribute to write into. |
|
1344 | # attribute to write into. | |
1345 | stats.stream = stdout_trap |
|
1345 | stats.stream = stdout_trap | |
1346 | stats.print_stats(*lims) |
|
1346 | stats.print_stats(*lims) | |
1347 | else: |
|
1347 | else: | |
1348 | # For older versions, we manually redirect stdout during printing |
|
1348 | # For older versions, we manually redirect stdout during printing | |
1349 | sys_stdout = sys.stdout |
|
1349 | sys_stdout = sys.stdout | |
1350 | try: |
|
1350 | try: | |
1351 | sys.stdout = stdout_trap |
|
1351 | sys.stdout = stdout_trap | |
1352 | stats.print_stats(*lims) |
|
1352 | stats.print_stats(*lims) | |
1353 | finally: |
|
1353 | finally: | |
1354 | sys.stdout = sys_stdout |
|
1354 | sys.stdout = sys_stdout | |
1355 |
|
1355 | |||
1356 | output = stdout_trap.getvalue() |
|
1356 | output = stdout_trap.getvalue() | |
1357 | output = output.rstrip() |
|
1357 | output = output.rstrip() | |
1358 |
|
1358 | |||
1359 | page.page(output) |
|
1359 | page.page(output) | |
1360 | print sys_exit, |
|
1360 | print sys_exit, | |
1361 |
|
1361 | |||
1362 | dump_file = opts.D[0] |
|
1362 | dump_file = opts.D[0] | |
1363 | text_file = opts.T[0] |
|
1363 | text_file = opts.T[0] | |
1364 | if dump_file: |
|
1364 | if dump_file: | |
1365 | prof.dump_stats(dump_file) |
|
1365 | prof.dump_stats(dump_file) | |
1366 | print '\n*** Profile stats marshalled to file',\ |
|
1366 | print '\n*** Profile stats marshalled to file',\ | |
1367 | `dump_file`+'.',sys_exit |
|
1367 | `dump_file`+'.',sys_exit | |
1368 | if text_file: |
|
1368 | if text_file: | |
1369 | pfile = file(text_file,'w') |
|
1369 | pfile = file(text_file,'w') | |
1370 | pfile.write(output) |
|
1370 | pfile.write(output) | |
1371 | pfile.close() |
|
1371 | pfile.close() | |
1372 | print '\n*** Profile printout saved to text file',\ |
|
1372 | print '\n*** Profile printout saved to text file',\ | |
1373 | `text_file`+'.',sys_exit |
|
1373 | `text_file`+'.',sys_exit | |
1374 |
|
1374 | |||
1375 | if opts.has_key('r'): |
|
1375 | if opts.has_key('r'): | |
1376 | return stats |
|
1376 | return stats | |
1377 | else: |
|
1377 | else: | |
1378 | return None |
|
1378 | return None | |
1379 |
|
1379 | |||
1380 | @testdec.skip_doctest |
|
1380 | @testdec.skip_doctest | |
1381 | def magic_run(self, parameter_s ='',runner=None, |
|
1381 | def magic_run(self, parameter_s ='',runner=None, | |
1382 | file_finder=get_py_filename): |
|
1382 | file_finder=get_py_filename): | |
1383 | """Run the named file inside IPython as a program. |
|
1383 | """Run the named file inside IPython as a program. | |
1384 |
|
1384 | |||
1385 | Usage:\\ |
|
1385 | Usage:\\ | |
1386 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1386 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1387 |
|
1387 | |||
1388 | Parameters after the filename are passed as command-line arguments to |
|
1388 | Parameters after the filename are passed as command-line arguments to | |
1389 | the program (put in sys.argv). Then, control returns to IPython's |
|
1389 | the program (put in sys.argv). Then, control returns to IPython's | |
1390 | prompt. |
|
1390 | prompt. | |
1391 |
|
1391 | |||
1392 | This is similar to running at a system prompt:\\ |
|
1392 | This is similar to running at a system prompt:\\ | |
1393 | $ python file args\\ |
|
1393 | $ python file args\\ | |
1394 | but with the advantage of giving you IPython's tracebacks, and of |
|
1394 | but with the advantage of giving you IPython's tracebacks, and of | |
1395 | loading all variables into your interactive namespace for further use |
|
1395 | loading all variables into your interactive namespace for further use | |
1396 | (unless -p is used, see below). |
|
1396 | (unless -p is used, see below). | |
1397 |
|
1397 | |||
1398 | The file is executed in a namespace initially consisting only of |
|
1398 | The file is executed in a namespace initially consisting only of | |
1399 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1399 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1400 | sees its environment as if it were being run as a stand-alone program |
|
1400 | sees its environment as if it were being run as a stand-alone program | |
1401 | (except for sharing global objects such as previously imported |
|
1401 | (except for sharing global objects such as previously imported | |
1402 | modules). But after execution, the IPython interactive namespace gets |
|
1402 | modules). But after execution, the IPython interactive namespace gets | |
1403 | updated with all variables defined in the program (except for __name__ |
|
1403 | updated with all variables defined in the program (except for __name__ | |
1404 | and sys.argv). This allows for very convenient loading of code for |
|
1404 | and sys.argv). This allows for very convenient loading of code for | |
1405 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1405 | interactive work, while giving each program a 'clean sheet' to run in. | |
1406 |
|
1406 | |||
1407 | Options: |
|
1407 | Options: | |
1408 |
|
1408 | |||
1409 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1409 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1410 | without extension (as python does under import). This allows running |
|
1410 | without extension (as python does under import). This allows running | |
1411 | scripts and reloading the definitions in them without calling code |
|
1411 | scripts and reloading the definitions in them without calling code | |
1412 | protected by an ' if __name__ == "__main__" ' clause. |
|
1412 | protected by an ' if __name__ == "__main__" ' clause. | |
1413 |
|
1413 | |||
1414 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1414 | -i: run the file in IPython's namespace instead of an empty one. This | |
1415 | is useful if you are experimenting with code written in a text editor |
|
1415 | is useful if you are experimenting with code written in a text editor | |
1416 | which depends on variables defined interactively. |
|
1416 | which depends on variables defined interactively. | |
1417 |
|
1417 | |||
1418 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1418 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1419 | being run. This is particularly useful if IPython is being used to |
|
1419 | being run. This is particularly useful if IPython is being used to | |
1420 | run unittests, which always exit with a sys.exit() call. In such |
|
1420 | run unittests, which always exit with a sys.exit() call. In such | |
1421 | cases you are interested in the output of the test results, not in |
|
1421 | cases you are interested in the output of the test results, not in | |
1422 | seeing a traceback of the unittest module. |
|
1422 | seeing a traceback of the unittest module. | |
1423 |
|
1423 | |||
1424 | -t: print timing information at the end of the run. IPython will give |
|
1424 | -t: print timing information at the end of the run. IPython will give | |
1425 | you an estimated CPU time consumption for your script, which under |
|
1425 | you an estimated CPU time consumption for your script, which under | |
1426 | Unix uses the resource module to avoid the wraparound problems of |
|
1426 | Unix uses the resource module to avoid the wraparound problems of | |
1427 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1427 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1428 | is also given (for Windows platforms this is reported as 0.0). |
|
1428 | is also given (for Windows platforms this is reported as 0.0). | |
1429 |
|
1429 | |||
1430 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1430 | If -t is given, an additional -N<N> option can be given, where <N> | |
1431 | must be an integer indicating how many times you want the script to |
|
1431 | must be an integer indicating how many times you want the script to | |
1432 | run. The final timing report will include total and per run results. |
|
1432 | run. The final timing report will include total and per run results. | |
1433 |
|
1433 | |||
1434 | For example (testing the script uniq_stable.py): |
|
1434 | For example (testing the script uniq_stable.py): | |
1435 |
|
1435 | |||
1436 | In [1]: run -t uniq_stable |
|
1436 | In [1]: run -t uniq_stable | |
1437 |
|
1437 | |||
1438 | IPython CPU timings (estimated):\\ |
|
1438 | IPython CPU timings (estimated):\\ | |
1439 | User : 0.19597 s.\\ |
|
1439 | User : 0.19597 s.\\ | |
1440 | System: 0.0 s.\\ |
|
1440 | System: 0.0 s.\\ | |
1441 |
|
1441 | |||
1442 | In [2]: run -t -N5 uniq_stable |
|
1442 | In [2]: run -t -N5 uniq_stable | |
1443 |
|
1443 | |||
1444 | IPython CPU timings (estimated):\\ |
|
1444 | IPython CPU timings (estimated):\\ | |
1445 | Total runs performed: 5\\ |
|
1445 | Total runs performed: 5\\ | |
1446 | Times : Total Per run\\ |
|
1446 | Times : Total Per run\\ | |
1447 | User : 0.910862 s, 0.1821724 s.\\ |
|
1447 | User : 0.910862 s, 0.1821724 s.\\ | |
1448 | System: 0.0 s, 0.0 s. |
|
1448 | System: 0.0 s, 0.0 s. | |
1449 |
|
1449 | |||
1450 | -d: run your program under the control of pdb, the Python debugger. |
|
1450 | -d: run your program under the control of pdb, the Python debugger. | |
1451 | This allows you to execute your program step by step, watch variables, |
|
1451 | This allows you to execute your program step by step, watch variables, | |
1452 | etc. Internally, what IPython does is similar to calling: |
|
1452 | etc. Internally, what IPython does is similar to calling: | |
1453 |
|
1453 | |||
1454 | pdb.run('execfile("YOURFILENAME")') |
|
1454 | pdb.run('execfile("YOURFILENAME")') | |
1455 |
|
1455 | |||
1456 | with a breakpoint set on line 1 of your file. You can change the line |
|
1456 | with a breakpoint set on line 1 of your file. You can change the line | |
1457 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1457 | number for this automatic breakpoint to be <N> by using the -bN option | |
1458 | (where N must be an integer). For example: |
|
1458 | (where N must be an integer). For example: | |
1459 |
|
1459 | |||
1460 | %run -d -b40 myscript |
|
1460 | %run -d -b40 myscript | |
1461 |
|
1461 | |||
1462 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1462 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1463 | the first breakpoint must be set on a line which actually does |
|
1463 | the first breakpoint must be set on a line which actually does | |
1464 | something (not a comment or docstring) for it to stop execution. |
|
1464 | something (not a comment or docstring) for it to stop execution. | |
1465 |
|
1465 | |||
1466 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1466 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1467 | first enter 'c' (without qoutes) to start execution up to the first |
|
1467 | first enter 'c' (without qoutes) to start execution up to the first | |
1468 | breakpoint. |
|
1468 | breakpoint. | |
1469 |
|
1469 | |||
1470 | Entering 'help' gives information about the use of the debugger. You |
|
1470 | Entering 'help' gives information about the use of the debugger. You | |
1471 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1471 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1472 | at a prompt. |
|
1472 | at a prompt. | |
1473 |
|
1473 | |||
1474 | -p: run program under the control of the Python profiler module (which |
|
1474 | -p: run program under the control of the Python profiler module (which | |
1475 | prints a detailed report of execution times, function calls, etc). |
|
1475 | prints a detailed report of execution times, function calls, etc). | |
1476 |
|
1476 | |||
1477 | You can pass other options after -p which affect the behavior of the |
|
1477 | You can pass other options after -p which affect the behavior of the | |
1478 | profiler itself. See the docs for %prun for details. |
|
1478 | profiler itself. See the docs for %prun for details. | |
1479 |
|
1479 | |||
1480 | In this mode, the program's variables do NOT propagate back to the |
|
1480 | In this mode, the program's variables do NOT propagate back to the | |
1481 | IPython interactive namespace (because they remain in the namespace |
|
1481 | IPython interactive namespace (because they remain in the namespace | |
1482 | where the profiler executes them). |
|
1482 | where the profiler executes them). | |
1483 |
|
1483 | |||
1484 | Internally this triggers a call to %prun, see its documentation for |
|
1484 | Internally this triggers a call to %prun, see its documentation for | |
1485 | details on the options available specifically for profiling. |
|
1485 | details on the options available specifically for profiling. | |
1486 |
|
1486 | |||
1487 | There is one special usage for which the text above doesn't apply: |
|
1487 | There is one special usage for which the text above doesn't apply: | |
1488 | if the filename ends with .ipy, the file is run as ipython script, |
|
1488 | if the filename ends with .ipy, the file is run as ipython script, | |
1489 | just as if the commands were written on IPython prompt. |
|
1489 | just as if the commands were written on IPython prompt. | |
1490 | """ |
|
1490 | """ | |
1491 |
|
1491 | |||
1492 | # get arguments and set sys.argv for program to be run. |
|
1492 | # get arguments and set sys.argv for program to be run. | |
1493 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1493 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1494 | mode='list',list_all=1) |
|
1494 | mode='list',list_all=1) | |
1495 |
|
1495 | |||
1496 | try: |
|
1496 | try: | |
1497 | filename = file_finder(arg_lst[0]) |
|
1497 | filename = file_finder(arg_lst[0]) | |
1498 | except IndexError: |
|
1498 | except IndexError: | |
1499 | warn('you must provide at least a filename.') |
|
1499 | warn('you must provide at least a filename.') | |
1500 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1500 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1501 | return |
|
1501 | return | |
1502 | except IOError,msg: |
|
1502 | except IOError,msg: | |
1503 | error(msg) |
|
1503 | error(msg) | |
1504 | return |
|
1504 | return | |
1505 |
|
1505 | |||
1506 | if filename.lower().endswith('.ipy'): |
|
1506 | if filename.lower().endswith('.ipy'): | |
1507 | self.shell.safe_execfile_ipy(filename) |
|
1507 | self.shell.safe_execfile_ipy(filename) | |
1508 | return |
|
1508 | return | |
1509 |
|
1509 | |||
1510 | # Control the response to exit() calls made by the script being run |
|
1510 | # Control the response to exit() calls made by the script being run | |
1511 | exit_ignore = opts.has_key('e') |
|
1511 | exit_ignore = opts.has_key('e') | |
1512 |
|
1512 | |||
1513 | # Make sure that the running script gets a proper sys.argv as if it |
|
1513 | # Make sure that the running script gets a proper sys.argv as if it | |
1514 | # were run from a system shell. |
|
1514 | # were run from a system shell. | |
1515 | save_argv = sys.argv # save it for later restoring |
|
1515 | save_argv = sys.argv # save it for later restoring | |
1516 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1516 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1517 |
|
1517 | |||
1518 | if opts.has_key('i'): |
|
1518 | if opts.has_key('i'): | |
1519 | # Run in user's interactive namespace |
|
1519 | # Run in user's interactive namespace | |
1520 | prog_ns = self.shell.user_ns |
|
1520 | prog_ns = self.shell.user_ns | |
1521 | __name__save = self.shell.user_ns['__name__'] |
|
1521 | __name__save = self.shell.user_ns['__name__'] | |
1522 | prog_ns['__name__'] = '__main__' |
|
1522 | prog_ns['__name__'] = '__main__' | |
1523 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1523 | main_mod = self.shell.new_main_mod(prog_ns) | |
1524 | else: |
|
1524 | else: | |
1525 | # Run in a fresh, empty namespace |
|
1525 | # Run in a fresh, empty namespace | |
1526 | if opts.has_key('n'): |
|
1526 | if opts.has_key('n'): | |
1527 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1527 | name = os.path.splitext(os.path.basename(filename))[0] | |
1528 | else: |
|
1528 | else: | |
1529 | name = '__main__' |
|
1529 | name = '__main__' | |
1530 |
|
1530 | |||
1531 | main_mod = self.shell.new_main_mod() |
|
1531 | main_mod = self.shell.new_main_mod() | |
1532 | prog_ns = main_mod.__dict__ |
|
1532 | prog_ns = main_mod.__dict__ | |
1533 | prog_ns['__name__'] = name |
|
1533 | prog_ns['__name__'] = name | |
1534 |
|
1534 | |||
1535 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1535 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1536 | # set the __file__ global in the script's namespace |
|
1536 | # set the __file__ global in the script's namespace | |
1537 | prog_ns['__file__'] = filename |
|
1537 | prog_ns['__file__'] = filename | |
1538 |
|
1538 | |||
1539 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1539 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1540 | # that, if we overwrite __main__, we replace it at the end |
|
1540 | # that, if we overwrite __main__, we replace it at the end | |
1541 | main_mod_name = prog_ns['__name__'] |
|
1541 | main_mod_name = prog_ns['__name__'] | |
1542 |
|
1542 | |||
1543 | if main_mod_name == '__main__': |
|
1543 | if main_mod_name == '__main__': | |
1544 | restore_main = sys.modules['__main__'] |
|
1544 | restore_main = sys.modules['__main__'] | |
1545 | else: |
|
1545 | else: | |
1546 | restore_main = False |
|
1546 | restore_main = False | |
1547 |
|
1547 | |||
1548 | # This needs to be undone at the end to prevent holding references to |
|
1548 | # This needs to be undone at the end to prevent holding references to | |
1549 | # every single object ever created. |
|
1549 | # every single object ever created. | |
1550 | sys.modules[main_mod_name] = main_mod |
|
1550 | sys.modules[main_mod_name] = main_mod | |
1551 |
|
1551 | |||
1552 | stats = None |
|
1552 | stats = None | |
1553 | try: |
|
1553 | try: | |
1554 | self.shell.save_hist() |
|
1554 | self.shell.save_history() | |
1555 |
|
1555 | |||
1556 | if opts.has_key('p'): |
|
1556 | if opts.has_key('p'): | |
1557 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1557 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1558 | else: |
|
1558 | else: | |
1559 | if opts.has_key('d'): |
|
1559 | if opts.has_key('d'): | |
1560 | deb = debugger.Pdb(self.shell.colors) |
|
1560 | deb = debugger.Pdb(self.shell.colors) | |
1561 | # reset Breakpoint state, which is moronically kept |
|
1561 | # reset Breakpoint state, which is moronically kept | |
1562 | # in a class |
|
1562 | # in a class | |
1563 | bdb.Breakpoint.next = 1 |
|
1563 | bdb.Breakpoint.next = 1 | |
1564 | bdb.Breakpoint.bplist = {} |
|
1564 | bdb.Breakpoint.bplist = {} | |
1565 | bdb.Breakpoint.bpbynumber = [None] |
|
1565 | bdb.Breakpoint.bpbynumber = [None] | |
1566 | # Set an initial breakpoint to stop execution |
|
1566 | # Set an initial breakpoint to stop execution | |
1567 | maxtries = 10 |
|
1567 | maxtries = 10 | |
1568 | bp = int(opts.get('b',[1])[0]) |
|
1568 | bp = int(opts.get('b',[1])[0]) | |
1569 | checkline = deb.checkline(filename,bp) |
|
1569 | checkline = deb.checkline(filename,bp) | |
1570 | if not checkline: |
|
1570 | if not checkline: | |
1571 | for bp in range(bp+1,bp+maxtries+1): |
|
1571 | for bp in range(bp+1,bp+maxtries+1): | |
1572 | if deb.checkline(filename,bp): |
|
1572 | if deb.checkline(filename,bp): | |
1573 | break |
|
1573 | break | |
1574 | else: |
|
1574 | else: | |
1575 | msg = ("\nI failed to find a valid line to set " |
|
1575 | msg = ("\nI failed to find a valid line to set " | |
1576 | "a breakpoint\n" |
|
1576 | "a breakpoint\n" | |
1577 | "after trying up to line: %s.\n" |
|
1577 | "after trying up to line: %s.\n" | |
1578 | "Please set a valid breakpoint manually " |
|
1578 | "Please set a valid breakpoint manually " | |
1579 | "with the -b option." % bp) |
|
1579 | "with the -b option." % bp) | |
1580 | error(msg) |
|
1580 | error(msg) | |
1581 | return |
|
1581 | return | |
1582 | # if we find a good linenumber, set the breakpoint |
|
1582 | # if we find a good linenumber, set the breakpoint | |
1583 | deb.do_break('%s:%s' % (filename,bp)) |
|
1583 | deb.do_break('%s:%s' % (filename,bp)) | |
1584 | # Start file run |
|
1584 | # Start file run | |
1585 | print "NOTE: Enter 'c' at the", |
|
1585 | print "NOTE: Enter 'c' at the", | |
1586 | print "%s prompt to start your script." % deb.prompt |
|
1586 | print "%s prompt to start your script." % deb.prompt | |
1587 | try: |
|
1587 | try: | |
1588 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1588 | deb.run('execfile("%s")' % filename,prog_ns) | |
1589 |
|
1589 | |||
1590 | except: |
|
1590 | except: | |
1591 | etype, value, tb = sys.exc_info() |
|
1591 | etype, value, tb = sys.exc_info() | |
1592 | # Skip three frames in the traceback: the %run one, |
|
1592 | # Skip three frames in the traceback: the %run one, | |
1593 | # one inside bdb.py, and the command-line typed by the |
|
1593 | # one inside bdb.py, and the command-line typed by the | |
1594 | # user (run by exec in pdb itself). |
|
1594 | # user (run by exec in pdb itself). | |
1595 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1595 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1596 | else: |
|
1596 | else: | |
1597 | if runner is None: |
|
1597 | if runner is None: | |
1598 | runner = self.shell.safe_execfile |
|
1598 | runner = self.shell.safe_execfile | |
1599 | if opts.has_key('t'): |
|
1599 | if opts.has_key('t'): | |
1600 | # timed execution |
|
1600 | # timed execution | |
1601 | try: |
|
1601 | try: | |
1602 | nruns = int(opts['N'][0]) |
|
1602 | nruns = int(opts['N'][0]) | |
1603 | if nruns < 1: |
|
1603 | if nruns < 1: | |
1604 | error('Number of runs must be >=1') |
|
1604 | error('Number of runs must be >=1') | |
1605 | return |
|
1605 | return | |
1606 | except (KeyError): |
|
1606 | except (KeyError): | |
1607 | nruns = 1 |
|
1607 | nruns = 1 | |
1608 | if nruns == 1: |
|
1608 | if nruns == 1: | |
1609 | t0 = clock2() |
|
1609 | t0 = clock2() | |
1610 | runner(filename,prog_ns,prog_ns, |
|
1610 | runner(filename,prog_ns,prog_ns, | |
1611 | exit_ignore=exit_ignore) |
|
1611 | exit_ignore=exit_ignore) | |
1612 | t1 = clock2() |
|
1612 | t1 = clock2() | |
1613 | t_usr = t1[0]-t0[0] |
|
1613 | t_usr = t1[0]-t0[0] | |
1614 | t_sys = t1[1]-t0[1] |
|
1614 | t_sys = t1[1]-t0[1] | |
1615 | print "\nIPython CPU timings (estimated):" |
|
1615 | print "\nIPython CPU timings (estimated):" | |
1616 | print " User : %10s s." % t_usr |
|
1616 | print " User : %10s s." % t_usr | |
1617 | print " System: %10s s." % t_sys |
|
1617 | print " System: %10s s." % t_sys | |
1618 | else: |
|
1618 | else: | |
1619 | runs = range(nruns) |
|
1619 | runs = range(nruns) | |
1620 | t0 = clock2() |
|
1620 | t0 = clock2() | |
1621 | for nr in runs: |
|
1621 | for nr in runs: | |
1622 | runner(filename,prog_ns,prog_ns, |
|
1622 | runner(filename,prog_ns,prog_ns, | |
1623 | exit_ignore=exit_ignore) |
|
1623 | exit_ignore=exit_ignore) | |
1624 | t1 = clock2() |
|
1624 | t1 = clock2() | |
1625 | t_usr = t1[0]-t0[0] |
|
1625 | t_usr = t1[0]-t0[0] | |
1626 | t_sys = t1[1]-t0[1] |
|
1626 | t_sys = t1[1]-t0[1] | |
1627 | print "\nIPython CPU timings (estimated):" |
|
1627 | print "\nIPython CPU timings (estimated):" | |
1628 | print "Total runs performed:",nruns |
|
1628 | print "Total runs performed:",nruns | |
1629 | print " Times : %10s %10s" % ('Total','Per run') |
|
1629 | print " Times : %10s %10s" % ('Total','Per run') | |
1630 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1630 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1631 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1631 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1632 |
|
1632 | |||
1633 | else: |
|
1633 | else: | |
1634 | # regular execution |
|
1634 | # regular execution | |
1635 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1635 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1636 |
|
1636 | |||
1637 | if opts.has_key('i'): |
|
1637 | if opts.has_key('i'): | |
1638 | self.shell.user_ns['__name__'] = __name__save |
|
1638 | self.shell.user_ns['__name__'] = __name__save | |
1639 | else: |
|
1639 | else: | |
1640 | # The shell MUST hold a reference to prog_ns so after %run |
|
1640 | # The shell MUST hold a reference to prog_ns so after %run | |
1641 | # exits, the python deletion mechanism doesn't zero it out |
|
1641 | # exits, the python deletion mechanism doesn't zero it out | |
1642 | # (leaving dangling references). |
|
1642 | # (leaving dangling references). | |
1643 | self.shell.cache_main_mod(prog_ns,filename) |
|
1643 | self.shell.cache_main_mod(prog_ns,filename) | |
1644 | # update IPython interactive namespace |
|
1644 | # update IPython interactive namespace | |
1645 |
|
1645 | |||
1646 | # Some forms of read errors on the file may mean the |
|
1646 | # Some forms of read errors on the file may mean the | |
1647 | # __name__ key was never set; using pop we don't have to |
|
1647 | # __name__ key was never set; using pop we don't have to | |
1648 | # worry about a possible KeyError. |
|
1648 | # worry about a possible KeyError. | |
1649 | prog_ns.pop('__name__', None) |
|
1649 | prog_ns.pop('__name__', None) | |
1650 |
|
1650 | |||
1651 | self.shell.user_ns.update(prog_ns) |
|
1651 | self.shell.user_ns.update(prog_ns) | |
1652 | finally: |
|
1652 | finally: | |
1653 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1653 | # It's a bit of a mystery why, but __builtins__ can change from | |
1654 | # being a module to becoming a dict missing some key data after |
|
1654 | # being a module to becoming a dict missing some key data after | |
1655 | # %run. As best I can see, this is NOT something IPython is doing |
|
1655 | # %run. As best I can see, this is NOT something IPython is doing | |
1656 | # at all, and similar problems have been reported before: |
|
1656 | # at all, and similar problems have been reported before: | |
1657 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1657 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1658 | # Since this seems to be done by the interpreter itself, the best |
|
1658 | # Since this seems to be done by the interpreter itself, the best | |
1659 | # we can do is to at least restore __builtins__ for the user on |
|
1659 | # we can do is to at least restore __builtins__ for the user on | |
1660 | # exit. |
|
1660 | # exit. | |
1661 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1661 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1662 |
|
1662 | |||
1663 | # Ensure key global structures are restored |
|
1663 | # Ensure key global structures are restored | |
1664 | sys.argv = save_argv |
|
1664 | sys.argv = save_argv | |
1665 | if restore_main: |
|
1665 | if restore_main: | |
1666 | sys.modules['__main__'] = restore_main |
|
1666 | sys.modules['__main__'] = restore_main | |
1667 | else: |
|
1667 | else: | |
1668 | # Remove from sys.modules the reference to main_mod we'd |
|
1668 | # Remove from sys.modules the reference to main_mod we'd | |
1669 | # added. Otherwise it will trap references to objects |
|
1669 | # added. Otherwise it will trap references to objects | |
1670 | # contained therein. |
|
1670 | # contained therein. | |
1671 | del sys.modules[main_mod_name] |
|
1671 | del sys.modules[main_mod_name] | |
1672 |
|
1672 | |||
1673 | self.shell.reload_hist() |
|
1673 | self.shell.reload_history() | |
1674 |
|
1674 | |||
1675 | return stats |
|
1675 | return stats | |
1676 |
|
1676 | |||
1677 | @testdec.skip_doctest |
|
1677 | @testdec.skip_doctest | |
1678 | def magic_timeit(self, parameter_s =''): |
|
1678 | def magic_timeit(self, parameter_s =''): | |
1679 | """Time execution of a Python statement or expression |
|
1679 | """Time execution of a Python statement or expression | |
1680 |
|
1680 | |||
1681 | Usage:\\ |
|
1681 | Usage:\\ | |
1682 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1682 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1683 |
|
1683 | |||
1684 | Time execution of a Python statement or expression using the timeit |
|
1684 | Time execution of a Python statement or expression using the timeit | |
1685 | module. |
|
1685 | module. | |
1686 |
|
1686 | |||
1687 | Options: |
|
1687 | Options: | |
1688 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1688 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1689 | is not given, a fitting value is chosen. |
|
1689 | is not given, a fitting value is chosen. | |
1690 |
|
1690 | |||
1691 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1691 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1692 | Default: 3 |
|
1692 | Default: 3 | |
1693 |
|
1693 | |||
1694 | -t: use time.time to measure the time, which is the default on Unix. |
|
1694 | -t: use time.time to measure the time, which is the default on Unix. | |
1695 | This function measures wall time. |
|
1695 | This function measures wall time. | |
1696 |
|
1696 | |||
1697 | -c: use time.clock to measure the time, which is the default on |
|
1697 | -c: use time.clock to measure the time, which is the default on | |
1698 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1698 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1699 | instead and returns the CPU user time. |
|
1699 | instead and returns the CPU user time. | |
1700 |
|
1700 | |||
1701 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1701 | -p<P>: use a precision of <P> digits to display the timing result. | |
1702 | Default: 3 |
|
1702 | Default: 3 | |
1703 |
|
1703 | |||
1704 |
|
1704 | |||
1705 | Examples: |
|
1705 | Examples: | |
1706 |
|
1706 | |||
1707 | In [1]: %timeit pass |
|
1707 | In [1]: %timeit pass | |
1708 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1708 | 10000000 loops, best of 3: 53.3 ns per loop | |
1709 |
|
1709 | |||
1710 | In [2]: u = None |
|
1710 | In [2]: u = None | |
1711 |
|
1711 | |||
1712 | In [3]: %timeit u is None |
|
1712 | In [3]: %timeit u is None | |
1713 | 10000000 loops, best of 3: 184 ns per loop |
|
1713 | 10000000 loops, best of 3: 184 ns per loop | |
1714 |
|
1714 | |||
1715 | In [4]: %timeit -r 4 u == None |
|
1715 | In [4]: %timeit -r 4 u == None | |
1716 | 1000000 loops, best of 4: 242 ns per loop |
|
1716 | 1000000 loops, best of 4: 242 ns per loop | |
1717 |
|
1717 | |||
1718 | In [5]: import time |
|
1718 | In [5]: import time | |
1719 |
|
1719 | |||
1720 | In [6]: %timeit -n1 time.sleep(2) |
|
1720 | In [6]: %timeit -n1 time.sleep(2) | |
1721 | 1 loops, best of 3: 2 s per loop |
|
1721 | 1 loops, best of 3: 2 s per loop | |
1722 |
|
1722 | |||
1723 |
|
1723 | |||
1724 | The times reported by %timeit will be slightly higher than those |
|
1724 | The times reported by %timeit will be slightly higher than those | |
1725 | reported by the timeit.py script when variables are accessed. This is |
|
1725 | reported by the timeit.py script when variables are accessed. This is | |
1726 | due to the fact that %timeit executes the statement in the namespace |
|
1726 | due to the fact that %timeit executes the statement in the namespace | |
1727 | of the shell, compared with timeit.py, which uses a single setup |
|
1727 | of the shell, compared with timeit.py, which uses a single setup | |
1728 | statement to import function or create variables. Generally, the bias |
|
1728 | statement to import function or create variables. Generally, the bias | |
1729 | does not matter as long as results from timeit.py are not mixed with |
|
1729 | does not matter as long as results from timeit.py are not mixed with | |
1730 | those from %timeit.""" |
|
1730 | those from %timeit.""" | |
1731 |
|
1731 | |||
1732 | import timeit |
|
1732 | import timeit | |
1733 | import math |
|
1733 | import math | |
1734 |
|
1734 | |||
1735 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1735 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1736 | # certain terminals. Until we figure out a robust way of |
|
1736 | # certain terminals. Until we figure out a robust way of | |
1737 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1737 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1738 | # microseconds. I am really NOT happy about disabling the proper |
|
1738 | # microseconds. I am really NOT happy about disabling the proper | |
1739 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1739 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1740 | # right solution for this is, I'm all ears... |
|
1740 | # right solution for this is, I'm all ears... | |
1741 | # |
|
1741 | # | |
1742 | # Note: using |
|
1742 | # Note: using | |
1743 | # |
|
1743 | # | |
1744 | # s = u'\xb5' |
|
1744 | # s = u'\xb5' | |
1745 | # s.encode(sys.getdefaultencoding()) |
|
1745 | # s.encode(sys.getdefaultencoding()) | |
1746 | # |
|
1746 | # | |
1747 | # is not sufficient, as I've seen terminals where that fails but |
|
1747 | # is not sufficient, as I've seen terminals where that fails but | |
1748 | # print s |
|
1748 | # print s | |
1749 | # |
|
1749 | # | |
1750 | # succeeds |
|
1750 | # succeeds | |
1751 | # |
|
1751 | # | |
1752 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1752 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1753 |
|
1753 | |||
1754 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1754 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1755 | units = [u"s", u"ms",u'us',"ns"] |
|
1755 | units = [u"s", u"ms",u'us',"ns"] | |
1756 |
|
1756 | |||
1757 | scaling = [1, 1e3, 1e6, 1e9] |
|
1757 | scaling = [1, 1e3, 1e6, 1e9] | |
1758 |
|
1758 | |||
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1759 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1760 | posix=False) |
|
1760 | posix=False) | |
1761 | if stmt == "": |
|
1761 | if stmt == "": | |
1762 | return |
|
1762 | return | |
1763 | timefunc = timeit.default_timer |
|
1763 | timefunc = timeit.default_timer | |
1764 | number = int(getattr(opts, "n", 0)) |
|
1764 | number = int(getattr(opts, "n", 0)) | |
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1765 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1766 | precision = int(getattr(opts, "p", 3)) |
|
1766 | precision = int(getattr(opts, "p", 3)) | |
1767 | if hasattr(opts, "t"): |
|
1767 | if hasattr(opts, "t"): | |
1768 | timefunc = time.time |
|
1768 | timefunc = time.time | |
1769 | if hasattr(opts, "c"): |
|
1769 | if hasattr(opts, "c"): | |
1770 | timefunc = clock |
|
1770 | timefunc = clock | |
1771 |
|
1771 | |||
1772 | timer = timeit.Timer(timer=timefunc) |
|
1772 | timer = timeit.Timer(timer=timefunc) | |
1773 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1773 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1774 | # but is there a better way to achieve that the code stmt has access |
|
1774 | # but is there a better way to achieve that the code stmt has access | |
1775 | # to the shell namespace? |
|
1775 | # to the shell namespace? | |
1776 |
|
1776 | |||
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1777 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1778 | 'setup': "pass"} |
|
1778 | 'setup': "pass"} | |
1779 | # Track compilation time so it can be reported if too long |
|
1779 | # Track compilation time so it can be reported if too long | |
1780 | # Minimum time above which compilation time will be reported |
|
1780 | # Minimum time above which compilation time will be reported | |
1781 | tc_min = 0.1 |
|
1781 | tc_min = 0.1 | |
1782 |
|
1782 | |||
1783 | t0 = clock() |
|
1783 | t0 = clock() | |
1784 | code = compile(src, "<magic-timeit>", "exec") |
|
1784 | code = compile(src, "<magic-timeit>", "exec") | |
1785 | tc = clock()-t0 |
|
1785 | tc = clock()-t0 | |
1786 |
|
1786 | |||
1787 | ns = {} |
|
1787 | ns = {} | |
1788 | exec code in self.shell.user_ns, ns |
|
1788 | exec code in self.shell.user_ns, ns | |
1789 | timer.inner = ns["inner"] |
|
1789 | timer.inner = ns["inner"] | |
1790 |
|
1790 | |||
1791 | if number == 0: |
|
1791 | if number == 0: | |
1792 | # determine number so that 0.2 <= total time < 2.0 |
|
1792 | # determine number so that 0.2 <= total time < 2.0 | |
1793 | number = 1 |
|
1793 | number = 1 | |
1794 | for i in range(1, 10): |
|
1794 | for i in range(1, 10): | |
1795 | if timer.timeit(number) >= 0.2: |
|
1795 | if timer.timeit(number) >= 0.2: | |
1796 | break |
|
1796 | break | |
1797 | number *= 10 |
|
1797 | number *= 10 | |
1798 |
|
1798 | |||
1799 | best = min(timer.repeat(repeat, number)) / number |
|
1799 | best = min(timer.repeat(repeat, number)) / number | |
1800 |
|
1800 | |||
1801 | if best > 0.0 and best < 1000.0: |
|
1801 | if best > 0.0 and best < 1000.0: | |
1802 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1802 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1803 | elif best >= 1000.0: |
|
1803 | elif best >= 1000.0: | |
1804 | order = 0 |
|
1804 | order = 0 | |
1805 | else: |
|
1805 | else: | |
1806 | order = 3 |
|
1806 | order = 3 | |
1807 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1807 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1808 | precision, |
|
1808 | precision, | |
1809 | best * scaling[order], |
|
1809 | best * scaling[order], | |
1810 | units[order]) |
|
1810 | units[order]) | |
1811 | if tc > tc_min: |
|
1811 | if tc > tc_min: | |
1812 | print "Compiler time: %.2f s" % tc |
|
1812 | print "Compiler time: %.2f s" % tc | |
1813 |
|
1813 | |||
1814 | @testdec.skip_doctest |
|
1814 | @testdec.skip_doctest | |
1815 | def magic_time(self,parameter_s = ''): |
|
1815 | def magic_time(self,parameter_s = ''): | |
1816 | """Time execution of a Python statement or expression. |
|
1816 | """Time execution of a Python statement or expression. | |
1817 |
|
1817 | |||
1818 | The CPU and wall clock times are printed, and the value of the |
|
1818 | The CPU and wall clock times are printed, and the value of the | |
1819 | expression (if any) is returned. Note that under Win32, system time |
|
1819 | expression (if any) is returned. Note that under Win32, system time | |
1820 | is always reported as 0, since it can not be measured. |
|
1820 | is always reported as 0, since it can not be measured. | |
1821 |
|
1821 | |||
1822 | This function provides very basic timing functionality. In Python |
|
1822 | This function provides very basic timing functionality. In Python | |
1823 | 2.3, the timeit module offers more control and sophistication, so this |
|
1823 | 2.3, the timeit module offers more control and sophistication, so this | |
1824 | could be rewritten to use it (patches welcome). |
|
1824 | could be rewritten to use it (patches welcome). | |
1825 |
|
1825 | |||
1826 | Some examples: |
|
1826 | Some examples: | |
1827 |
|
1827 | |||
1828 | In [1]: time 2**128 |
|
1828 | In [1]: time 2**128 | |
1829 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1829 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1830 | Wall time: 0.00 |
|
1830 | Wall time: 0.00 | |
1831 | Out[1]: 340282366920938463463374607431768211456L |
|
1831 | Out[1]: 340282366920938463463374607431768211456L | |
1832 |
|
1832 | |||
1833 | In [2]: n = 1000000 |
|
1833 | In [2]: n = 1000000 | |
1834 |
|
1834 | |||
1835 | In [3]: time sum(range(n)) |
|
1835 | In [3]: time sum(range(n)) | |
1836 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1836 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1837 | Wall time: 1.37 |
|
1837 | Wall time: 1.37 | |
1838 | Out[3]: 499999500000L |
|
1838 | Out[3]: 499999500000L | |
1839 |
|
1839 | |||
1840 | In [4]: time print 'hello world' |
|
1840 | In [4]: time print 'hello world' | |
1841 | hello world |
|
1841 | hello world | |
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1842 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1843 | Wall time: 0.00 |
|
1843 | Wall time: 0.00 | |
1844 |
|
1844 | |||
1845 | Note that the time needed by Python to compile the given expression |
|
1845 | Note that the time needed by Python to compile the given expression | |
1846 | will be reported if it is more than 0.1s. In this example, the |
|
1846 | will be reported if it is more than 0.1s. In this example, the | |
1847 | actual exponentiation is done by Python at compilation time, so while |
|
1847 | actual exponentiation is done by Python at compilation time, so while | |
1848 | the expression can take a noticeable amount of time to compute, that |
|
1848 | the expression can take a noticeable amount of time to compute, that | |
1849 | time is purely due to the compilation: |
|
1849 | time is purely due to the compilation: | |
1850 |
|
1850 | |||
1851 | In [5]: time 3**9999; |
|
1851 | In [5]: time 3**9999; | |
1852 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1852 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1853 | Wall time: 0.00 s |
|
1853 | Wall time: 0.00 s | |
1854 |
|
1854 | |||
1855 | In [6]: time 3**999999; |
|
1855 | In [6]: time 3**999999; | |
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1857 | Wall time: 0.00 s |
|
1857 | Wall time: 0.00 s | |
1858 | Compiler : 0.78 s |
|
1858 | Compiler : 0.78 s | |
1859 | """ |
|
1859 | """ | |
1860 |
|
1860 | |||
1861 | # fail immediately if the given expression can't be compiled |
|
1861 | # fail immediately if the given expression can't be compiled | |
1862 |
|
1862 | |||
1863 | expr = self.shell.prefilter(parameter_s,False) |
|
1863 | expr = self.shell.prefilter(parameter_s,False) | |
1864 |
|
1864 | |||
1865 | # Minimum time above which compilation time will be reported |
|
1865 | # Minimum time above which compilation time will be reported | |
1866 | tc_min = 0.1 |
|
1866 | tc_min = 0.1 | |
1867 |
|
1867 | |||
1868 | try: |
|
1868 | try: | |
1869 | mode = 'eval' |
|
1869 | mode = 'eval' | |
1870 | t0 = clock() |
|
1870 | t0 = clock() | |
1871 | code = compile(expr,'<timed eval>',mode) |
|
1871 | code = compile(expr,'<timed eval>',mode) | |
1872 | tc = clock()-t0 |
|
1872 | tc = clock()-t0 | |
1873 | except SyntaxError: |
|
1873 | except SyntaxError: | |
1874 | mode = 'exec' |
|
1874 | mode = 'exec' | |
1875 | t0 = clock() |
|
1875 | t0 = clock() | |
1876 | code = compile(expr,'<timed exec>',mode) |
|
1876 | code = compile(expr,'<timed exec>',mode) | |
1877 | tc = clock()-t0 |
|
1877 | tc = clock()-t0 | |
1878 | # skew measurement as little as possible |
|
1878 | # skew measurement as little as possible | |
1879 | glob = self.shell.user_ns |
|
1879 | glob = self.shell.user_ns | |
1880 | clk = clock2 |
|
1880 | clk = clock2 | |
1881 | wtime = time.time |
|
1881 | wtime = time.time | |
1882 | # time execution |
|
1882 | # time execution | |
1883 | wall_st = wtime() |
|
1883 | wall_st = wtime() | |
1884 | if mode=='eval': |
|
1884 | if mode=='eval': | |
1885 | st = clk() |
|
1885 | st = clk() | |
1886 | out = eval(code,glob) |
|
1886 | out = eval(code,glob) | |
1887 | end = clk() |
|
1887 | end = clk() | |
1888 | else: |
|
1888 | else: | |
1889 | st = clk() |
|
1889 | st = clk() | |
1890 | exec code in glob |
|
1890 | exec code in glob | |
1891 | end = clk() |
|
1891 | end = clk() | |
1892 | out = None |
|
1892 | out = None | |
1893 | wall_end = wtime() |
|
1893 | wall_end = wtime() | |
1894 | # Compute actual times and report |
|
1894 | # Compute actual times and report | |
1895 | wall_time = wall_end-wall_st |
|
1895 | wall_time = wall_end-wall_st | |
1896 | cpu_user = end[0]-st[0] |
|
1896 | cpu_user = end[0]-st[0] | |
1897 | cpu_sys = end[1]-st[1] |
|
1897 | cpu_sys = end[1]-st[1] | |
1898 | cpu_tot = cpu_user+cpu_sys |
|
1898 | cpu_tot = cpu_user+cpu_sys | |
1899 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1899 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1900 | (cpu_user,cpu_sys,cpu_tot) |
|
1900 | (cpu_user,cpu_sys,cpu_tot) | |
1901 | print "Wall time: %.2f s" % wall_time |
|
1901 | print "Wall time: %.2f s" % wall_time | |
1902 | if tc > tc_min: |
|
1902 | if tc > tc_min: | |
1903 | print "Compiler : %.2f s" % tc |
|
1903 | print "Compiler : %.2f s" % tc | |
1904 | return out |
|
1904 | return out | |
1905 |
|
1905 | |||
1906 | @testdec.skip_doctest |
|
1906 | @testdec.skip_doctest | |
1907 | def magic_macro(self,parameter_s = ''): |
|
1907 | def magic_macro(self,parameter_s = ''): | |
1908 | """Define a set of input lines as a macro for future re-execution. |
|
1908 | """Define a set of input lines as a macro for future re-execution. | |
1909 |
|
1909 | |||
1910 | Usage:\\ |
|
1910 | Usage:\\ | |
1911 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1911 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1912 |
|
1912 | |||
1913 | Options: |
|
1913 | Options: | |
1914 |
|
1914 | |||
1915 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1915 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1916 | so that magics are loaded in their transformed version to valid |
|
1916 | so that magics are loaded in their transformed version to valid | |
1917 | Python. If this option is given, the raw input as typed as the |
|
1917 | Python. If this option is given, the raw input as typed as the | |
1918 | command line is used instead. |
|
1918 | command line is used instead. | |
1919 |
|
1919 | |||
1920 | This will define a global variable called `name` which is a string |
|
1920 | This will define a global variable called `name` which is a string | |
1921 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1921 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1922 | above) from your input history into a single string. This variable |
|
1922 | above) from your input history into a single string. This variable | |
1923 | acts like an automatic function which re-executes those lines as if |
|
1923 | acts like an automatic function which re-executes those lines as if | |
1924 | you had typed them. You just type 'name' at the prompt and the code |
|
1924 | you had typed them. You just type 'name' at the prompt and the code | |
1925 | executes. |
|
1925 | executes. | |
1926 |
|
1926 | |||
1927 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1927 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1928 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1928 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1929 | using the lines numbered 5,6 and 7. |
|
1929 | using the lines numbered 5,6 and 7. | |
1930 |
|
1930 | |||
1931 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1931 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1932 | notation, where N:M means numbers N through M-1. |
|
1932 | notation, where N:M means numbers N through M-1. | |
1933 |
|
1933 | |||
1934 | For example, if your history contains (%hist prints it): |
|
1934 | For example, if your history contains (%hist prints it): | |
1935 |
|
1935 | |||
1936 | 44: x=1 |
|
1936 | 44: x=1 | |
1937 | 45: y=3 |
|
1937 | 45: y=3 | |
1938 | 46: z=x+y |
|
1938 | 46: z=x+y | |
1939 | 47: print x |
|
1939 | 47: print x | |
1940 | 48: a=5 |
|
1940 | 48: a=5 | |
1941 | 49: print 'x',x,'y',y |
|
1941 | 49: print 'x',x,'y',y | |
1942 |
|
1942 | |||
1943 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1943 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1944 | called my_macro with: |
|
1944 | called my_macro with: | |
1945 |
|
1945 | |||
1946 | In [55]: %macro my_macro 44-47 49 |
|
1946 | In [55]: %macro my_macro 44-47 49 | |
1947 |
|
1947 | |||
1948 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1948 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1949 | in one pass. |
|
1949 | in one pass. | |
1950 |
|
1950 | |||
1951 | You don't need to give the line-numbers in order, and any given line |
|
1951 | You don't need to give the line-numbers in order, and any given line | |
1952 | number can appear multiple times. You can assemble macros with any |
|
1952 | number can appear multiple times. You can assemble macros with any | |
1953 | lines from your input history in any order. |
|
1953 | lines from your input history in any order. | |
1954 |
|
1954 | |||
1955 | The macro is a simple object which holds its value in an attribute, |
|
1955 | The macro is a simple object which holds its value in an attribute, | |
1956 | but IPython's display system checks for macros and executes them as |
|
1956 | but IPython's display system checks for macros and executes them as | |
1957 | code instead of printing them when you type their name. |
|
1957 | code instead of printing them when you type their name. | |
1958 |
|
1958 | |||
1959 | You can view a macro's contents by explicitly printing it with: |
|
1959 | You can view a macro's contents by explicitly printing it with: | |
1960 |
|
1960 | |||
1961 | 'print macro_name'. |
|
1961 | 'print macro_name'. | |
1962 |
|
1962 | |||
1963 | For one-off cases which DON'T contain magic function calls in them you |
|
1963 | For one-off cases which DON'T contain magic function calls in them you | |
1964 | can obtain similar results by explicitly executing slices from your |
|
1964 | can obtain similar results by explicitly executing slices from your | |
1965 | input history with: |
|
1965 | input history with: | |
1966 |
|
1966 | |||
1967 | In [60]: exec In[44:48]+In[49]""" |
|
1967 | In [60]: exec In[44:48]+In[49]""" | |
1968 |
|
1968 | |||
1969 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1969 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1970 | if not args: |
|
1970 | if not args: | |
1971 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1971 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1972 | macs.sort() |
|
1972 | macs.sort() | |
1973 | return macs |
|
1973 | return macs | |
1974 | if len(args) == 1: |
|
1974 | if len(args) == 1: | |
1975 | raise UsageError( |
|
1975 | raise UsageError( | |
1976 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1976 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1977 | name,ranges = args[0], args[1:] |
|
1977 | name,ranges = args[0], args[1:] | |
1978 |
|
1978 | |||
1979 | #print 'rng',ranges # dbg |
|
1979 | #print 'rng',ranges # dbg | |
1980 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1980 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1981 | macro = Macro(lines) |
|
1981 | macro = Macro(lines) | |
1982 | self.shell.define_macro(name, macro) |
|
1982 | self.shell.define_macro(name, macro) | |
1983 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1983 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1984 | print 'Macro contents:' |
|
1984 | print 'Macro contents:' | |
1985 | print macro, |
|
1985 | print macro, | |
1986 |
|
1986 | |||
1987 | def magic_save(self,parameter_s = ''): |
|
1987 | def magic_save(self,parameter_s = ''): | |
1988 | """Save a set of lines to a given filename. |
|
1988 | """Save a set of lines to a given filename. | |
1989 |
|
1989 | |||
1990 | Usage:\\ |
|
1990 | Usage:\\ | |
1991 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1991 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1992 |
|
1992 | |||
1993 | Options: |
|
1993 | Options: | |
1994 |
|
1994 | |||
1995 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1995 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1996 | so that magics are loaded in their transformed version to valid |
|
1996 | so that magics are loaded in their transformed version to valid | |
1997 | Python. If this option is given, the raw input as typed as the |
|
1997 | Python. If this option is given, the raw input as typed as the | |
1998 | command line is used instead. |
|
1998 | command line is used instead. | |
1999 |
|
1999 | |||
2000 | This function uses the same syntax as %macro for line extraction, but |
|
2000 | This function uses the same syntax as %macro for line extraction, but | |
2001 | instead of creating a macro it saves the resulting string to the |
|
2001 | instead of creating a macro it saves the resulting string to the | |
2002 | filename you specify. |
|
2002 | filename you specify. | |
2003 |
|
2003 | |||
2004 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2004 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2005 | it asks for confirmation before overwriting existing files.""" |
|
2005 | it asks for confirmation before overwriting existing files.""" | |
2006 |
|
2006 | |||
2007 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2007 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2008 | fname,ranges = args[0], args[1:] |
|
2008 | fname,ranges = args[0], args[1:] | |
2009 | if not fname.endswith('.py'): |
|
2009 | if not fname.endswith('.py'): | |
2010 | fname += '.py' |
|
2010 | fname += '.py' | |
2011 | if os.path.isfile(fname): |
|
2011 | if os.path.isfile(fname): | |
2012 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2012 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2013 | if ans.lower() not in ['y','yes']: |
|
2013 | if ans.lower() not in ['y','yes']: | |
2014 | print 'Operation cancelled.' |
|
2014 | print 'Operation cancelled.' | |
2015 | return |
|
2015 | return | |
2016 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2016 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2017 | f = file(fname,'w') |
|
2017 | f = file(fname,'w') | |
2018 | f.write(cmds) |
|
2018 | f.write(cmds) | |
2019 | f.close() |
|
2019 | f.close() | |
2020 | print 'The following commands were written to file `%s`:' % fname |
|
2020 | print 'The following commands were written to file `%s`:' % fname | |
2021 | print cmds |
|
2021 | print cmds | |
2022 |
|
2022 | |||
2023 | def _edit_macro(self,mname,macro): |
|
2023 | def _edit_macro(self,mname,macro): | |
2024 | """open an editor with the macro data in a file""" |
|
2024 | """open an editor with the macro data in a file""" | |
2025 | filename = self.shell.mktempfile(macro.value) |
|
2025 | filename = self.shell.mktempfile(macro.value) | |
2026 | self.shell.hooks.editor(filename) |
|
2026 | self.shell.hooks.editor(filename) | |
2027 |
|
2027 | |||
2028 | # and make a new macro object, to replace the old one |
|
2028 | # and make a new macro object, to replace the old one | |
2029 | mfile = open(filename) |
|
2029 | mfile = open(filename) | |
2030 | mvalue = mfile.read() |
|
2030 | mvalue = mfile.read() | |
2031 | mfile.close() |
|
2031 | mfile.close() | |
2032 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2032 | self.shell.user_ns[mname] = Macro(mvalue) | |
2033 |
|
2033 | |||
2034 | def magic_ed(self,parameter_s=''): |
|
2034 | def magic_ed(self,parameter_s=''): | |
2035 | """Alias to %edit.""" |
|
2035 | """Alias to %edit.""" | |
2036 | return self.magic_edit(parameter_s) |
|
2036 | return self.magic_edit(parameter_s) | |
2037 |
|
2037 | |||
2038 | @testdec.skip_doctest |
|
2038 | @testdec.skip_doctest | |
2039 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2039 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2040 | """Bring up an editor and execute the resulting code. |
|
2040 | """Bring up an editor and execute the resulting code. | |
2041 |
|
2041 | |||
2042 | Usage: |
|
2042 | Usage: | |
2043 | %edit [options] [args] |
|
2043 | %edit [options] [args] | |
2044 |
|
2044 | |||
2045 | %edit runs IPython's editor hook. The default version of this hook is |
|
2045 | %edit runs IPython's editor hook. The default version of this hook is | |
2046 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2046 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2047 | environment variable $EDITOR. If this isn't found, it will default to |
|
2047 | environment variable $EDITOR. If this isn't found, it will default to | |
2048 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2048 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2049 | docstring for how to change the editor hook. |
|
2049 | docstring for how to change the editor hook. | |
2050 |
|
2050 | |||
2051 | You can also set the value of this editor via the command line option |
|
2051 | You can also set the value of this editor via the command line option | |
2052 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2052 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2053 | specifically for IPython an editor different from your typical default |
|
2053 | specifically for IPython an editor different from your typical default | |
2054 | (and for Windows users who typically don't set environment variables). |
|
2054 | (and for Windows users who typically don't set environment variables). | |
2055 |
|
2055 | |||
2056 | This command allows you to conveniently edit multi-line code right in |
|
2056 | This command allows you to conveniently edit multi-line code right in | |
2057 | your IPython session. |
|
2057 | your IPython session. | |
2058 |
|
2058 | |||
2059 | If called without arguments, %edit opens up an empty editor with a |
|
2059 | If called without arguments, %edit opens up an empty editor with a | |
2060 | temporary file and will execute the contents of this file when you |
|
2060 | temporary file and will execute the contents of this file when you | |
2061 | close it (don't forget to save it!). |
|
2061 | close it (don't forget to save it!). | |
2062 |
|
2062 | |||
2063 |
|
2063 | |||
2064 | Options: |
|
2064 | Options: | |
2065 |
|
2065 | |||
2066 | -n <number>: open the editor at a specified line number. By default, |
|
2066 | -n <number>: open the editor at a specified line number. By default, | |
2067 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2067 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2068 | you can configure this by providing your own modified hook if your |
|
2068 | you can configure this by providing your own modified hook if your | |
2069 | favorite editor supports line-number specifications with a different |
|
2069 | favorite editor supports line-number specifications with a different | |
2070 | syntax. |
|
2070 | syntax. | |
2071 |
|
2071 | |||
2072 | -p: this will call the editor with the same data as the previous time |
|
2072 | -p: this will call the editor with the same data as the previous time | |
2073 | it was used, regardless of how long ago (in your current session) it |
|
2073 | it was used, regardless of how long ago (in your current session) it | |
2074 | was. |
|
2074 | was. | |
2075 |
|
2075 | |||
2076 | -r: use 'raw' input. This option only applies to input taken from the |
|
2076 | -r: use 'raw' input. This option only applies to input taken from the | |
2077 | user's history. By default, the 'processed' history is used, so that |
|
2077 | user's history. By default, the 'processed' history is used, so that | |
2078 | magics are loaded in their transformed version to valid Python. If |
|
2078 | magics are loaded in their transformed version to valid Python. If | |
2079 | this option is given, the raw input as typed as the command line is |
|
2079 | this option is given, the raw input as typed as the command line is | |
2080 | used instead. When you exit the editor, it will be executed by |
|
2080 | used instead. When you exit the editor, it will be executed by | |
2081 | IPython's own processor. |
|
2081 | IPython's own processor. | |
2082 |
|
2082 | |||
2083 | -x: do not execute the edited code immediately upon exit. This is |
|
2083 | -x: do not execute the edited code immediately upon exit. This is | |
2084 | mainly useful if you are editing programs which need to be called with |
|
2084 | mainly useful if you are editing programs which need to be called with | |
2085 | command line arguments, which you can then do using %run. |
|
2085 | command line arguments, which you can then do using %run. | |
2086 |
|
2086 | |||
2087 |
|
2087 | |||
2088 | Arguments: |
|
2088 | Arguments: | |
2089 |
|
2089 | |||
2090 | If arguments are given, the following possibilites exist: |
|
2090 | If arguments are given, the following possibilites exist: | |
2091 |
|
2091 | |||
2092 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2092 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2093 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2093 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2094 | loaded into the editor. The syntax is the same of the %macro command. |
|
2094 | loaded into the editor. The syntax is the same of the %macro command. | |
2095 |
|
2095 | |||
2096 | - If the argument doesn't start with a number, it is evaluated as a |
|
2096 | - If the argument doesn't start with a number, it is evaluated as a | |
2097 | variable and its contents loaded into the editor. You can thus edit |
|
2097 | variable and its contents loaded into the editor. You can thus edit | |
2098 | any string which contains python code (including the result of |
|
2098 | any string which contains python code (including the result of | |
2099 | previous edits). |
|
2099 | previous edits). | |
2100 |
|
2100 | |||
2101 | - If the argument is the name of an object (other than a string), |
|
2101 | - If the argument is the name of an object (other than a string), | |
2102 | IPython will try to locate the file where it was defined and open the |
|
2102 | IPython will try to locate the file where it was defined and open the | |
2103 | editor at the point where it is defined. You can use `%edit function` |
|
2103 | editor at the point where it is defined. You can use `%edit function` | |
2104 | to load an editor exactly at the point where 'function' is defined, |
|
2104 | to load an editor exactly at the point where 'function' is defined, | |
2105 | edit it and have the file be executed automatically. |
|
2105 | edit it and have the file be executed automatically. | |
2106 |
|
2106 | |||
2107 | If the object is a macro (see %macro for details), this opens up your |
|
2107 | If the object is a macro (see %macro for details), this opens up your | |
2108 | specified editor with a temporary file containing the macro's data. |
|
2108 | specified editor with a temporary file containing the macro's data. | |
2109 | Upon exit, the macro is reloaded with the contents of the file. |
|
2109 | Upon exit, the macro is reloaded with the contents of the file. | |
2110 |
|
2110 | |||
2111 | Note: opening at an exact line is only supported under Unix, and some |
|
2111 | Note: opening at an exact line is only supported under Unix, and some | |
2112 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2112 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2113 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2113 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2114 | (X)Emacs, vi, jed, pico and joe all do. |
|
2114 | (X)Emacs, vi, jed, pico and joe all do. | |
2115 |
|
2115 | |||
2116 | - If the argument is not found as a variable, IPython will look for a |
|
2116 | - If the argument is not found as a variable, IPython will look for a | |
2117 | file with that name (adding .py if necessary) and load it into the |
|
2117 | file with that name (adding .py if necessary) and load it into the | |
2118 | editor. It will execute its contents with execfile() when you exit, |
|
2118 | editor. It will execute its contents with execfile() when you exit, | |
2119 | loading any code in the file into your interactive namespace. |
|
2119 | loading any code in the file into your interactive namespace. | |
2120 |
|
2120 | |||
2121 | After executing your code, %edit will return as output the code you |
|
2121 | After executing your code, %edit will return as output the code you | |
2122 | typed in the editor (except when it was an existing file). This way |
|
2122 | typed in the editor (except when it was an existing file). This way | |
2123 | you can reload the code in further invocations of %edit as a variable, |
|
2123 | you can reload the code in further invocations of %edit as a variable, | |
2124 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2124 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2125 | the output. |
|
2125 | the output. | |
2126 |
|
2126 | |||
2127 | Note that %edit is also available through the alias %ed. |
|
2127 | Note that %edit is also available through the alias %ed. | |
2128 |
|
2128 | |||
2129 | This is an example of creating a simple function inside the editor and |
|
2129 | This is an example of creating a simple function inside the editor and | |
2130 | then modifying it. First, start up the editor: |
|
2130 | then modifying it. First, start up the editor: | |
2131 |
|
2131 | |||
2132 | In [1]: ed |
|
2132 | In [1]: ed | |
2133 | Editing... done. Executing edited code... |
|
2133 | Editing... done. Executing edited code... | |
2134 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2134 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2135 |
|
2135 | |||
2136 | We can then call the function foo(): |
|
2136 | We can then call the function foo(): | |
2137 |
|
2137 | |||
2138 | In [2]: foo() |
|
2138 | In [2]: foo() | |
2139 | foo() was defined in an editing session |
|
2139 | foo() was defined in an editing session | |
2140 |
|
2140 | |||
2141 | Now we edit foo. IPython automatically loads the editor with the |
|
2141 | Now we edit foo. IPython automatically loads the editor with the | |
2142 | (temporary) file where foo() was previously defined: |
|
2142 | (temporary) file where foo() was previously defined: | |
2143 |
|
2143 | |||
2144 | In [3]: ed foo |
|
2144 | In [3]: ed foo | |
2145 | Editing... done. Executing edited code... |
|
2145 | Editing... done. Executing edited code... | |
2146 |
|
2146 | |||
2147 | And if we call foo() again we get the modified version: |
|
2147 | And if we call foo() again we get the modified version: | |
2148 |
|
2148 | |||
2149 | In [4]: foo() |
|
2149 | In [4]: foo() | |
2150 | foo() has now been changed! |
|
2150 | foo() has now been changed! | |
2151 |
|
2151 | |||
2152 | Here is an example of how to edit a code snippet successive |
|
2152 | Here is an example of how to edit a code snippet successive | |
2153 | times. First we call the editor: |
|
2153 | times. First we call the editor: | |
2154 |
|
2154 | |||
2155 | In [5]: ed |
|
2155 | In [5]: ed | |
2156 | Editing... done. Executing edited code... |
|
2156 | Editing... done. Executing edited code... | |
2157 | hello |
|
2157 | hello | |
2158 | Out[5]: "print 'hello'n" |
|
2158 | Out[5]: "print 'hello'n" | |
2159 |
|
2159 | |||
2160 | Now we call it again with the previous output (stored in _): |
|
2160 | Now we call it again with the previous output (stored in _): | |
2161 |
|
2161 | |||
2162 | In [6]: ed _ |
|
2162 | In [6]: ed _ | |
2163 | Editing... done. Executing edited code... |
|
2163 | Editing... done. Executing edited code... | |
2164 | hello world |
|
2164 | hello world | |
2165 | Out[6]: "print 'hello world'n" |
|
2165 | Out[6]: "print 'hello world'n" | |
2166 |
|
2166 | |||
2167 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2167 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2168 |
|
2168 | |||
2169 | In [7]: ed _8 |
|
2169 | In [7]: ed _8 | |
2170 | Editing... done. Executing edited code... |
|
2170 | Editing... done. Executing edited code... | |
2171 | hello again |
|
2171 | hello again | |
2172 | Out[7]: "print 'hello again'n" |
|
2172 | Out[7]: "print 'hello again'n" | |
2173 |
|
2173 | |||
2174 |
|
2174 | |||
2175 | Changing the default editor hook: |
|
2175 | Changing the default editor hook: | |
2176 |
|
2176 | |||
2177 | If you wish to write your own editor hook, you can put it in a |
|
2177 | If you wish to write your own editor hook, you can put it in a | |
2178 | configuration file which you load at startup time. The default hook |
|
2178 | configuration file which you load at startup time. The default hook | |
2179 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2179 | is defined in the IPython.core.hooks module, and you can use that as a | |
2180 | starting example for further modifications. That file also has |
|
2180 | starting example for further modifications. That file also has | |
2181 | general instructions on how to set a new hook for use once you've |
|
2181 | general instructions on how to set a new hook for use once you've | |
2182 | defined it.""" |
|
2182 | defined it.""" | |
2183 |
|
2183 | |||
2184 | # FIXME: This function has become a convoluted mess. It needs a |
|
2184 | # FIXME: This function has become a convoluted mess. It needs a | |
2185 | # ground-up rewrite with clean, simple logic. |
|
2185 | # ground-up rewrite with clean, simple logic. | |
2186 |
|
2186 | |||
2187 | def make_filename(arg): |
|
2187 | def make_filename(arg): | |
2188 | "Make a filename from the given args" |
|
2188 | "Make a filename from the given args" | |
2189 | try: |
|
2189 | try: | |
2190 | filename = get_py_filename(arg) |
|
2190 | filename = get_py_filename(arg) | |
2191 | except IOError: |
|
2191 | except IOError: | |
2192 | if args.endswith('.py'): |
|
2192 | if args.endswith('.py'): | |
2193 | filename = arg |
|
2193 | filename = arg | |
2194 | else: |
|
2194 | else: | |
2195 | filename = None |
|
2195 | filename = None | |
2196 | return filename |
|
2196 | return filename | |
2197 |
|
2197 | |||
2198 | # custom exceptions |
|
2198 | # custom exceptions | |
2199 | class DataIsObject(Exception): pass |
|
2199 | class DataIsObject(Exception): pass | |
2200 |
|
2200 | |||
2201 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2201 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2202 | # Set a few locals from the options for convenience: |
|
2202 | # Set a few locals from the options for convenience: | |
2203 | opts_p = opts.has_key('p') |
|
2203 | opts_p = opts.has_key('p') | |
2204 | opts_r = opts.has_key('r') |
|
2204 | opts_r = opts.has_key('r') | |
2205 |
|
2205 | |||
2206 | # Default line number value |
|
2206 | # Default line number value | |
2207 | lineno = opts.get('n',None) |
|
2207 | lineno = opts.get('n',None) | |
2208 |
|
2208 | |||
2209 | if opts_p: |
|
2209 | if opts_p: | |
2210 | args = '_%s' % last_call[0] |
|
2210 | args = '_%s' % last_call[0] | |
2211 | if not self.shell.user_ns.has_key(args): |
|
2211 | if not self.shell.user_ns.has_key(args): | |
2212 | args = last_call[1] |
|
2212 | args = last_call[1] | |
2213 |
|
2213 | |||
2214 | # use last_call to remember the state of the previous call, but don't |
|
2214 | # use last_call to remember the state of the previous call, but don't | |
2215 | # let it be clobbered by successive '-p' calls. |
|
2215 | # let it be clobbered by successive '-p' calls. | |
2216 | try: |
|
2216 | try: | |
2217 | last_call[0] = self.shell.displayhook.prompt_count |
|
2217 | last_call[0] = self.shell.displayhook.prompt_count | |
2218 | if not opts_p: |
|
2218 | if not opts_p: | |
2219 | last_call[1] = parameter_s |
|
2219 | last_call[1] = parameter_s | |
2220 | except: |
|
2220 | except: | |
2221 | pass |
|
2221 | pass | |
2222 |
|
2222 | |||
2223 | # by default this is done with temp files, except when the given |
|
2223 | # by default this is done with temp files, except when the given | |
2224 | # arg is a filename |
|
2224 | # arg is a filename | |
2225 | use_temp = 1 |
|
2225 | use_temp = 1 | |
2226 |
|
2226 | |||
2227 | if re.match(r'\d',args): |
|
2227 | if re.match(r'\d',args): | |
2228 | # Mode where user specifies ranges of lines, like in %macro. |
|
2228 | # Mode where user specifies ranges of lines, like in %macro. | |
2229 | # This means that you can't edit files whose names begin with |
|
2229 | # This means that you can't edit files whose names begin with | |
2230 | # numbers this way. Tough. |
|
2230 | # numbers this way. Tough. | |
2231 | ranges = args.split() |
|
2231 | ranges = args.split() | |
2232 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2232 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2233 | elif args.endswith('.py'): |
|
2233 | elif args.endswith('.py'): | |
2234 | filename = make_filename(args) |
|
2234 | filename = make_filename(args) | |
2235 | data = '' |
|
2235 | data = '' | |
2236 | use_temp = 0 |
|
2236 | use_temp = 0 | |
2237 | elif args: |
|
2237 | elif args: | |
2238 | try: |
|
2238 | try: | |
2239 | # Load the parameter given as a variable. If not a string, |
|
2239 | # Load the parameter given as a variable. If not a string, | |
2240 | # process it as an object instead (below) |
|
2240 | # process it as an object instead (below) | |
2241 |
|
2241 | |||
2242 | #print '*** args',args,'type',type(args) # dbg |
|
2242 | #print '*** args',args,'type',type(args) # dbg | |
2243 | data = eval(args,self.shell.user_ns) |
|
2243 | data = eval(args,self.shell.user_ns) | |
2244 | if not type(data) in StringTypes: |
|
2244 | if not type(data) in StringTypes: | |
2245 | raise DataIsObject |
|
2245 | raise DataIsObject | |
2246 |
|
2246 | |||
2247 | except (NameError,SyntaxError): |
|
2247 | except (NameError,SyntaxError): | |
2248 | # given argument is not a variable, try as a filename |
|
2248 | # given argument is not a variable, try as a filename | |
2249 | filename = make_filename(args) |
|
2249 | filename = make_filename(args) | |
2250 | if filename is None: |
|
2250 | if filename is None: | |
2251 | warn("Argument given (%s) can't be found as a variable " |
|
2251 | warn("Argument given (%s) can't be found as a variable " | |
2252 | "or as a filename." % args) |
|
2252 | "or as a filename." % args) | |
2253 | return |
|
2253 | return | |
2254 |
|
2254 | |||
2255 | data = '' |
|
2255 | data = '' | |
2256 | use_temp = 0 |
|
2256 | use_temp = 0 | |
2257 | except DataIsObject: |
|
2257 | except DataIsObject: | |
2258 |
|
2258 | |||
2259 | # macros have a special edit function |
|
2259 | # macros have a special edit function | |
2260 | if isinstance(data,Macro): |
|
2260 | if isinstance(data,Macro): | |
2261 | self._edit_macro(args,data) |
|
2261 | self._edit_macro(args,data) | |
2262 | return |
|
2262 | return | |
2263 |
|
2263 | |||
2264 | # For objects, try to edit the file where they are defined |
|
2264 | # For objects, try to edit the file where they are defined | |
2265 | try: |
|
2265 | try: | |
2266 | filename = inspect.getabsfile(data) |
|
2266 | filename = inspect.getabsfile(data) | |
2267 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2267 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2268 | # class created by %edit? Try to find source |
|
2268 | # class created by %edit? Try to find source | |
2269 | # by looking for method definitions instead, the |
|
2269 | # by looking for method definitions instead, the | |
2270 | # __module__ in those classes is FakeModule. |
|
2270 | # __module__ in those classes is FakeModule. | |
2271 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2271 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2272 | for attr in attrs: |
|
2272 | for attr in attrs: | |
2273 | if not inspect.ismethod(attr): |
|
2273 | if not inspect.ismethod(attr): | |
2274 | continue |
|
2274 | continue | |
2275 | filename = inspect.getabsfile(attr) |
|
2275 | filename = inspect.getabsfile(attr) | |
2276 | if filename and 'fakemodule' not in filename.lower(): |
|
2276 | if filename and 'fakemodule' not in filename.lower(): | |
2277 | # change the attribute to be the edit target instead |
|
2277 | # change the attribute to be the edit target instead | |
2278 | data = attr |
|
2278 | data = attr | |
2279 | break |
|
2279 | break | |
2280 |
|
2280 | |||
2281 | datafile = 1 |
|
2281 | datafile = 1 | |
2282 | except TypeError: |
|
2282 | except TypeError: | |
2283 | filename = make_filename(args) |
|
2283 | filename = make_filename(args) | |
2284 | datafile = 1 |
|
2284 | datafile = 1 | |
2285 | warn('Could not find file where `%s` is defined.\n' |
|
2285 | warn('Could not find file where `%s` is defined.\n' | |
2286 | 'Opening a file named `%s`' % (args,filename)) |
|
2286 | 'Opening a file named `%s`' % (args,filename)) | |
2287 | # Now, make sure we can actually read the source (if it was in |
|
2287 | # Now, make sure we can actually read the source (if it was in | |
2288 | # a temp file it's gone by now). |
|
2288 | # a temp file it's gone by now). | |
2289 | if datafile: |
|
2289 | if datafile: | |
2290 | try: |
|
2290 | try: | |
2291 | if lineno is None: |
|
2291 | if lineno is None: | |
2292 | lineno = inspect.getsourcelines(data)[1] |
|
2292 | lineno = inspect.getsourcelines(data)[1] | |
2293 | except IOError: |
|
2293 | except IOError: | |
2294 | filename = make_filename(args) |
|
2294 | filename = make_filename(args) | |
2295 | if filename is None: |
|
2295 | if filename is None: | |
2296 | warn('The file `%s` where `%s` was defined cannot ' |
|
2296 | warn('The file `%s` where `%s` was defined cannot ' | |
2297 | 'be read.' % (filename,data)) |
|
2297 | 'be read.' % (filename,data)) | |
2298 | return |
|
2298 | return | |
2299 | use_temp = 0 |
|
2299 | use_temp = 0 | |
2300 | else: |
|
2300 | else: | |
2301 | data = '' |
|
2301 | data = '' | |
2302 |
|
2302 | |||
2303 | if use_temp: |
|
2303 | if use_temp: | |
2304 | filename = self.shell.mktempfile(data) |
|
2304 | filename = self.shell.mktempfile(data) | |
2305 | print 'IPython will make a temporary file named:',filename |
|
2305 | print 'IPython will make a temporary file named:',filename | |
2306 |
|
2306 | |||
2307 | # do actual editing here |
|
2307 | # do actual editing here | |
2308 | print 'Editing...', |
|
2308 | print 'Editing...', | |
2309 | sys.stdout.flush() |
|
2309 | sys.stdout.flush() | |
2310 | try: |
|
2310 | try: | |
2311 | # Quote filenames that may have spaces in them |
|
2311 | # Quote filenames that may have spaces in them | |
2312 | if ' ' in filename: |
|
2312 | if ' ' in filename: | |
2313 | filename = "%s" % filename |
|
2313 | filename = "%s" % filename | |
2314 | self.shell.hooks.editor(filename,lineno) |
|
2314 | self.shell.hooks.editor(filename,lineno) | |
2315 | except TryNext: |
|
2315 | except TryNext: | |
2316 | warn('Could not open editor') |
|
2316 | warn('Could not open editor') | |
2317 | return |
|
2317 | return | |
2318 |
|
2318 | |||
2319 | # XXX TODO: should this be generalized for all string vars? |
|
2319 | # XXX TODO: should this be generalized for all string vars? | |
2320 | # For now, this is special-cased to blocks created by cpaste |
|
2320 | # For now, this is special-cased to blocks created by cpaste | |
2321 | if args.strip() == 'pasted_block': |
|
2321 | if args.strip() == 'pasted_block': | |
2322 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2322 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2323 |
|
2323 | |||
2324 | if opts.has_key('x'): # -x prevents actual execution |
|
2324 | if opts.has_key('x'): # -x prevents actual execution | |
2325 |
|
2325 | |||
2326 | else: |
|
2326 | else: | |
2327 | print 'done. Executing edited code...' |
|
2327 | print 'done. Executing edited code...' | |
2328 | if opts_r: |
|
2328 | if opts_r: | |
2329 | self.shell.run_cell(file_read(filename)) |
|
2329 | self.shell.run_cell(file_read(filename)) | |
2330 | else: |
|
2330 | else: | |
2331 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2331 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2332 | self.shell.user_ns) |
|
2332 | self.shell.user_ns) | |
2333 |
|
2333 | |||
2334 |
|
2334 | |||
2335 | if use_temp: |
|
2335 | if use_temp: | |
2336 | try: |
|
2336 | try: | |
2337 | return open(filename).read() |
|
2337 | return open(filename).read() | |
2338 | except IOError,msg: |
|
2338 | except IOError,msg: | |
2339 | if msg.filename == filename: |
|
2339 | if msg.filename == filename: | |
2340 | warn('File not found. Did you forget to save?') |
|
2340 | warn('File not found. Did you forget to save?') | |
2341 | return |
|
2341 | return | |
2342 | else: |
|
2342 | else: | |
2343 | self.shell.showtraceback() |
|
2343 | self.shell.showtraceback() | |
2344 |
|
2344 | |||
2345 | def magic_xmode(self,parameter_s = ''): |
|
2345 | def magic_xmode(self,parameter_s = ''): | |
2346 | """Switch modes for the exception handlers. |
|
2346 | """Switch modes for the exception handlers. | |
2347 |
|
2347 | |||
2348 | Valid modes: Plain, Context and Verbose. |
|
2348 | Valid modes: Plain, Context and Verbose. | |
2349 |
|
2349 | |||
2350 | If called without arguments, acts as a toggle.""" |
|
2350 | If called without arguments, acts as a toggle.""" | |
2351 |
|
2351 | |||
2352 | def xmode_switch_err(name): |
|
2352 | def xmode_switch_err(name): | |
2353 | warn('Error changing %s exception modes.\n%s' % |
|
2353 | warn('Error changing %s exception modes.\n%s' % | |
2354 | (name,sys.exc_info()[1])) |
|
2354 | (name,sys.exc_info()[1])) | |
2355 |
|
2355 | |||
2356 | shell = self.shell |
|
2356 | shell = self.shell | |
2357 | new_mode = parameter_s.strip().capitalize() |
|
2357 | new_mode = parameter_s.strip().capitalize() | |
2358 | try: |
|
2358 | try: | |
2359 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2359 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2360 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2360 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2361 | except: |
|
2361 | except: | |
2362 | xmode_switch_err('user') |
|
2362 | xmode_switch_err('user') | |
2363 |
|
2363 | |||
2364 | def magic_colors(self,parameter_s = ''): |
|
2364 | def magic_colors(self,parameter_s = ''): | |
2365 | """Switch color scheme for prompts, info system and exception handlers. |
|
2365 | """Switch color scheme for prompts, info system and exception handlers. | |
2366 |
|
2366 | |||
2367 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2367 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2368 |
|
2368 | |||
2369 | Color scheme names are not case-sensitive.""" |
|
2369 | Color scheme names are not case-sensitive.""" | |
2370 |
|
2370 | |||
2371 | def color_switch_err(name): |
|
2371 | def color_switch_err(name): | |
2372 | warn('Error changing %s color schemes.\n%s' % |
|
2372 | warn('Error changing %s color schemes.\n%s' % | |
2373 | (name,sys.exc_info()[1])) |
|
2373 | (name,sys.exc_info()[1])) | |
2374 |
|
2374 | |||
2375 |
|
2375 | |||
2376 | new_scheme = parameter_s.strip() |
|
2376 | new_scheme = parameter_s.strip() | |
2377 | if not new_scheme: |
|
2377 | if not new_scheme: | |
2378 | raise UsageError( |
|
2378 | raise UsageError( | |
2379 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2379 | "%colors: you must specify a color scheme. See '%colors?'") | |
2380 | return |
|
2380 | return | |
2381 | # local shortcut |
|
2381 | # local shortcut | |
2382 | shell = self.shell |
|
2382 | shell = self.shell | |
2383 |
|
2383 | |||
2384 | import IPython.utils.rlineimpl as readline |
|
2384 | import IPython.utils.rlineimpl as readline | |
2385 |
|
2385 | |||
2386 | if not readline.have_readline and sys.platform == "win32": |
|
2386 | if not readline.have_readline and sys.platform == "win32": | |
2387 | msg = """\ |
|
2387 | msg = """\ | |
2388 | Proper color support under MS Windows requires the pyreadline library. |
|
2388 | Proper color support under MS Windows requires the pyreadline library. | |
2389 | You can find it at: |
|
2389 | You can find it at: | |
2390 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2390 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2391 | Gary's readline needs the ctypes module, from: |
|
2391 | Gary's readline needs the ctypes module, from: | |
2392 | http://starship.python.net/crew/theller/ctypes |
|
2392 | http://starship.python.net/crew/theller/ctypes | |
2393 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2393 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2394 |
|
2394 | |||
2395 | Defaulting color scheme to 'NoColor'""" |
|
2395 | Defaulting color scheme to 'NoColor'""" | |
2396 | new_scheme = 'NoColor' |
|
2396 | new_scheme = 'NoColor' | |
2397 | warn(msg) |
|
2397 | warn(msg) | |
2398 |
|
2398 | |||
2399 | # readline option is 0 |
|
2399 | # readline option is 0 | |
2400 | if not shell.has_readline: |
|
2400 | if not shell.has_readline: | |
2401 | new_scheme = 'NoColor' |
|
2401 | new_scheme = 'NoColor' | |
2402 |
|
2402 | |||
2403 | # Set prompt colors |
|
2403 | # Set prompt colors | |
2404 | try: |
|
2404 | try: | |
2405 | shell.displayhook.set_colors(new_scheme) |
|
2405 | shell.displayhook.set_colors(new_scheme) | |
2406 | except: |
|
2406 | except: | |
2407 | color_switch_err('prompt') |
|
2407 | color_switch_err('prompt') | |
2408 | else: |
|
2408 | else: | |
2409 | shell.colors = \ |
|
2409 | shell.colors = \ | |
2410 | shell.displayhook.color_table.active_scheme_name |
|
2410 | shell.displayhook.color_table.active_scheme_name | |
2411 | # Set exception colors |
|
2411 | # Set exception colors | |
2412 | try: |
|
2412 | try: | |
2413 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2413 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2414 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2414 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2415 | except: |
|
2415 | except: | |
2416 | color_switch_err('exception') |
|
2416 | color_switch_err('exception') | |
2417 |
|
2417 | |||
2418 | # Set info (for 'object?') colors |
|
2418 | # Set info (for 'object?') colors | |
2419 | if shell.color_info: |
|
2419 | if shell.color_info: | |
2420 | try: |
|
2420 | try: | |
2421 | shell.inspector.set_active_scheme(new_scheme) |
|
2421 | shell.inspector.set_active_scheme(new_scheme) | |
2422 | except: |
|
2422 | except: | |
2423 | color_switch_err('object inspector') |
|
2423 | color_switch_err('object inspector') | |
2424 | else: |
|
2424 | else: | |
2425 | shell.inspector.set_active_scheme('NoColor') |
|
2425 | shell.inspector.set_active_scheme('NoColor') | |
2426 |
|
2426 | |||
2427 | def magic_Pprint(self, parameter_s=''): |
|
2427 | def magic_Pprint(self, parameter_s=''): | |
2428 | """Toggle pretty printing on/off.""" |
|
2428 | """Toggle pretty printing on/off.""" | |
2429 |
|
2429 | |||
2430 | self.shell.pprint = 1 - self.shell.pprint |
|
2430 | self.shell.pprint = 1 - self.shell.pprint | |
2431 | print 'Pretty printing has been turned', \ |
|
2431 | print 'Pretty printing has been turned', \ | |
2432 | ['OFF','ON'][self.shell.pprint] |
|
2432 | ['OFF','ON'][self.shell.pprint] | |
2433 |
|
2433 | |||
2434 | def magic_Exit(self, parameter_s=''): |
|
2434 | def magic_Exit(self, parameter_s=''): | |
2435 | """Exit IPython.""" |
|
2435 | """Exit IPython.""" | |
2436 |
|
2436 | |||
2437 | self.shell.ask_exit() |
|
2437 | self.shell.ask_exit() | |
2438 |
|
2438 | |||
2439 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2439 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2440 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2440 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2441 |
|
2441 | |||
2442 | #...................................................................... |
|
2442 | #...................................................................... | |
2443 | # Functions to implement unix shell-type things |
|
2443 | # Functions to implement unix shell-type things | |
2444 |
|
2444 | |||
2445 | @testdec.skip_doctest |
|
2445 | @testdec.skip_doctest | |
2446 | def magic_alias(self, parameter_s = ''): |
|
2446 | def magic_alias(self, parameter_s = ''): | |
2447 | """Define an alias for a system command. |
|
2447 | """Define an alias for a system command. | |
2448 |
|
2448 | |||
2449 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2449 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2450 |
|
2450 | |||
2451 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2451 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2452 | params' (from your underlying operating system). |
|
2452 | params' (from your underlying operating system). | |
2453 |
|
2453 | |||
2454 | Aliases have lower precedence than magic functions and Python normal |
|
2454 | Aliases have lower precedence than magic functions and Python normal | |
2455 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2455 | variables, so if 'foo' is both a Python variable and an alias, the | |
2456 | alias can not be executed until 'del foo' removes the Python variable. |
|
2456 | alias can not be executed until 'del foo' removes the Python variable. | |
2457 |
|
2457 | |||
2458 | You can use the %l specifier in an alias definition to represent the |
|
2458 | You can use the %l specifier in an alias definition to represent the | |
2459 | whole line when the alias is called. For example: |
|
2459 | whole line when the alias is called. For example: | |
2460 |
|
2460 | |||
2461 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2461 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2462 | In [3]: bracket hello world |
|
2462 | In [3]: bracket hello world | |
2463 | Input in brackets: <hello world> |
|
2463 | Input in brackets: <hello world> | |
2464 |
|
2464 | |||
2465 | You can also define aliases with parameters using %s specifiers (one |
|
2465 | You can also define aliases with parameters using %s specifiers (one | |
2466 | per parameter): |
|
2466 | per parameter): | |
2467 |
|
2467 | |||
2468 | In [1]: alias parts echo first %s second %s |
|
2468 | In [1]: alias parts echo first %s second %s | |
2469 | In [2]: %parts A B |
|
2469 | In [2]: %parts A B | |
2470 | first A second B |
|
2470 | first A second B | |
2471 | In [3]: %parts A |
|
2471 | In [3]: %parts A | |
2472 | Incorrect number of arguments: 2 expected. |
|
2472 | Incorrect number of arguments: 2 expected. | |
2473 | parts is an alias to: 'echo first %s second %s' |
|
2473 | parts is an alias to: 'echo first %s second %s' | |
2474 |
|
2474 | |||
2475 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2475 | Note that %l and %s are mutually exclusive. You can only use one or | |
2476 | the other in your aliases. |
|
2476 | the other in your aliases. | |
2477 |
|
2477 | |||
2478 | Aliases expand Python variables just like system calls using ! or !! |
|
2478 | Aliases expand Python variables just like system calls using ! or !! | |
2479 | do: all expressions prefixed with '$' get expanded. For details of |
|
2479 | do: all expressions prefixed with '$' get expanded. For details of | |
2480 | the semantic rules, see PEP-215: |
|
2480 | the semantic rules, see PEP-215: | |
2481 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2481 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2482 | IPython for variable expansion. If you want to access a true shell |
|
2482 | IPython for variable expansion. If you want to access a true shell | |
2483 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2483 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2484 |
|
2484 | |||
2485 | In [6]: alias show echo |
|
2485 | In [6]: alias show echo | |
2486 | In [7]: PATH='A Python string' |
|
2486 | In [7]: PATH='A Python string' | |
2487 | In [8]: show $PATH |
|
2487 | In [8]: show $PATH | |
2488 | A Python string |
|
2488 | A Python string | |
2489 | In [9]: show $$PATH |
|
2489 | In [9]: show $$PATH | |
2490 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2490 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2491 |
|
2491 | |||
2492 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2492 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2493 | and %rehashx functions, which automatically create aliases for the |
|
2493 | and %rehashx functions, which automatically create aliases for the | |
2494 | contents of your $PATH. |
|
2494 | contents of your $PATH. | |
2495 |
|
2495 | |||
2496 | If called with no parameters, %alias prints the current alias table.""" |
|
2496 | If called with no parameters, %alias prints the current alias table.""" | |
2497 |
|
2497 | |||
2498 | par = parameter_s.strip() |
|
2498 | par = parameter_s.strip() | |
2499 | if not par: |
|
2499 | if not par: | |
2500 | stored = self.db.get('stored_aliases', {} ) |
|
2500 | stored = self.db.get('stored_aliases', {} ) | |
2501 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2501 | aliases = sorted(self.shell.alias_manager.aliases) | |
2502 | # for k, v in stored: |
|
2502 | # for k, v in stored: | |
2503 | # atab.append(k, v[0]) |
|
2503 | # atab.append(k, v[0]) | |
2504 |
|
2504 | |||
2505 | print "Total number of aliases:", len(aliases) |
|
2505 | print "Total number of aliases:", len(aliases) | |
2506 | sys.stdout.flush() |
|
2506 | sys.stdout.flush() | |
2507 | return aliases |
|
2507 | return aliases | |
2508 |
|
2508 | |||
2509 | # Now try to define a new one |
|
2509 | # Now try to define a new one | |
2510 | try: |
|
2510 | try: | |
2511 | alias,cmd = par.split(None, 1) |
|
2511 | alias,cmd = par.split(None, 1) | |
2512 | except: |
|
2512 | except: | |
2513 | print oinspect.getdoc(self.magic_alias) |
|
2513 | print oinspect.getdoc(self.magic_alias) | |
2514 | else: |
|
2514 | else: | |
2515 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2515 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2516 | # end magic_alias |
|
2516 | # end magic_alias | |
2517 |
|
2517 | |||
2518 | def magic_unalias(self, parameter_s = ''): |
|
2518 | def magic_unalias(self, parameter_s = ''): | |
2519 | """Remove an alias""" |
|
2519 | """Remove an alias""" | |
2520 |
|
2520 | |||
2521 | aname = parameter_s.strip() |
|
2521 | aname = parameter_s.strip() | |
2522 | self.shell.alias_manager.undefine_alias(aname) |
|
2522 | self.shell.alias_manager.undefine_alias(aname) | |
2523 | stored = self.db.get('stored_aliases', {} ) |
|
2523 | stored = self.db.get('stored_aliases', {} ) | |
2524 | if aname in stored: |
|
2524 | if aname in stored: | |
2525 | print "Removing %stored alias",aname |
|
2525 | print "Removing %stored alias",aname | |
2526 | del stored[aname] |
|
2526 | del stored[aname] | |
2527 | self.db['stored_aliases'] = stored |
|
2527 | self.db['stored_aliases'] = stored | |
2528 |
|
2528 | |||
2529 | def magic_rehashx(self, parameter_s = ''): |
|
2529 | def magic_rehashx(self, parameter_s = ''): | |
2530 | """Update the alias table with all executable files in $PATH. |
|
2530 | """Update the alias table with all executable files in $PATH. | |
2531 |
|
2531 | |||
2532 | This version explicitly checks that every entry in $PATH is a file |
|
2532 | This version explicitly checks that every entry in $PATH is a file | |
2533 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2533 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2534 |
|
2534 | |||
2535 | Under Windows, it checks executability as a match agains a |
|
2535 | Under Windows, it checks executability as a match agains a | |
2536 | '|'-separated string of extensions, stored in the IPython config |
|
2536 | '|'-separated string of extensions, stored in the IPython config | |
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2537 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2538 |
|
2538 | |||
2539 | This function also resets the root module cache of module completer, |
|
2539 | This function also resets the root module cache of module completer, | |
2540 | used on slow filesystems. |
|
2540 | used on slow filesystems. | |
2541 | """ |
|
2541 | """ | |
2542 | from IPython.core.alias import InvalidAliasError |
|
2542 | from IPython.core.alias import InvalidAliasError | |
2543 |
|
2543 | |||
2544 | # for the benefit of module completer in ipy_completers.py |
|
2544 | # for the benefit of module completer in ipy_completers.py | |
2545 | del self.db['rootmodules'] |
|
2545 | del self.db['rootmodules'] | |
2546 |
|
2546 | |||
2547 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2547 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2548 | os.environ.get('PATH','').split(os.pathsep)] |
|
2548 | os.environ.get('PATH','').split(os.pathsep)] | |
2549 | path = filter(os.path.isdir,path) |
|
2549 | path = filter(os.path.isdir,path) | |
2550 |
|
2550 | |||
2551 | syscmdlist = [] |
|
2551 | syscmdlist = [] | |
2552 | # Now define isexec in a cross platform manner. |
|
2552 | # Now define isexec in a cross platform manner. | |
2553 | if os.name == 'posix': |
|
2553 | if os.name == 'posix': | |
2554 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2554 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2555 | os.access(fname,os.X_OK) |
|
2555 | os.access(fname,os.X_OK) | |
2556 | else: |
|
2556 | else: | |
2557 | try: |
|
2557 | try: | |
2558 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2558 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2559 | except KeyError: |
|
2559 | except KeyError: | |
2560 | winext = 'exe|com|bat|py' |
|
2560 | winext = 'exe|com|bat|py' | |
2561 | if 'py' not in winext: |
|
2561 | if 'py' not in winext: | |
2562 | winext += '|py' |
|
2562 | winext += '|py' | |
2563 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2563 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2564 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2564 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2565 | savedir = os.getcwd() |
|
2565 | savedir = os.getcwd() | |
2566 |
|
2566 | |||
2567 | # Now walk the paths looking for executables to alias. |
|
2567 | # Now walk the paths looking for executables to alias. | |
2568 | try: |
|
2568 | try: | |
2569 | # write the whole loop for posix/Windows so we don't have an if in |
|
2569 | # write the whole loop for posix/Windows so we don't have an if in | |
2570 | # the innermost part |
|
2570 | # the innermost part | |
2571 | if os.name == 'posix': |
|
2571 | if os.name == 'posix': | |
2572 | for pdir in path: |
|
2572 | for pdir in path: | |
2573 | os.chdir(pdir) |
|
2573 | os.chdir(pdir) | |
2574 | for ff in os.listdir(pdir): |
|
2574 | for ff in os.listdir(pdir): | |
2575 | if isexec(ff): |
|
2575 | if isexec(ff): | |
2576 | try: |
|
2576 | try: | |
2577 | # Removes dots from the name since ipython |
|
2577 | # Removes dots from the name since ipython | |
2578 | # will assume names with dots to be python. |
|
2578 | # will assume names with dots to be python. | |
2579 | self.shell.alias_manager.define_alias( |
|
2579 | self.shell.alias_manager.define_alias( | |
2580 | ff.replace('.',''), ff) |
|
2580 | ff.replace('.',''), ff) | |
2581 | except InvalidAliasError: |
|
2581 | except InvalidAliasError: | |
2582 | pass |
|
2582 | pass | |
2583 | else: |
|
2583 | else: | |
2584 | syscmdlist.append(ff) |
|
2584 | syscmdlist.append(ff) | |
2585 | else: |
|
2585 | else: | |
2586 | no_alias = self.shell.alias_manager.no_alias |
|
2586 | no_alias = self.shell.alias_manager.no_alias | |
2587 | for pdir in path: |
|
2587 | for pdir in path: | |
2588 | os.chdir(pdir) |
|
2588 | os.chdir(pdir) | |
2589 | for ff in os.listdir(pdir): |
|
2589 | for ff in os.listdir(pdir): | |
2590 | base, ext = os.path.splitext(ff) |
|
2590 | base, ext = os.path.splitext(ff) | |
2591 | if isexec(ff) and base.lower() not in no_alias: |
|
2591 | if isexec(ff) and base.lower() not in no_alias: | |
2592 | if ext.lower() == '.exe': |
|
2592 | if ext.lower() == '.exe': | |
2593 | ff = base |
|
2593 | ff = base | |
2594 | try: |
|
2594 | try: | |
2595 | # Removes dots from the name since ipython |
|
2595 | # Removes dots from the name since ipython | |
2596 | # will assume names with dots to be python. |
|
2596 | # will assume names with dots to be python. | |
2597 | self.shell.alias_manager.define_alias( |
|
2597 | self.shell.alias_manager.define_alias( | |
2598 | base.lower().replace('.',''), ff) |
|
2598 | base.lower().replace('.',''), ff) | |
2599 | except InvalidAliasError: |
|
2599 | except InvalidAliasError: | |
2600 | pass |
|
2600 | pass | |
2601 | syscmdlist.append(ff) |
|
2601 | syscmdlist.append(ff) | |
2602 | db = self.db |
|
2602 | db = self.db | |
2603 | db['syscmdlist'] = syscmdlist |
|
2603 | db['syscmdlist'] = syscmdlist | |
2604 | finally: |
|
2604 | finally: | |
2605 | os.chdir(savedir) |
|
2605 | os.chdir(savedir) | |
2606 |
|
2606 | |||
2607 | def magic_pwd(self, parameter_s = ''): |
|
2607 | def magic_pwd(self, parameter_s = ''): | |
2608 | """Return the current working directory path.""" |
|
2608 | """Return the current working directory path.""" | |
2609 | return os.getcwd() |
|
2609 | return os.getcwd() | |
2610 |
|
2610 | |||
2611 | def magic_cd(self, parameter_s=''): |
|
2611 | def magic_cd(self, parameter_s=''): | |
2612 | """Change the current working directory. |
|
2612 | """Change the current working directory. | |
2613 |
|
2613 | |||
2614 | This command automatically maintains an internal list of directories |
|
2614 | This command automatically maintains an internal list of directories | |
2615 | you visit during your IPython session, in the variable _dh. The |
|
2615 | you visit during your IPython session, in the variable _dh. The | |
2616 | command %dhist shows this history nicely formatted. You can also |
|
2616 | command %dhist shows this history nicely formatted. You can also | |
2617 | do 'cd -<tab>' to see directory history conveniently. |
|
2617 | do 'cd -<tab>' to see directory history conveniently. | |
2618 |
|
2618 | |||
2619 | Usage: |
|
2619 | Usage: | |
2620 |
|
2620 | |||
2621 | cd 'dir': changes to directory 'dir'. |
|
2621 | cd 'dir': changes to directory 'dir'. | |
2622 |
|
2622 | |||
2623 | cd -: changes to the last visited directory. |
|
2623 | cd -: changes to the last visited directory. | |
2624 |
|
2624 | |||
2625 | cd -<n>: changes to the n-th directory in the directory history. |
|
2625 | cd -<n>: changes to the n-th directory in the directory history. | |
2626 |
|
2626 | |||
2627 | cd --foo: change to directory that matches 'foo' in history |
|
2627 | cd --foo: change to directory that matches 'foo' in history | |
2628 |
|
2628 | |||
2629 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2629 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2630 | (note: cd <bookmark_name> is enough if there is no |
|
2630 | (note: cd <bookmark_name> is enough if there is no | |
2631 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2631 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2632 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2632 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2633 |
|
2633 | |||
2634 | Options: |
|
2634 | Options: | |
2635 |
|
2635 | |||
2636 | -q: quiet. Do not print the working directory after the cd command is |
|
2636 | -q: quiet. Do not print the working directory after the cd command is | |
2637 | executed. By default IPython's cd command does print this directory, |
|
2637 | executed. By default IPython's cd command does print this directory, | |
2638 | since the default prompts do not display path information. |
|
2638 | since the default prompts do not display path information. | |
2639 |
|
2639 | |||
2640 | Note that !cd doesn't work for this purpose because the shell where |
|
2640 | Note that !cd doesn't work for this purpose because the shell where | |
2641 | !command runs is immediately discarded after executing 'command'.""" |
|
2641 | !command runs is immediately discarded after executing 'command'.""" | |
2642 |
|
2642 | |||
2643 | parameter_s = parameter_s.strip() |
|
2643 | parameter_s = parameter_s.strip() | |
2644 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2644 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2645 |
|
2645 | |||
2646 | oldcwd = os.getcwd() |
|
2646 | oldcwd = os.getcwd() | |
2647 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2647 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2648 | # jump in directory history by number |
|
2648 | # jump in directory history by number | |
2649 | if numcd: |
|
2649 | if numcd: | |
2650 | nn = int(numcd.group(2)) |
|
2650 | nn = int(numcd.group(2)) | |
2651 | try: |
|
2651 | try: | |
2652 | ps = self.shell.user_ns['_dh'][nn] |
|
2652 | ps = self.shell.user_ns['_dh'][nn] | |
2653 | except IndexError: |
|
2653 | except IndexError: | |
2654 | print 'The requested directory does not exist in history.' |
|
2654 | print 'The requested directory does not exist in history.' | |
2655 | return |
|
2655 | return | |
2656 | else: |
|
2656 | else: | |
2657 | opts = {} |
|
2657 | opts = {} | |
2658 | elif parameter_s.startswith('--'): |
|
2658 | elif parameter_s.startswith('--'): | |
2659 | ps = None |
|
2659 | ps = None | |
2660 | fallback = None |
|
2660 | fallback = None | |
2661 | pat = parameter_s[2:] |
|
2661 | pat = parameter_s[2:] | |
2662 | dh = self.shell.user_ns['_dh'] |
|
2662 | dh = self.shell.user_ns['_dh'] | |
2663 | # first search only by basename (last component) |
|
2663 | # first search only by basename (last component) | |
2664 | for ent in reversed(dh): |
|
2664 | for ent in reversed(dh): | |
2665 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2665 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2666 | ps = ent |
|
2666 | ps = ent | |
2667 | break |
|
2667 | break | |
2668 |
|
2668 | |||
2669 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2669 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2670 | fallback = ent |
|
2670 | fallback = ent | |
2671 |
|
2671 | |||
2672 | # if we have no last part match, pick the first full path match |
|
2672 | # if we have no last part match, pick the first full path match | |
2673 | if ps is None: |
|
2673 | if ps is None: | |
2674 | ps = fallback |
|
2674 | ps = fallback | |
2675 |
|
2675 | |||
2676 | if ps is None: |
|
2676 | if ps is None: | |
2677 | print "No matching entry in directory history" |
|
2677 | print "No matching entry in directory history" | |
2678 | return |
|
2678 | return | |
2679 | else: |
|
2679 | else: | |
2680 | opts = {} |
|
2680 | opts = {} | |
2681 |
|
2681 | |||
2682 |
|
2682 | |||
2683 | else: |
|
2683 | else: | |
2684 | #turn all non-space-escaping backslashes to slashes, |
|
2684 | #turn all non-space-escaping backslashes to slashes, | |
2685 | # for c:\windows\directory\names\ |
|
2685 | # for c:\windows\directory\names\ | |
2686 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2686 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2687 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2687 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2688 | # jump to previous |
|
2688 | # jump to previous | |
2689 | if ps == '-': |
|
2689 | if ps == '-': | |
2690 | try: |
|
2690 | try: | |
2691 | ps = self.shell.user_ns['_dh'][-2] |
|
2691 | ps = self.shell.user_ns['_dh'][-2] | |
2692 | except IndexError: |
|
2692 | except IndexError: | |
2693 | raise UsageError('%cd -: No previous directory to change to.') |
|
2693 | raise UsageError('%cd -: No previous directory to change to.') | |
2694 | # jump to bookmark if needed |
|
2694 | # jump to bookmark if needed | |
2695 | else: |
|
2695 | else: | |
2696 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2696 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2697 | bkms = self.db.get('bookmarks', {}) |
|
2697 | bkms = self.db.get('bookmarks', {}) | |
2698 |
|
2698 | |||
2699 | if bkms.has_key(ps): |
|
2699 | if bkms.has_key(ps): | |
2700 | target = bkms[ps] |
|
2700 | target = bkms[ps] | |
2701 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2701 | print '(bookmark:%s) -> %s' % (ps,target) | |
2702 | ps = target |
|
2702 | ps = target | |
2703 | else: |
|
2703 | else: | |
2704 | if opts.has_key('b'): |
|
2704 | if opts.has_key('b'): | |
2705 | raise UsageError("Bookmark '%s' not found. " |
|
2705 | raise UsageError("Bookmark '%s' not found. " | |
2706 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2706 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2707 |
|
2707 | |||
2708 | # at this point ps should point to the target dir |
|
2708 | # at this point ps should point to the target dir | |
2709 | if ps: |
|
2709 | if ps: | |
2710 | try: |
|
2710 | try: | |
2711 | os.chdir(os.path.expanduser(ps)) |
|
2711 | os.chdir(os.path.expanduser(ps)) | |
2712 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2712 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2713 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2713 | set_term_title('IPython: ' + abbrev_cwd()) | |
2714 | except OSError: |
|
2714 | except OSError: | |
2715 | print sys.exc_info()[1] |
|
2715 | print sys.exc_info()[1] | |
2716 | else: |
|
2716 | else: | |
2717 | cwd = os.getcwd() |
|
2717 | cwd = os.getcwd() | |
2718 | dhist = self.shell.user_ns['_dh'] |
|
2718 | dhist = self.shell.user_ns['_dh'] | |
2719 | if oldcwd != cwd: |
|
2719 | if oldcwd != cwd: | |
2720 | dhist.append(cwd) |
|
2720 | dhist.append(cwd) | |
2721 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2721 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2722 |
|
2722 | |||
2723 | else: |
|
2723 | else: | |
2724 | os.chdir(self.shell.home_dir) |
|
2724 | os.chdir(self.shell.home_dir) | |
2725 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2725 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2726 | set_term_title('IPython: ' + '~') |
|
2726 | set_term_title('IPython: ' + '~') | |
2727 | cwd = os.getcwd() |
|
2727 | cwd = os.getcwd() | |
2728 | dhist = self.shell.user_ns['_dh'] |
|
2728 | dhist = self.shell.user_ns['_dh'] | |
2729 |
|
2729 | |||
2730 | if oldcwd != cwd: |
|
2730 | if oldcwd != cwd: | |
2731 | dhist.append(cwd) |
|
2731 | dhist.append(cwd) | |
2732 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2732 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2733 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2733 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2734 | print self.shell.user_ns['_dh'][-1] |
|
2734 | print self.shell.user_ns['_dh'][-1] | |
2735 |
|
2735 | |||
2736 |
|
2736 | |||
2737 | def magic_env(self, parameter_s=''): |
|
2737 | def magic_env(self, parameter_s=''): | |
2738 | """List environment variables.""" |
|
2738 | """List environment variables.""" | |
2739 |
|
2739 | |||
2740 | return os.environ.data |
|
2740 | return os.environ.data | |
2741 |
|
2741 | |||
2742 | def magic_pushd(self, parameter_s=''): |
|
2742 | def magic_pushd(self, parameter_s=''): | |
2743 | """Place the current dir on stack and change directory. |
|
2743 | """Place the current dir on stack and change directory. | |
2744 |
|
2744 | |||
2745 | Usage:\\ |
|
2745 | Usage:\\ | |
2746 | %pushd ['dirname'] |
|
2746 | %pushd ['dirname'] | |
2747 | """ |
|
2747 | """ | |
2748 |
|
2748 | |||
2749 | dir_s = self.shell.dir_stack |
|
2749 | dir_s = self.shell.dir_stack | |
2750 | tgt = os.path.expanduser(parameter_s) |
|
2750 | tgt = os.path.expanduser(parameter_s) | |
2751 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2751 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2752 | if tgt: |
|
2752 | if tgt: | |
2753 | self.magic_cd(parameter_s) |
|
2753 | self.magic_cd(parameter_s) | |
2754 | dir_s.insert(0,cwd) |
|
2754 | dir_s.insert(0,cwd) | |
2755 | return self.magic_dirs() |
|
2755 | return self.magic_dirs() | |
2756 |
|
2756 | |||
2757 | def magic_popd(self, parameter_s=''): |
|
2757 | def magic_popd(self, parameter_s=''): | |
2758 | """Change to directory popped off the top of the stack. |
|
2758 | """Change to directory popped off the top of the stack. | |
2759 | """ |
|
2759 | """ | |
2760 | if not self.shell.dir_stack: |
|
2760 | if not self.shell.dir_stack: | |
2761 | raise UsageError("%popd on empty stack") |
|
2761 | raise UsageError("%popd on empty stack") | |
2762 | top = self.shell.dir_stack.pop(0) |
|
2762 | top = self.shell.dir_stack.pop(0) | |
2763 | self.magic_cd(top) |
|
2763 | self.magic_cd(top) | |
2764 | print "popd ->",top |
|
2764 | print "popd ->",top | |
2765 |
|
2765 | |||
2766 | def magic_dirs(self, parameter_s=''): |
|
2766 | def magic_dirs(self, parameter_s=''): | |
2767 | """Return the current directory stack.""" |
|
2767 | """Return the current directory stack.""" | |
2768 |
|
2768 | |||
2769 | return self.shell.dir_stack |
|
2769 | return self.shell.dir_stack | |
2770 |
|
2770 | |||
2771 | def magic_dhist(self, parameter_s=''): |
|
2771 | def magic_dhist(self, parameter_s=''): | |
2772 | """Print your history of visited directories. |
|
2772 | """Print your history of visited directories. | |
2773 |
|
2773 | |||
2774 | %dhist -> print full history\\ |
|
2774 | %dhist -> print full history\\ | |
2775 | %dhist n -> print last n entries only\\ |
|
2775 | %dhist n -> print last n entries only\\ | |
2776 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2776 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2777 |
|
2777 | |||
2778 | This history is automatically maintained by the %cd command, and |
|
2778 | This history is automatically maintained by the %cd command, and | |
2779 | always available as the global list variable _dh. You can use %cd -<n> |
|
2779 | always available as the global list variable _dh. You can use %cd -<n> | |
2780 | to go to directory number <n>. |
|
2780 | to go to directory number <n>. | |
2781 |
|
2781 | |||
2782 | Note that most of time, you should view directory history by entering |
|
2782 | Note that most of time, you should view directory history by entering | |
2783 | cd -<TAB>. |
|
2783 | cd -<TAB>. | |
2784 |
|
2784 | |||
2785 | """ |
|
2785 | """ | |
2786 |
|
2786 | |||
2787 | dh = self.shell.user_ns['_dh'] |
|
2787 | dh = self.shell.user_ns['_dh'] | |
2788 | if parameter_s: |
|
2788 | if parameter_s: | |
2789 | try: |
|
2789 | try: | |
2790 | args = map(int,parameter_s.split()) |
|
2790 | args = map(int,parameter_s.split()) | |
2791 | except: |
|
2791 | except: | |
2792 | self.arg_err(Magic.magic_dhist) |
|
2792 | self.arg_err(Magic.magic_dhist) | |
2793 | return |
|
2793 | return | |
2794 | if len(args) == 1: |
|
2794 | if len(args) == 1: | |
2795 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2795 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2796 | elif len(args) == 2: |
|
2796 | elif len(args) == 2: | |
2797 | ini,fin = args |
|
2797 | ini,fin = args | |
2798 | else: |
|
2798 | else: | |
2799 | self.arg_err(Magic.magic_dhist) |
|
2799 | self.arg_err(Magic.magic_dhist) | |
2800 | return |
|
2800 | return | |
2801 | else: |
|
2801 | else: | |
2802 | ini,fin = 0,len(dh) |
|
2802 | ini,fin = 0,len(dh) | |
2803 | nlprint(dh, |
|
2803 | nlprint(dh, | |
2804 | header = 'Directory history (kept in _dh)', |
|
2804 | header = 'Directory history (kept in _dh)', | |
2805 | start=ini,stop=fin) |
|
2805 | start=ini,stop=fin) | |
2806 |
|
2806 | |||
2807 | @testdec.skip_doctest |
|
2807 | @testdec.skip_doctest | |
2808 | def magic_sc(self, parameter_s=''): |
|
2808 | def magic_sc(self, parameter_s=''): | |
2809 | """Shell capture - execute a shell command and capture its output. |
|
2809 | """Shell capture - execute a shell command and capture its output. | |
2810 |
|
2810 | |||
2811 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2811 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2812 |
|
2812 | |||
2813 | You should use the form 'var = !command' instead. Example: |
|
2813 | You should use the form 'var = !command' instead. Example: | |
2814 |
|
2814 | |||
2815 | "%sc -l myfiles = ls ~" should now be written as |
|
2815 | "%sc -l myfiles = ls ~" should now be written as | |
2816 |
|
2816 | |||
2817 | "myfiles = !ls ~" |
|
2817 | "myfiles = !ls ~" | |
2818 |
|
2818 | |||
2819 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2819 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2820 | below. |
|
2820 | below. | |
2821 |
|
2821 | |||
2822 | -- |
|
2822 | -- | |
2823 | %sc [options] varname=command |
|
2823 | %sc [options] varname=command | |
2824 |
|
2824 | |||
2825 | IPython will run the given command using commands.getoutput(), and |
|
2825 | IPython will run the given command using commands.getoutput(), and | |
2826 | will then update the user's interactive namespace with a variable |
|
2826 | will then update the user's interactive namespace with a variable | |
2827 | called varname, containing the value of the call. Your command can |
|
2827 | called varname, containing the value of the call. Your command can | |
2828 | contain shell wildcards, pipes, etc. |
|
2828 | contain shell wildcards, pipes, etc. | |
2829 |
|
2829 | |||
2830 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2830 | The '=' sign in the syntax is mandatory, and the variable name you | |
2831 | supply must follow Python's standard conventions for valid names. |
|
2831 | supply must follow Python's standard conventions for valid names. | |
2832 |
|
2832 | |||
2833 | (A special format without variable name exists for internal use) |
|
2833 | (A special format without variable name exists for internal use) | |
2834 |
|
2834 | |||
2835 | Options: |
|
2835 | Options: | |
2836 |
|
2836 | |||
2837 | -l: list output. Split the output on newlines into a list before |
|
2837 | -l: list output. Split the output on newlines into a list before | |
2838 | assigning it to the given variable. By default the output is stored |
|
2838 | assigning it to the given variable. By default the output is stored | |
2839 | as a single string. |
|
2839 | as a single string. | |
2840 |
|
2840 | |||
2841 | -v: verbose. Print the contents of the variable. |
|
2841 | -v: verbose. Print the contents of the variable. | |
2842 |
|
2842 | |||
2843 | In most cases you should not need to split as a list, because the |
|
2843 | In most cases you should not need to split as a list, because the | |
2844 | returned value is a special type of string which can automatically |
|
2844 | returned value is a special type of string which can automatically | |
2845 | provide its contents either as a list (split on newlines) or as a |
|
2845 | provide its contents either as a list (split on newlines) or as a | |
2846 | space-separated string. These are convenient, respectively, either |
|
2846 | space-separated string. These are convenient, respectively, either | |
2847 | for sequential processing or to be passed to a shell command. |
|
2847 | for sequential processing or to be passed to a shell command. | |
2848 |
|
2848 | |||
2849 | For example: |
|
2849 | For example: | |
2850 |
|
2850 | |||
2851 | # all-random |
|
2851 | # all-random | |
2852 |
|
2852 | |||
2853 | # Capture into variable a |
|
2853 | # Capture into variable a | |
2854 | In [1]: sc a=ls *py |
|
2854 | In [1]: sc a=ls *py | |
2855 |
|
2855 | |||
2856 | # a is a string with embedded newlines |
|
2856 | # a is a string with embedded newlines | |
2857 | In [2]: a |
|
2857 | In [2]: a | |
2858 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2858 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2859 |
|
2859 | |||
2860 | # which can be seen as a list: |
|
2860 | # which can be seen as a list: | |
2861 | In [3]: a.l |
|
2861 | In [3]: a.l | |
2862 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2862 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2863 |
|
2863 | |||
2864 | # or as a whitespace-separated string: |
|
2864 | # or as a whitespace-separated string: | |
2865 | In [4]: a.s |
|
2865 | In [4]: a.s | |
2866 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2866 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2867 |
|
2867 | |||
2868 | # a.s is useful to pass as a single command line: |
|
2868 | # a.s is useful to pass as a single command line: | |
2869 | In [5]: !wc -l $a.s |
|
2869 | In [5]: !wc -l $a.s | |
2870 | 146 setup.py |
|
2870 | 146 setup.py | |
2871 | 130 win32_manual_post_install.py |
|
2871 | 130 win32_manual_post_install.py | |
2872 | 276 total |
|
2872 | 276 total | |
2873 |
|
2873 | |||
2874 | # while the list form is useful to loop over: |
|
2874 | # while the list form is useful to loop over: | |
2875 | In [6]: for f in a.l: |
|
2875 | In [6]: for f in a.l: | |
2876 | ...: !wc -l $f |
|
2876 | ...: !wc -l $f | |
2877 | ...: |
|
2877 | ...: | |
2878 | 146 setup.py |
|
2878 | 146 setup.py | |
2879 | 130 win32_manual_post_install.py |
|
2879 | 130 win32_manual_post_install.py | |
2880 |
|
2880 | |||
2881 | Similiarly, the lists returned by the -l option are also special, in |
|
2881 | Similiarly, the lists returned by the -l option are also special, in | |
2882 | the sense that you can equally invoke the .s attribute on them to |
|
2882 | the sense that you can equally invoke the .s attribute on them to | |
2883 | automatically get a whitespace-separated string from their contents: |
|
2883 | automatically get a whitespace-separated string from their contents: | |
2884 |
|
2884 | |||
2885 | In [7]: sc -l b=ls *py |
|
2885 | In [7]: sc -l b=ls *py | |
2886 |
|
2886 | |||
2887 | In [8]: b |
|
2887 | In [8]: b | |
2888 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2888 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2889 |
|
2889 | |||
2890 | In [9]: b.s |
|
2890 | In [9]: b.s | |
2891 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2891 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2892 |
|
2892 | |||
2893 | In summary, both the lists and strings used for ouptut capture have |
|
2893 | In summary, both the lists and strings used for ouptut capture have | |
2894 | the following special attributes: |
|
2894 | the following special attributes: | |
2895 |
|
2895 | |||
2896 | .l (or .list) : value as list. |
|
2896 | .l (or .list) : value as list. | |
2897 | .n (or .nlstr): value as newline-separated string. |
|
2897 | .n (or .nlstr): value as newline-separated string. | |
2898 | .s (or .spstr): value as space-separated string. |
|
2898 | .s (or .spstr): value as space-separated string. | |
2899 | """ |
|
2899 | """ | |
2900 |
|
2900 | |||
2901 | opts,args = self.parse_options(parameter_s,'lv') |
|
2901 | opts,args = self.parse_options(parameter_s,'lv') | |
2902 | # Try to get a variable name and command to run |
|
2902 | # Try to get a variable name and command to run | |
2903 | try: |
|
2903 | try: | |
2904 | # the variable name must be obtained from the parse_options |
|
2904 | # the variable name must be obtained from the parse_options | |
2905 | # output, which uses shlex.split to strip options out. |
|
2905 | # output, which uses shlex.split to strip options out. | |
2906 | var,_ = args.split('=',1) |
|
2906 | var,_ = args.split('=',1) | |
2907 | var = var.strip() |
|
2907 | var = var.strip() | |
2908 | # But the the command has to be extracted from the original input |
|
2908 | # But the the command has to be extracted from the original input | |
2909 | # parameter_s, not on what parse_options returns, to avoid the |
|
2909 | # parameter_s, not on what parse_options returns, to avoid the | |
2910 | # quote stripping which shlex.split performs on it. |
|
2910 | # quote stripping which shlex.split performs on it. | |
2911 | _,cmd = parameter_s.split('=',1) |
|
2911 | _,cmd = parameter_s.split('=',1) | |
2912 | except ValueError: |
|
2912 | except ValueError: | |
2913 | var,cmd = '','' |
|
2913 | var,cmd = '','' | |
2914 | # If all looks ok, proceed |
|
2914 | # If all looks ok, proceed | |
2915 | split = 'l' in opts |
|
2915 | split = 'l' in opts | |
2916 | out = self.shell.getoutput(cmd, split=split) |
|
2916 | out = self.shell.getoutput(cmd, split=split) | |
2917 | if opts.has_key('v'): |
|
2917 | if opts.has_key('v'): | |
2918 | print '%s ==\n%s' % (var,pformat(out)) |
|
2918 | print '%s ==\n%s' % (var,pformat(out)) | |
2919 | if var: |
|
2919 | if var: | |
2920 | self.shell.user_ns.update({var:out}) |
|
2920 | self.shell.user_ns.update({var:out}) | |
2921 | else: |
|
2921 | else: | |
2922 | return out |
|
2922 | return out | |
2923 |
|
2923 | |||
2924 | def magic_sx(self, parameter_s=''): |
|
2924 | def magic_sx(self, parameter_s=''): | |
2925 | """Shell execute - run a shell command and capture its output. |
|
2925 | """Shell execute - run a shell command and capture its output. | |
2926 |
|
2926 | |||
2927 | %sx command |
|
2927 | %sx command | |
2928 |
|
2928 | |||
2929 | IPython will run the given command using commands.getoutput(), and |
|
2929 | IPython will run the given command using commands.getoutput(), and | |
2930 | return the result formatted as a list (split on '\\n'). Since the |
|
2930 | return the result formatted as a list (split on '\\n'). Since the | |
2931 | output is _returned_, it will be stored in ipython's regular output |
|
2931 | output is _returned_, it will be stored in ipython's regular output | |
2932 | cache Out[N] and in the '_N' automatic variables. |
|
2932 | cache Out[N] and in the '_N' automatic variables. | |
2933 |
|
2933 | |||
2934 | Notes: |
|
2934 | Notes: | |
2935 |
|
2935 | |||
2936 | 1) If an input line begins with '!!', then %sx is automatically |
|
2936 | 1) If an input line begins with '!!', then %sx is automatically | |
2937 | invoked. That is, while: |
|
2937 | invoked. That is, while: | |
2938 | !ls |
|
2938 | !ls | |
2939 | causes ipython to simply issue system('ls'), typing |
|
2939 | causes ipython to simply issue system('ls'), typing | |
2940 | !!ls |
|
2940 | !!ls | |
2941 | is a shorthand equivalent to: |
|
2941 | is a shorthand equivalent to: | |
2942 | %sx ls |
|
2942 | %sx ls | |
2943 |
|
2943 | |||
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2945 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2945 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2946 | to process line-oriented shell output via further python commands. |
|
2946 | to process line-oriented shell output via further python commands. | |
2947 | %sc is meant to provide much finer control, but requires more |
|
2947 | %sc is meant to provide much finer control, but requires more | |
2948 | typing. |
|
2948 | typing. | |
2949 |
|
2949 | |||
2950 | 3) Just like %sc -l, this is a list with special attributes: |
|
2950 | 3) Just like %sc -l, this is a list with special attributes: | |
2951 |
|
2951 | |||
2952 | .l (or .list) : value as list. |
|
2952 | .l (or .list) : value as list. | |
2953 | .n (or .nlstr): value as newline-separated string. |
|
2953 | .n (or .nlstr): value as newline-separated string. | |
2954 | .s (or .spstr): value as whitespace-separated string. |
|
2954 | .s (or .spstr): value as whitespace-separated string. | |
2955 |
|
2955 | |||
2956 | This is very useful when trying to use such lists as arguments to |
|
2956 | This is very useful when trying to use such lists as arguments to | |
2957 | system commands.""" |
|
2957 | system commands.""" | |
2958 |
|
2958 | |||
2959 | if parameter_s: |
|
2959 | if parameter_s: | |
2960 | return self.shell.getoutput(parameter_s) |
|
2960 | return self.shell.getoutput(parameter_s) | |
2961 |
|
2961 | |||
2962 | def magic_r(self, parameter_s=''): |
|
2962 | def magic_r(self, parameter_s=''): | |
2963 | """Repeat previous input. |
|
2963 | """Repeat previous input. | |
2964 |
|
2964 | |||
2965 | Note: Consider using the more powerfull %rep instead! |
|
2965 | Note: Consider using the more powerfull %rep instead! | |
2966 |
|
2966 | |||
2967 | If given an argument, repeats the previous command which starts with |
|
2967 | If given an argument, repeats the previous command which starts with | |
2968 | the same string, otherwise it just repeats the previous input. |
|
2968 | the same string, otherwise it just repeats the previous input. | |
2969 |
|
2969 | |||
2970 | Shell escaped commands (with ! as first character) are not recognized |
|
2970 | Shell escaped commands (with ! as first character) are not recognized | |
2971 | by this system, only pure python code and magic commands. |
|
2971 | by this system, only pure python code and magic commands. | |
2972 | """ |
|
2972 | """ | |
2973 |
|
2973 | |||
2974 | start = parameter_s.strip() |
|
2974 | start = parameter_s.strip() | |
2975 | esc_magic = ESC_MAGIC |
|
2975 | esc_magic = ESC_MAGIC | |
2976 | # Identify magic commands even if automagic is on (which means |
|
2976 | # Identify magic commands even if automagic is on (which means | |
2977 | # the in-memory version is different from that typed by the user). |
|
2977 | # the in-memory version is different from that typed by the user). | |
2978 | if self.shell.automagic: |
|
2978 | if self.shell.automagic: | |
2979 | start_magic = esc_magic+start |
|
2979 | start_magic = esc_magic+start | |
2980 | else: |
|
2980 | else: | |
2981 | start_magic = start |
|
2981 | start_magic = start | |
2982 | # Look through the input history in reverse |
|
2982 | # Look through the input history in reverse | |
2983 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
2983 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): | |
2984 | input = self.shell.input_hist[n] |
|
2984 | input = self.shell.history_manager.input_hist_parsed[n] | |
2985 | # skip plain 'r' lines so we don't recurse to infinity |
|
2985 | # skip plain 'r' lines so we don't recurse to infinity | |
2986 | if input != '_ip.magic("r")\n' and \ |
|
2986 | if input != '_ip.magic("r")\n' and \ | |
2987 | (input.startswith(start) or input.startswith(start_magic)): |
|
2987 | (input.startswith(start) or input.startswith(start_magic)): | |
2988 | #print 'match',`input` # dbg |
|
2988 | #print 'match',`input` # dbg | |
2989 | print 'Executing:',input, |
|
2989 | print 'Executing:',input, | |
2990 | self.shell.run_cell(input) |
|
2990 | self.shell.run_cell(input) | |
2991 | return |
|
2991 | return | |
2992 | print 'No previous input matching `%s` found.' % start |
|
2992 | print 'No previous input matching `%s` found.' % start | |
2993 |
|
2993 | |||
2994 |
|
2994 | |||
2995 | def magic_bookmark(self, parameter_s=''): |
|
2995 | def magic_bookmark(self, parameter_s=''): | |
2996 | """Manage IPython's bookmark system. |
|
2996 | """Manage IPython's bookmark system. | |
2997 |
|
2997 | |||
2998 | %bookmark <name> - set bookmark to current dir |
|
2998 | %bookmark <name> - set bookmark to current dir | |
2999 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2999 | %bookmark <name> <dir> - set bookmark to <dir> | |
3000 | %bookmark -l - list all bookmarks |
|
3000 | %bookmark -l - list all bookmarks | |
3001 | %bookmark -d <name> - remove bookmark |
|
3001 | %bookmark -d <name> - remove bookmark | |
3002 | %bookmark -r - remove all bookmarks |
|
3002 | %bookmark -r - remove all bookmarks | |
3003 |
|
3003 | |||
3004 | You can later on access a bookmarked folder with: |
|
3004 | You can later on access a bookmarked folder with: | |
3005 | %cd -b <name> |
|
3005 | %cd -b <name> | |
3006 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3006 | or simply '%cd <name>' if there is no directory called <name> AND | |
3007 | there is such a bookmark defined. |
|
3007 | there is such a bookmark defined. | |
3008 |
|
3008 | |||
3009 | Your bookmarks persist through IPython sessions, but they are |
|
3009 | Your bookmarks persist through IPython sessions, but they are | |
3010 | associated with each profile.""" |
|
3010 | associated with each profile.""" | |
3011 |
|
3011 | |||
3012 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3012 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3013 | if len(args) > 2: |
|
3013 | if len(args) > 2: | |
3014 | raise UsageError("%bookmark: too many arguments") |
|
3014 | raise UsageError("%bookmark: too many arguments") | |
3015 |
|
3015 | |||
3016 | bkms = self.db.get('bookmarks',{}) |
|
3016 | bkms = self.db.get('bookmarks',{}) | |
3017 |
|
3017 | |||
3018 | if opts.has_key('d'): |
|
3018 | if opts.has_key('d'): | |
3019 | try: |
|
3019 | try: | |
3020 | todel = args[0] |
|
3020 | todel = args[0] | |
3021 | except IndexError: |
|
3021 | except IndexError: | |
3022 | raise UsageError( |
|
3022 | raise UsageError( | |
3023 | "%bookmark -d: must provide a bookmark to delete") |
|
3023 | "%bookmark -d: must provide a bookmark to delete") | |
3024 | else: |
|
3024 | else: | |
3025 | try: |
|
3025 | try: | |
3026 | del bkms[todel] |
|
3026 | del bkms[todel] | |
3027 | except KeyError: |
|
3027 | except KeyError: | |
3028 | raise UsageError( |
|
3028 | raise UsageError( | |
3029 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3029 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3030 |
|
3030 | |||
3031 | elif opts.has_key('r'): |
|
3031 | elif opts.has_key('r'): | |
3032 | bkms = {} |
|
3032 | bkms = {} | |
3033 | elif opts.has_key('l'): |
|
3033 | elif opts.has_key('l'): | |
3034 | bks = bkms.keys() |
|
3034 | bks = bkms.keys() | |
3035 | bks.sort() |
|
3035 | bks.sort() | |
3036 | if bks: |
|
3036 | if bks: | |
3037 | size = max(map(len,bks)) |
|
3037 | size = max(map(len,bks)) | |
3038 | else: |
|
3038 | else: | |
3039 | size = 0 |
|
3039 | size = 0 | |
3040 | fmt = '%-'+str(size)+'s -> %s' |
|
3040 | fmt = '%-'+str(size)+'s -> %s' | |
3041 | print 'Current bookmarks:' |
|
3041 | print 'Current bookmarks:' | |
3042 | for bk in bks: |
|
3042 | for bk in bks: | |
3043 | print fmt % (bk,bkms[bk]) |
|
3043 | print fmt % (bk,bkms[bk]) | |
3044 | else: |
|
3044 | else: | |
3045 | if not args: |
|
3045 | if not args: | |
3046 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3046 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3047 | elif len(args)==1: |
|
3047 | elif len(args)==1: | |
3048 | bkms[args[0]] = os.getcwd() |
|
3048 | bkms[args[0]] = os.getcwd() | |
3049 | elif len(args)==2: |
|
3049 | elif len(args)==2: | |
3050 | bkms[args[0]] = args[1] |
|
3050 | bkms[args[0]] = args[1] | |
3051 | self.db['bookmarks'] = bkms |
|
3051 | self.db['bookmarks'] = bkms | |
3052 |
|
3052 | |||
3053 | def magic_pycat(self, parameter_s=''): |
|
3053 | def magic_pycat(self, parameter_s=''): | |
3054 | """Show a syntax-highlighted file through a pager. |
|
3054 | """Show a syntax-highlighted file through a pager. | |
3055 |
|
3055 | |||
3056 | This magic is similar to the cat utility, but it will assume the file |
|
3056 | This magic is similar to the cat utility, but it will assume the file | |
3057 | to be Python source and will show it with syntax highlighting. """ |
|
3057 | to be Python source and will show it with syntax highlighting. """ | |
3058 |
|
3058 | |||
3059 | try: |
|
3059 | try: | |
3060 | filename = get_py_filename(parameter_s) |
|
3060 | filename = get_py_filename(parameter_s) | |
3061 | cont = file_read(filename) |
|
3061 | cont = file_read(filename) | |
3062 | except IOError: |
|
3062 | except IOError: | |
3063 | try: |
|
3063 | try: | |
3064 | cont = eval(parameter_s,self.user_ns) |
|
3064 | cont = eval(parameter_s,self.user_ns) | |
3065 | except NameError: |
|
3065 | except NameError: | |
3066 | cont = None |
|
3066 | cont = None | |
3067 | if cont is None: |
|
3067 | if cont is None: | |
3068 | print "Error: no such file or variable" |
|
3068 | print "Error: no such file or variable" | |
3069 | return |
|
3069 | return | |
3070 |
|
3070 | |||
3071 | page.page(self.shell.pycolorize(cont)) |
|
3071 | page.page(self.shell.pycolorize(cont)) | |
3072 |
|
3072 | |||
3073 | def _rerun_pasted(self): |
|
3073 | def _rerun_pasted(self): | |
3074 | """ Rerun a previously pasted command. |
|
3074 | """ Rerun a previously pasted command. | |
3075 | """ |
|
3075 | """ | |
3076 | b = self.user_ns.get('pasted_block', None) |
|
3076 | b = self.user_ns.get('pasted_block', None) | |
3077 | if b is None: |
|
3077 | if b is None: | |
3078 | raise UsageError('No previous pasted block available') |
|
3078 | raise UsageError('No previous pasted block available') | |
3079 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3079 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3080 | exec b in self.user_ns |
|
3080 | exec b in self.user_ns | |
3081 |
|
3081 | |||
3082 | def _get_pasted_lines(self, sentinel): |
|
3082 | def _get_pasted_lines(self, sentinel): | |
3083 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3083 | """ Yield pasted lines until the user enters the given sentinel value. | |
3084 | """ |
|
3084 | """ | |
3085 | from IPython.core import interactiveshell |
|
3085 | from IPython.core import interactiveshell | |
3086 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3086 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3087 | while True: |
|
3087 | while True: | |
3088 | l = interactiveshell.raw_input_original(':') |
|
3088 | l = interactiveshell.raw_input_original(':') | |
3089 | if l == sentinel: |
|
3089 | if l == sentinel: | |
3090 | return |
|
3090 | return | |
3091 | else: |
|
3091 | else: | |
3092 | yield l |
|
3092 | yield l | |
3093 |
|
3093 | |||
3094 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3094 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3095 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3095 | """ Strip non-code parts of a sequence of lines to return a block of | |
3096 | code. |
|
3096 | code. | |
3097 | """ |
|
3097 | """ | |
3098 | # Regular expressions that declare text we strip from the input: |
|
3098 | # Regular expressions that declare text we strip from the input: | |
3099 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3099 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3100 | r'^\s*(\s?>)+', # Python input prompt |
|
3100 | r'^\s*(\s?>)+', # Python input prompt | |
3101 | r'^\s*\.{3,}', # Continuation prompts |
|
3101 | r'^\s*\.{3,}', # Continuation prompts | |
3102 | r'^\++', |
|
3102 | r'^\++', | |
3103 | ] |
|
3103 | ] | |
3104 |
|
3104 | |||
3105 | strip_from_start = map(re.compile,strip_re) |
|
3105 | strip_from_start = map(re.compile,strip_re) | |
3106 |
|
3106 | |||
3107 | lines = [] |
|
3107 | lines = [] | |
3108 | for l in raw_lines: |
|
3108 | for l in raw_lines: | |
3109 | for pat in strip_from_start: |
|
3109 | for pat in strip_from_start: | |
3110 | l = pat.sub('',l) |
|
3110 | l = pat.sub('',l) | |
3111 | lines.append(l) |
|
3111 | lines.append(l) | |
3112 |
|
3112 | |||
3113 | block = "\n".join(lines) + '\n' |
|
3113 | block = "\n".join(lines) + '\n' | |
3114 | #print "block:\n",block |
|
3114 | #print "block:\n",block | |
3115 | return block |
|
3115 | return block | |
3116 |
|
3116 | |||
3117 | def _execute_block(self, block, par): |
|
3117 | def _execute_block(self, block, par): | |
3118 | """ Execute a block, or store it in a variable, per the user's request. |
|
3118 | """ Execute a block, or store it in a variable, per the user's request. | |
3119 | """ |
|
3119 | """ | |
3120 | if not par: |
|
3120 | if not par: | |
3121 | b = textwrap.dedent(block) |
|
3121 | b = textwrap.dedent(block) | |
3122 | self.user_ns['pasted_block'] = b |
|
3122 | self.user_ns['pasted_block'] = b | |
3123 | exec b in self.user_ns |
|
3123 | exec b in self.user_ns | |
3124 | else: |
|
3124 | else: | |
3125 | self.user_ns[par] = SList(block.splitlines()) |
|
3125 | self.user_ns[par] = SList(block.splitlines()) | |
3126 | print "Block assigned to '%s'" % par |
|
3126 | print "Block assigned to '%s'" % par | |
3127 |
|
3127 | |||
3128 | def magic_quickref(self,arg): |
|
3128 | def magic_quickref(self,arg): | |
3129 | """ Show a quick reference sheet """ |
|
3129 | """ Show a quick reference sheet """ | |
3130 | import IPython.core.usage |
|
3130 | import IPython.core.usage | |
3131 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3131 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3132 |
|
3132 | |||
3133 | page.page(qr) |
|
3133 | page.page(qr) | |
3134 |
|
3134 | |||
3135 | def magic_doctest_mode(self,parameter_s=''): |
|
3135 | def magic_doctest_mode(self,parameter_s=''): | |
3136 | """Toggle doctest mode on and off. |
|
3136 | """Toggle doctest mode on and off. | |
3137 |
|
3137 | |||
3138 | This mode is intended to make IPython behave as much as possible like a |
|
3138 | This mode is intended to make IPython behave as much as possible like a | |
3139 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3139 | plain Python shell, from the perspective of how its prompts, exceptions | |
3140 | and output look. This makes it easy to copy and paste parts of a |
|
3140 | and output look. This makes it easy to copy and paste parts of a | |
3141 | session into doctests. It does so by: |
|
3141 | session into doctests. It does so by: | |
3142 |
|
3142 | |||
3143 | - Changing the prompts to the classic ``>>>`` ones. |
|
3143 | - Changing the prompts to the classic ``>>>`` ones. | |
3144 | - Changing the exception reporting mode to 'Plain'. |
|
3144 | - Changing the exception reporting mode to 'Plain'. | |
3145 | - Disabling pretty-printing of output. |
|
3145 | - Disabling pretty-printing of output. | |
3146 |
|
3146 | |||
3147 | Note that IPython also supports the pasting of code snippets that have |
|
3147 | Note that IPython also supports the pasting of code snippets that have | |
3148 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3148 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3149 | doctests from files or docstrings (even if they have leading |
|
3149 | doctests from files or docstrings (even if they have leading | |
3150 | whitespace), and the code will execute correctly. You can then use |
|
3150 | whitespace), and the code will execute correctly. You can then use | |
3151 | '%history -t' to see the translated history; this will give you the |
|
3151 | '%history -t' to see the translated history; this will give you the | |
3152 | input after removal of all the leading prompts and whitespace, which |
|
3152 | input after removal of all the leading prompts and whitespace, which | |
3153 | can be pasted back into an editor. |
|
3153 | can be pasted back into an editor. | |
3154 |
|
3154 | |||
3155 | With these features, you can switch into this mode easily whenever you |
|
3155 | With these features, you can switch into this mode easily whenever you | |
3156 | need to do testing and changes to doctests, without having to leave |
|
3156 | need to do testing and changes to doctests, without having to leave | |
3157 | your existing IPython session. |
|
3157 | your existing IPython session. | |
3158 | """ |
|
3158 | """ | |
3159 |
|
3159 | |||
3160 | from IPython.utils.ipstruct import Struct |
|
3160 | from IPython.utils.ipstruct import Struct | |
3161 |
|
3161 | |||
3162 | # Shorthands |
|
3162 | # Shorthands | |
3163 | shell = self.shell |
|
3163 | shell = self.shell | |
3164 | oc = shell.displayhook |
|
3164 | oc = shell.displayhook | |
3165 | meta = shell.meta |
|
3165 | meta = shell.meta | |
3166 | # dstore is a data store kept in the instance metadata bag to track any |
|
3166 | # dstore is a data store kept in the instance metadata bag to track any | |
3167 | # changes we make, so we can undo them later. |
|
3167 | # changes we make, so we can undo them later. | |
3168 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3168 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3169 | save_dstore = dstore.setdefault |
|
3169 | save_dstore = dstore.setdefault | |
3170 |
|
3170 | |||
3171 | # save a few values we'll need to recover later |
|
3171 | # save a few values we'll need to recover later | |
3172 | mode = save_dstore('mode',False) |
|
3172 | mode = save_dstore('mode',False) | |
3173 | save_dstore('rc_pprint',shell.pprint) |
|
3173 | save_dstore('rc_pprint',shell.pprint) | |
3174 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3174 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3175 | save_dstore('rc_separate_out',shell.separate_out) |
|
3175 | save_dstore('rc_separate_out',shell.separate_out) | |
3176 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3176 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3177 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3177 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3178 | save_dstore('rc_separate_in',shell.separate_in) |
|
3178 | save_dstore('rc_separate_in',shell.separate_in) | |
3179 |
|
3179 | |||
3180 | if mode == False: |
|
3180 | if mode == False: | |
3181 | # turn on |
|
3181 | # turn on | |
3182 | oc.prompt1.p_template = '>>> ' |
|
3182 | oc.prompt1.p_template = '>>> ' | |
3183 | oc.prompt2.p_template = '... ' |
|
3183 | oc.prompt2.p_template = '... ' | |
3184 | oc.prompt_out.p_template = '' |
|
3184 | oc.prompt_out.p_template = '' | |
3185 |
|
3185 | |||
3186 | # Prompt separators like plain python |
|
3186 | # Prompt separators like plain python | |
3187 | oc.input_sep = oc.prompt1.sep = '' |
|
3187 | oc.input_sep = oc.prompt1.sep = '' | |
3188 | oc.output_sep = '' |
|
3188 | oc.output_sep = '' | |
3189 | oc.output_sep2 = '' |
|
3189 | oc.output_sep2 = '' | |
3190 |
|
3190 | |||
3191 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3191 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3192 | oc.prompt_out.pad_left = False |
|
3192 | oc.prompt_out.pad_left = False | |
3193 |
|
3193 | |||
3194 | shell.pprint = False |
|
3194 | shell.pprint = False | |
3195 |
|
3195 | |||
3196 | shell.magic_xmode('Plain') |
|
3196 | shell.magic_xmode('Plain') | |
3197 | else: |
|
3197 | else: | |
3198 | # turn off |
|
3198 | # turn off | |
3199 | oc.prompt1.p_template = shell.prompt_in1 |
|
3199 | oc.prompt1.p_template = shell.prompt_in1 | |
3200 | oc.prompt2.p_template = shell.prompt_in2 |
|
3200 | oc.prompt2.p_template = shell.prompt_in2 | |
3201 | oc.prompt_out.p_template = shell.prompt_out |
|
3201 | oc.prompt_out.p_template = shell.prompt_out | |
3202 |
|
3202 | |||
3203 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3203 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3204 |
|
3204 | |||
3205 | oc.output_sep = dstore.rc_separate_out |
|
3205 | oc.output_sep = dstore.rc_separate_out | |
3206 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3206 | oc.output_sep2 = dstore.rc_separate_out2 | |
3207 |
|
3207 | |||
3208 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3208 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3209 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3209 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3210 |
|
3210 | |||
3211 | shell.pprint = dstore.rc_pprint |
|
3211 | shell.pprint = dstore.rc_pprint | |
3212 |
|
3212 | |||
3213 | shell.magic_xmode(dstore.xmode) |
|
3213 | shell.magic_xmode(dstore.xmode) | |
3214 |
|
3214 | |||
3215 | # Store new mode and inform |
|
3215 | # Store new mode and inform | |
3216 | dstore.mode = bool(1-int(mode)) |
|
3216 | dstore.mode = bool(1-int(mode)) | |
3217 | mode_label = ['OFF','ON'][dstore.mode] |
|
3217 | mode_label = ['OFF','ON'][dstore.mode] | |
3218 | print 'Doctest mode is:', mode_label |
|
3218 | print 'Doctest mode is:', mode_label | |
3219 |
|
3219 | |||
3220 | def magic_gui(self, parameter_s=''): |
|
3220 | def magic_gui(self, parameter_s=''): | |
3221 | """Enable or disable IPython GUI event loop integration. |
|
3221 | """Enable or disable IPython GUI event loop integration. | |
3222 |
|
3222 | |||
3223 | %gui [GUINAME] |
|
3223 | %gui [GUINAME] | |
3224 |
|
3224 | |||
3225 | This magic replaces IPython's threaded shells that were activated |
|
3225 | This magic replaces IPython's threaded shells that were activated | |
3226 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3226 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3227 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3227 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3228 | interrupts should work without any problems. The following toolkits |
|
3228 | interrupts should work without any problems. The following toolkits | |
3229 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3229 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3230 |
|
3230 | |||
3231 | %gui wx # enable wxPython event loop integration |
|
3231 | %gui wx # enable wxPython event loop integration | |
3232 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3232 | %gui qt4|qt # enable PyQt4 event loop integration | |
3233 | %gui gtk # enable PyGTK event loop integration |
|
3233 | %gui gtk # enable PyGTK event loop integration | |
3234 | %gui tk # enable Tk event loop integration |
|
3234 | %gui tk # enable Tk event loop integration | |
3235 | %gui # disable all event loop integration |
|
3235 | %gui # disable all event loop integration | |
3236 |
|
3236 | |||
3237 | WARNING: after any of these has been called you can simply create |
|
3237 | WARNING: after any of these has been called you can simply create | |
3238 | an application object, but DO NOT start the event loop yourself, as |
|
3238 | an application object, but DO NOT start the event loop yourself, as | |
3239 | we have already handled that. |
|
3239 | we have already handled that. | |
3240 | """ |
|
3240 | """ | |
3241 | from IPython.lib.inputhook import enable_gui |
|
3241 | from IPython.lib.inputhook import enable_gui | |
3242 | opts, arg = self.parse_options(parameter_s, '') |
|
3242 | opts, arg = self.parse_options(parameter_s, '') | |
3243 | if arg=='': arg = None |
|
3243 | if arg=='': arg = None | |
3244 | return enable_gui(arg) |
|
3244 | return enable_gui(arg) | |
3245 |
|
3245 | |||
3246 | def magic_load_ext(self, module_str): |
|
3246 | def magic_load_ext(self, module_str): | |
3247 | """Load an IPython extension by its module name.""" |
|
3247 | """Load an IPython extension by its module name.""" | |
3248 | return self.extension_manager.load_extension(module_str) |
|
3248 | return self.extension_manager.load_extension(module_str) | |
3249 |
|
3249 | |||
3250 | def magic_unload_ext(self, module_str): |
|
3250 | def magic_unload_ext(self, module_str): | |
3251 | """Unload an IPython extension by its module name.""" |
|
3251 | """Unload an IPython extension by its module name.""" | |
3252 | self.extension_manager.unload_extension(module_str) |
|
3252 | self.extension_manager.unload_extension(module_str) | |
3253 |
|
3253 | |||
3254 | def magic_reload_ext(self, module_str): |
|
3254 | def magic_reload_ext(self, module_str): | |
3255 | """Reload an IPython extension by its module name.""" |
|
3255 | """Reload an IPython extension by its module name.""" | |
3256 | self.extension_manager.reload_extension(module_str) |
|
3256 | self.extension_manager.reload_extension(module_str) | |
3257 |
|
3257 | |||
3258 | @testdec.skip_doctest |
|
3258 | @testdec.skip_doctest | |
3259 | def magic_install_profiles(self, s): |
|
3259 | def magic_install_profiles(self, s): | |
3260 | """Install the default IPython profiles into the .ipython dir. |
|
3260 | """Install the default IPython profiles into the .ipython dir. | |
3261 |
|
3261 | |||
3262 | If the default profiles have already been installed, they will not |
|
3262 | If the default profiles have already been installed, they will not | |
3263 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3263 | be overwritten. You can force overwriting them by using the ``-o`` | |
3264 | option:: |
|
3264 | option:: | |
3265 |
|
3265 | |||
3266 | In [1]: %install_profiles -o |
|
3266 | In [1]: %install_profiles -o | |
3267 | """ |
|
3267 | """ | |
3268 | if '-o' in s: |
|
3268 | if '-o' in s: | |
3269 | overwrite = True |
|
3269 | overwrite = True | |
3270 | else: |
|
3270 | else: | |
3271 | overwrite = False |
|
3271 | overwrite = False | |
3272 | from IPython.config import profile |
|
3272 | from IPython.config import profile | |
3273 | profile_dir = os.path.split(profile.__file__)[0] |
|
3273 | profile_dir = os.path.split(profile.__file__)[0] | |
3274 | ipython_dir = self.ipython_dir |
|
3274 | ipython_dir = self.ipython_dir | |
3275 | files = os.listdir(profile_dir) |
|
3275 | files = os.listdir(profile_dir) | |
3276 |
|
3276 | |||
3277 | to_install = [] |
|
3277 | to_install = [] | |
3278 | for f in files: |
|
3278 | for f in files: | |
3279 | if f.startswith('ipython_config'): |
|
3279 | if f.startswith('ipython_config'): | |
3280 | src = os.path.join(profile_dir, f) |
|
3280 | src = os.path.join(profile_dir, f) | |
3281 | dst = os.path.join(ipython_dir, f) |
|
3281 | dst = os.path.join(ipython_dir, f) | |
3282 | if (not os.path.isfile(dst)) or overwrite: |
|
3282 | if (not os.path.isfile(dst)) or overwrite: | |
3283 | to_install.append((f, src, dst)) |
|
3283 | to_install.append((f, src, dst)) | |
3284 | if len(to_install)>0: |
|
3284 | if len(to_install)>0: | |
3285 | print "Installing profiles to: ", ipython_dir |
|
3285 | print "Installing profiles to: ", ipython_dir | |
3286 | for (f, src, dst) in to_install: |
|
3286 | for (f, src, dst) in to_install: | |
3287 | shutil.copy(src, dst) |
|
3287 | shutil.copy(src, dst) | |
3288 | print " %s" % f |
|
3288 | print " %s" % f | |
3289 |
|
3289 | |||
3290 | def magic_install_default_config(self, s): |
|
3290 | def magic_install_default_config(self, s): | |
3291 | """Install IPython's default config file into the .ipython dir. |
|
3291 | """Install IPython's default config file into the .ipython dir. | |
3292 |
|
3292 | |||
3293 | If the default config file (:file:`ipython_config.py`) is already |
|
3293 | If the default config file (:file:`ipython_config.py`) is already | |
3294 | installed, it will not be overwritten. You can force overwriting |
|
3294 | installed, it will not be overwritten. You can force overwriting | |
3295 | by using the ``-o`` option:: |
|
3295 | by using the ``-o`` option:: | |
3296 |
|
3296 | |||
3297 | In [1]: %install_default_config |
|
3297 | In [1]: %install_default_config | |
3298 | """ |
|
3298 | """ | |
3299 | if '-o' in s: |
|
3299 | if '-o' in s: | |
3300 | overwrite = True |
|
3300 | overwrite = True | |
3301 | else: |
|
3301 | else: | |
3302 | overwrite = False |
|
3302 | overwrite = False | |
3303 | from IPython.config import default |
|
3303 | from IPython.config import default | |
3304 | config_dir = os.path.split(default.__file__)[0] |
|
3304 | config_dir = os.path.split(default.__file__)[0] | |
3305 | ipython_dir = self.ipython_dir |
|
3305 | ipython_dir = self.ipython_dir | |
3306 | default_config_file_name = 'ipython_config.py' |
|
3306 | default_config_file_name = 'ipython_config.py' | |
3307 | src = os.path.join(config_dir, default_config_file_name) |
|
3307 | src = os.path.join(config_dir, default_config_file_name) | |
3308 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3308 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3309 | if (not os.path.isfile(dst)) or overwrite: |
|
3309 | if (not os.path.isfile(dst)) or overwrite: | |
3310 | shutil.copy(src, dst) |
|
3310 | shutil.copy(src, dst) | |
3311 | print "Installing default config file: %s" % dst |
|
3311 | print "Installing default config file: %s" % dst | |
3312 |
|
3312 | |||
3313 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3313 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3314 | # handling and modify slightly %run |
|
3314 | # handling and modify slightly %run | |
3315 |
|
3315 | |||
3316 | @testdec.skip_doctest |
|
3316 | @testdec.skip_doctest | |
3317 | def _pylab_magic_run(self, parameter_s=''): |
|
3317 | def _pylab_magic_run(self, parameter_s=''): | |
3318 | Magic.magic_run(self, parameter_s, |
|
3318 | Magic.magic_run(self, parameter_s, | |
3319 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3319 | runner=mpl_runner(self.shell.safe_execfile)) | |
3320 |
|
3320 | |||
3321 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3321 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3322 |
|
3322 | |||
3323 | @testdec.skip_doctest |
|
3323 | @testdec.skip_doctest | |
3324 | def magic_pylab(self, s): |
|
3324 | def magic_pylab(self, s): | |
3325 | """Load numpy and matplotlib to work interactively. |
|
3325 | """Load numpy and matplotlib to work interactively. | |
3326 |
|
3326 | |||
3327 | %pylab [GUINAME] |
|
3327 | %pylab [GUINAME] | |
3328 |
|
3328 | |||
3329 | This function lets you activate pylab (matplotlib, numpy and |
|
3329 | This function lets you activate pylab (matplotlib, numpy and | |
3330 | interactive support) at any point during an IPython session. |
|
3330 | interactive support) at any point during an IPython session. | |
3331 |
|
3331 | |||
3332 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3332 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3333 | pylab and mlab, as well as all names from numpy and pylab. |
|
3333 | pylab and mlab, as well as all names from numpy and pylab. | |
3334 |
|
3334 | |||
3335 | Parameters |
|
3335 | Parameters | |
3336 | ---------- |
|
3336 | ---------- | |
3337 | guiname : optional |
|
3337 | guiname : optional | |
3338 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3338 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3339 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3339 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3340 | otherwise matplotlib's default (which you can override in your |
|
3340 | otherwise matplotlib's default (which you can override in your | |
3341 | matplotlib config file) is used. |
|
3341 | matplotlib config file) is used. | |
3342 |
|
3342 | |||
3343 | Examples |
|
3343 | Examples | |
3344 | -------- |
|
3344 | -------- | |
3345 | In this case, where the MPL default is TkAgg: |
|
3345 | In this case, where the MPL default is TkAgg: | |
3346 | In [2]: %pylab |
|
3346 | In [2]: %pylab | |
3347 |
|
3347 | |||
3348 | Welcome to pylab, a matplotlib-based Python environment. |
|
3348 | Welcome to pylab, a matplotlib-based Python environment. | |
3349 | Backend in use: TkAgg |
|
3349 | Backend in use: TkAgg | |
3350 | For more information, type 'help(pylab)'. |
|
3350 | For more information, type 'help(pylab)'. | |
3351 |
|
3351 | |||
3352 | But you can explicitly request a different backend: |
|
3352 | But you can explicitly request a different backend: | |
3353 | In [3]: %pylab qt |
|
3353 | In [3]: %pylab qt | |
3354 |
|
3354 | |||
3355 | Welcome to pylab, a matplotlib-based Python environment. |
|
3355 | Welcome to pylab, a matplotlib-based Python environment. | |
3356 | Backend in use: Qt4Agg |
|
3356 | Backend in use: Qt4Agg | |
3357 | For more information, type 'help(pylab)'. |
|
3357 | For more information, type 'help(pylab)'. | |
3358 | """ |
|
3358 | """ | |
3359 | self.shell.enable_pylab(s) |
|
3359 | self.shell.enable_pylab(s) | |
3360 |
|
3360 | |||
3361 | def magic_tb(self, s): |
|
3361 | def magic_tb(self, s): | |
3362 | """Print the last traceback with the currently active exception mode. |
|
3362 | """Print the last traceback with the currently active exception mode. | |
3363 |
|
3363 | |||
3364 | See %xmode for changing exception reporting modes.""" |
|
3364 | See %xmode for changing exception reporting modes.""" | |
3365 | self.shell.showtraceback() |
|
3365 | self.shell.showtraceback() | |
3366 |
|
3366 | |||
3367 | # end Magic |
|
3367 | # end Magic |
@@ -1,615 +1,615 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
2 | """Subclass of InteractiveShell for terminal based frontends.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | from contextlib import nested |
|
19 | from contextlib import nested | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 |
|
23 | |||
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.usage import interactive_usage, default_banner |
|
25 | from IPython.core.usage import interactive_usage, default_banner | |
26 | from IPython.core.inputlist import InputList |
|
26 | from IPython.core.inputlist import InputList | |
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | |
28 | from IPython.lib.inputhook import enable_gui |
|
28 | from IPython.lib.inputhook import enable_gui | |
29 | from IPython.lib.pylabtools import pylab_activate |
|
29 | from IPython.lib.pylabtools import pylab_activate | |
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title | |
31 | from IPython.utils.process import abbrev_cwd |
|
31 | from IPython.utils.process import abbrev_cwd | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 | from IPython.utils.text import num_ini_spaces |
|
33 | from IPython.utils.text import num_ini_spaces | |
34 | from IPython.utils.traitlets import Int, Str, CBool |
|
34 | from IPython.utils.traitlets import Int, Str, CBool | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | # Utilities |
|
38 | # Utilities | |
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | def get_default_editor(): |
|
42 | def get_default_editor(): | |
43 | try: |
|
43 | try: | |
44 | ed = os.environ['EDITOR'] |
|
44 | ed = os.environ['EDITOR'] | |
45 | except KeyError: |
|
45 | except KeyError: | |
46 | if os.name == 'posix': |
|
46 | if os.name == 'posix': | |
47 | ed = 'vi' # the only one guaranteed to be there! |
|
47 | ed = 'vi' # the only one guaranteed to be there! | |
48 | else: |
|
48 | else: | |
49 | ed = 'notepad' # same in Windows! |
|
49 | ed = 'notepad' # same in Windows! | |
50 | return ed |
|
50 | return ed | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | # store the builtin raw_input globally, and use this always, in case user code |
|
53 | # store the builtin raw_input globally, and use this always, in case user code | |
54 | # overwrites it (like wx.py.PyShell does) |
|
54 | # overwrites it (like wx.py.PyShell does) | |
55 | raw_input_original = raw_input |
|
55 | raw_input_original = raw_input | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | #----------------------------------------------------------------------------- |
|
58 | #----------------------------------------------------------------------------- | |
59 | # Main class |
|
59 | # Main class | |
60 | #----------------------------------------------------------------------------- |
|
60 | #----------------------------------------------------------------------------- | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | class TerminalInteractiveShell(InteractiveShell): |
|
63 | class TerminalInteractiveShell(InteractiveShell): | |
64 |
|
64 | |||
65 | autoedit_syntax = CBool(False, config=True) |
|
65 | autoedit_syntax = CBool(False, config=True) | |
66 | banner = Str('') |
|
66 | banner = Str('') | |
67 | banner1 = Str(default_banner, config=True) |
|
67 | banner1 = Str(default_banner, config=True) | |
68 | banner2 = Str('', config=True) |
|
68 | banner2 = Str('', config=True) | |
69 | confirm_exit = CBool(True, config=True) |
|
69 | confirm_exit = CBool(True, config=True) | |
70 | # This display_banner only controls whether or not self.show_banner() |
|
70 | # This display_banner only controls whether or not self.show_banner() | |
71 | # is called when mainloop/interact are called. The default is False |
|
71 | # is called when mainloop/interact are called. The default is False | |
72 | # because for the terminal based application, the banner behavior |
|
72 | # because for the terminal based application, the banner behavior | |
73 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
73 | # is controlled by Global.display_banner, which IPythonApp looks at | |
74 | # to determine if *it* should call show_banner() by hand or not. |
|
74 | # to determine if *it* should call show_banner() by hand or not. | |
75 | display_banner = CBool(False) # This isn't configurable! |
|
75 | display_banner = CBool(False) # This isn't configurable! | |
76 | embedded = CBool(False) |
|
76 | embedded = CBool(False) | |
77 | embedded_active = CBool(False) |
|
77 | embedded_active = CBool(False) | |
78 | editor = Str(get_default_editor(), config=True) |
|
78 | editor = Str(get_default_editor(), config=True) | |
79 | pager = Str('less', config=True) |
|
79 | pager = Str('less', config=True) | |
80 |
|
80 | |||
81 | screen_length = Int(0, config=True) |
|
81 | screen_length = Int(0, config=True) | |
82 | term_title = CBool(False, config=True) |
|
82 | term_title = CBool(False, config=True) | |
83 |
|
83 | |||
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, |
|
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, | |
85 | user_global_ns=None, custom_exceptions=((),None), |
|
85 | user_global_ns=None, custom_exceptions=((),None), | |
86 | usage=None, banner1=None, banner2=None, |
|
86 | usage=None, banner1=None, banner2=None, | |
87 | display_banner=None): |
|
87 | display_banner=None): | |
88 |
|
88 | |||
89 | super(TerminalInteractiveShell, self).__init__( |
|
89 | super(TerminalInteractiveShell, self).__init__( | |
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, |
|
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, | |
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions |
|
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions | |
92 | ) |
|
92 | ) | |
93 | self.init_term_title() |
|
93 | self.init_term_title() | |
94 | self.init_usage(usage) |
|
94 | self.init_usage(usage) | |
95 | self.init_banner(banner1, banner2, display_banner) |
|
95 | self.init_banner(banner1, banner2, display_banner) | |
96 |
|
96 | |||
97 | #------------------------------------------------------------------------- |
|
97 | #------------------------------------------------------------------------- | |
98 | # Things related to the terminal |
|
98 | # Things related to the terminal | |
99 | #------------------------------------------------------------------------- |
|
99 | #------------------------------------------------------------------------- | |
100 |
|
100 | |||
101 | @property |
|
101 | @property | |
102 | def usable_screen_length(self): |
|
102 | def usable_screen_length(self): | |
103 | if self.screen_length == 0: |
|
103 | if self.screen_length == 0: | |
104 | return 0 |
|
104 | return 0 | |
105 | else: |
|
105 | else: | |
106 | num_lines_bot = self.separate_in.count('\n')+1 |
|
106 | num_lines_bot = self.separate_in.count('\n')+1 | |
107 | return self.screen_length - num_lines_bot |
|
107 | return self.screen_length - num_lines_bot | |
108 |
|
108 | |||
109 | def init_term_title(self): |
|
109 | def init_term_title(self): | |
110 | # Enable or disable the terminal title. |
|
110 | # Enable or disable the terminal title. | |
111 | if self.term_title: |
|
111 | if self.term_title: | |
112 | toggle_set_term_title(True) |
|
112 | toggle_set_term_title(True) | |
113 | set_term_title('IPython: ' + abbrev_cwd()) |
|
113 | set_term_title('IPython: ' + abbrev_cwd()) | |
114 | else: |
|
114 | else: | |
115 | toggle_set_term_title(False) |
|
115 | toggle_set_term_title(False) | |
116 |
|
116 | |||
117 | #------------------------------------------------------------------------- |
|
117 | #------------------------------------------------------------------------- | |
118 | # Things related to aliases |
|
118 | # Things related to aliases | |
119 | #------------------------------------------------------------------------- |
|
119 | #------------------------------------------------------------------------- | |
120 |
|
120 | |||
121 | def init_alias(self): |
|
121 | def init_alias(self): | |
122 | # The parent class defines aliases that can be safely used with any |
|
122 | # The parent class defines aliases that can be safely used with any | |
123 | # frontend. |
|
123 | # frontend. | |
124 | super(TerminalInteractiveShell, self).init_alias() |
|
124 | super(TerminalInteractiveShell, self).init_alias() | |
125 |
|
125 | |||
126 | # Now define aliases that only make sense on the terminal, because they |
|
126 | # Now define aliases that only make sense on the terminal, because they | |
127 | # need direct access to the console in a way that we can't emulate in |
|
127 | # need direct access to the console in a way that we can't emulate in | |
128 | # GUI or web frontend |
|
128 | # GUI or web frontend | |
129 | if os.name == 'posix': |
|
129 | if os.name == 'posix': | |
130 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), |
|
130 | aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), | |
131 | ('man', 'man')] |
|
131 | ('man', 'man')] | |
132 | elif os.name == 'nt': |
|
132 | elif os.name == 'nt': | |
133 | aliases = [('cls', 'cls')] |
|
133 | aliases = [('cls', 'cls')] | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | for name, cmd in aliases: |
|
136 | for name, cmd in aliases: | |
137 | self.alias_manager.define_alias(name, cmd) |
|
137 | self.alias_manager.define_alias(name, cmd) | |
138 |
|
138 | |||
139 | #------------------------------------------------------------------------- |
|
139 | #------------------------------------------------------------------------- | |
140 | # Things related to the banner and usage |
|
140 | # Things related to the banner and usage | |
141 | #------------------------------------------------------------------------- |
|
141 | #------------------------------------------------------------------------- | |
142 |
|
142 | |||
143 | def _banner1_changed(self): |
|
143 | def _banner1_changed(self): | |
144 | self.compute_banner() |
|
144 | self.compute_banner() | |
145 |
|
145 | |||
146 | def _banner2_changed(self): |
|
146 | def _banner2_changed(self): | |
147 | self.compute_banner() |
|
147 | self.compute_banner() | |
148 |
|
148 | |||
149 | def _term_title_changed(self, name, new_value): |
|
149 | def _term_title_changed(self, name, new_value): | |
150 | self.init_term_title() |
|
150 | self.init_term_title() | |
151 |
|
151 | |||
152 | def init_banner(self, banner1, banner2, display_banner): |
|
152 | def init_banner(self, banner1, banner2, display_banner): | |
153 | if banner1 is not None: |
|
153 | if banner1 is not None: | |
154 | self.banner1 = banner1 |
|
154 | self.banner1 = banner1 | |
155 | if banner2 is not None: |
|
155 | if banner2 is not None: | |
156 | self.banner2 = banner2 |
|
156 | self.banner2 = banner2 | |
157 | if display_banner is not None: |
|
157 | if display_banner is not None: | |
158 | self.display_banner = display_banner |
|
158 | self.display_banner = display_banner | |
159 | self.compute_banner() |
|
159 | self.compute_banner() | |
160 |
|
160 | |||
161 | def show_banner(self, banner=None): |
|
161 | def show_banner(self, banner=None): | |
162 | if banner is None: |
|
162 | if banner is None: | |
163 | banner = self.banner |
|
163 | banner = self.banner | |
164 | self.write(banner) |
|
164 | self.write(banner) | |
165 |
|
165 | |||
166 | def compute_banner(self): |
|
166 | def compute_banner(self): | |
167 | self.banner = self.banner1 |
|
167 | self.banner = self.banner1 | |
168 | if self.profile: |
|
168 | if self.profile: | |
169 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
169 | self.banner += '\nIPython profile: %s\n' % self.profile | |
170 | if self.banner2: |
|
170 | if self.banner2: | |
171 | self.banner += '\n' + self.banner2 |
|
171 | self.banner += '\n' + self.banner2 | |
172 |
|
172 | |||
173 | def init_usage(self, usage=None): |
|
173 | def init_usage(self, usage=None): | |
174 | if usage is None: |
|
174 | if usage is None: | |
175 | self.usage = interactive_usage |
|
175 | self.usage = interactive_usage | |
176 | else: |
|
176 | else: | |
177 | self.usage = usage |
|
177 | self.usage = usage | |
178 |
|
178 | |||
179 | #------------------------------------------------------------------------- |
|
179 | #------------------------------------------------------------------------- | |
180 | # Mainloop and code execution logic |
|
180 | # Mainloop and code execution logic | |
181 | #------------------------------------------------------------------------- |
|
181 | #------------------------------------------------------------------------- | |
182 |
|
182 | |||
183 | def mainloop(self, display_banner=None): |
|
183 | def mainloop(self, display_banner=None): | |
184 | """Start the mainloop. |
|
184 | """Start the mainloop. | |
185 |
|
185 | |||
186 | If an optional banner argument is given, it will override the |
|
186 | If an optional banner argument is given, it will override the | |
187 | internally created default banner. |
|
187 | internally created default banner. | |
188 | """ |
|
188 | """ | |
189 |
|
189 | |||
190 | with nested(self.builtin_trap, self.display_trap): |
|
190 | with nested(self.builtin_trap, self.display_trap): | |
191 |
|
191 | |||
192 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
192 | # if you run stuff with -c <cmd>, raw hist is not updated | |
193 | # ensure that it's in sync |
|
193 | # ensure that it's in sync | |
194 | self.history_manager.sync_inputs() |
|
194 | self.history_manager.sync_inputs() | |
195 |
|
195 | |||
196 | while 1: |
|
196 | while 1: | |
197 | try: |
|
197 | try: | |
198 | self.interact(display_banner=display_banner) |
|
198 | self.interact(display_banner=display_banner) | |
199 | #self.interact_with_readline() |
|
199 | #self.interact_with_readline() | |
200 | # XXX for testing of a readline-decoupled repl loop, call |
|
200 | # XXX for testing of a readline-decoupled repl loop, call | |
201 | # interact_with_readline above |
|
201 | # interact_with_readline above | |
202 | break |
|
202 | break | |
203 | except KeyboardInterrupt: |
|
203 | except KeyboardInterrupt: | |
204 | # this should not be necessary, but KeyboardInterrupt |
|
204 | # this should not be necessary, but KeyboardInterrupt | |
205 | # handling seems rather unpredictable... |
|
205 | # handling seems rather unpredictable... | |
206 | self.write("\nKeyboardInterrupt in interact()\n") |
|
206 | self.write("\nKeyboardInterrupt in interact()\n") | |
207 |
|
207 | |||
208 | def interact(self, display_banner=None): |
|
208 | def interact(self, display_banner=None): | |
209 | """Closely emulate the interactive Python console.""" |
|
209 | """Closely emulate the interactive Python console.""" | |
210 |
|
210 | |||
211 | # batch run -> do not interact |
|
211 | # batch run -> do not interact | |
212 | if self.exit_now: |
|
212 | if self.exit_now: | |
213 | return |
|
213 | return | |
214 |
|
214 | |||
215 | if display_banner is None: |
|
215 | if display_banner is None: | |
216 | display_banner = self.display_banner |
|
216 | display_banner = self.display_banner | |
217 | if display_banner: |
|
217 | if display_banner: | |
218 | self.show_banner() |
|
218 | self.show_banner() | |
219 |
|
219 | |||
220 | more = False |
|
220 | more = False | |
221 |
|
221 | |||
222 | # Mark activity in the builtins |
|
222 | # Mark activity in the builtins | |
223 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
223 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
224 |
|
224 | |||
225 | if self.has_readline: |
|
225 | if self.has_readline: | |
226 | self.readline_startup_hook(self.pre_readline) |
|
226 | self.readline_startup_hook(self.pre_readline) | |
227 | # exit_now is set by a call to %Exit or %Quit, through the |
|
227 | # exit_now is set by a call to %Exit or %Quit, through the | |
228 | # ask_exit callback. |
|
228 | # ask_exit callback. | |
229 |
|
229 | |||
230 | while not self.exit_now: |
|
230 | while not self.exit_now: | |
231 | self.hooks.pre_prompt_hook() |
|
231 | self.hooks.pre_prompt_hook() | |
232 | if more: |
|
232 | if more: | |
233 | try: |
|
233 | try: | |
234 | prompt = self.hooks.generate_prompt(True) |
|
234 | prompt = self.hooks.generate_prompt(True) | |
235 | except: |
|
235 | except: | |
236 | self.showtraceback() |
|
236 | self.showtraceback() | |
237 | if self.autoindent: |
|
237 | if self.autoindent: | |
238 | self.rl_do_indent = True |
|
238 | self.rl_do_indent = True | |
239 |
|
239 | |||
240 | else: |
|
240 | else: | |
241 | try: |
|
241 | try: | |
242 | prompt = self.hooks.generate_prompt(False) |
|
242 | prompt = self.hooks.generate_prompt(False) | |
243 | except: |
|
243 | except: | |
244 | self.showtraceback() |
|
244 | self.showtraceback() | |
245 | try: |
|
245 | try: | |
246 | line = self.raw_input(prompt) |
|
246 | line = self.raw_input(prompt) | |
247 | if self.exit_now: |
|
247 | if self.exit_now: | |
248 | # quick exit on sys.std[in|out] close |
|
248 | # quick exit on sys.std[in|out] close | |
249 | break |
|
249 | break | |
250 | if self.autoindent: |
|
250 | if self.autoindent: | |
251 | self.rl_do_indent = False |
|
251 | self.rl_do_indent = False | |
252 |
|
252 | |||
253 | except KeyboardInterrupt: |
|
253 | except KeyboardInterrupt: | |
254 | #double-guard against keyboardinterrupts during kbdint handling |
|
254 | #double-guard against keyboardinterrupts during kbdint handling | |
255 | try: |
|
255 | try: | |
256 | self.write('\nKeyboardInterrupt\n') |
|
256 | self.write('\nKeyboardInterrupt\n') | |
257 | self.resetbuffer() |
|
257 | self.resetbuffer() | |
258 | more = False |
|
258 | more = False | |
259 | except KeyboardInterrupt: |
|
259 | except KeyboardInterrupt: | |
260 | pass |
|
260 | pass | |
261 | except EOFError: |
|
261 | except EOFError: | |
262 | if self.autoindent: |
|
262 | if self.autoindent: | |
263 | self.rl_do_indent = False |
|
263 | self.rl_do_indent = False | |
264 | if self.has_readline: |
|
264 | if self.has_readline: | |
265 | self.readline_startup_hook(None) |
|
265 | self.readline_startup_hook(None) | |
266 | self.write('\n') |
|
266 | self.write('\n') | |
267 | self.exit() |
|
267 | self.exit() | |
268 | except bdb.BdbQuit: |
|
268 | except bdb.BdbQuit: | |
269 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
269 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
270 | 'Because of how pdb handles the stack, it is impossible\n' |
|
270 | 'Because of how pdb handles the stack, it is impossible\n' | |
271 | 'for IPython to properly format this particular exception.\n' |
|
271 | 'for IPython to properly format this particular exception.\n' | |
272 | 'IPython will resume normal operation.') |
|
272 | 'IPython will resume normal operation.') | |
273 | except: |
|
273 | except: | |
274 | # exceptions here are VERY RARE, but they can be triggered |
|
274 | # exceptions here are VERY RARE, but they can be triggered | |
275 | # asynchronously by signal handlers, for example. |
|
275 | # asynchronously by signal handlers, for example. | |
276 | self.showtraceback() |
|
276 | self.showtraceback() | |
277 | else: |
|
277 | else: | |
278 | self.input_splitter.push(line) |
|
278 | self.input_splitter.push(line) | |
279 | more = self.input_splitter.push_accepts_more() |
|
279 | more = self.input_splitter.push_accepts_more() | |
280 | if (self.SyntaxTB.last_syntax_error and |
|
280 | if (self.SyntaxTB.last_syntax_error and | |
281 | self.autoedit_syntax): |
|
281 | self.autoedit_syntax): | |
282 | self.edit_syntax_error() |
|
282 | self.edit_syntax_error() | |
283 | if not more: |
|
283 | if not more: | |
284 | source_raw = self.input_splitter.source_raw_reset()[1] |
|
284 | source_raw = self.input_splitter.source_raw_reset()[1] | |
285 | self.run_cell(source_raw) |
|
285 | self.run_cell(source_raw) | |
286 |
|
286 | |||
287 | # We are off again... |
|
287 | # We are off again... | |
288 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
288 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
289 |
|
289 | |||
290 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
290 | # Turn off the exit flag, so the mainloop can be restarted if desired | |
291 | self.exit_now = False |
|
291 | self.exit_now = False | |
292 |
|
292 | |||
293 | def raw_input(self, prompt='', continue_prompt=False): |
|
293 | def raw_input(self, prompt='', continue_prompt=False): | |
294 | """Write a prompt and read a line. |
|
294 | """Write a prompt and read a line. | |
295 |
|
295 | |||
296 | The returned line does not include the trailing newline. |
|
296 | The returned line does not include the trailing newline. | |
297 | When the user enters the EOF key sequence, EOFError is raised. |
|
297 | When the user enters the EOF key sequence, EOFError is raised. | |
298 |
|
298 | |||
299 | Optional inputs: |
|
299 | Optional inputs: | |
300 |
|
300 | |||
301 | - prompt(''): a string to be printed to prompt the user. |
|
301 | - prompt(''): a string to be printed to prompt the user. | |
302 |
|
302 | |||
303 | - continue_prompt(False): whether this line is the first one or a |
|
303 | - continue_prompt(False): whether this line is the first one or a | |
304 | continuation in a sequence of inputs. |
|
304 | continuation in a sequence of inputs. | |
305 | """ |
|
305 | """ | |
306 | # Code run by the user may have modified the readline completer state. |
|
306 | # Code run by the user may have modified the readline completer state. | |
307 | # We must ensure that our completer is back in place. |
|
307 | # We must ensure that our completer is back in place. | |
308 |
|
308 | |||
309 | if self.has_readline: |
|
309 | if self.has_readline: | |
310 | self.set_readline_completer() |
|
310 | self.set_readline_completer() | |
311 |
|
311 | |||
312 | try: |
|
312 | try: | |
313 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
313 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
314 | except ValueError: |
|
314 | except ValueError: | |
315 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
315 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
316 | " or sys.stdout.close()!\nExiting IPython!") |
|
316 | " or sys.stdout.close()!\nExiting IPython!") | |
317 | self.ask_exit() |
|
317 | self.ask_exit() | |
318 | return "" |
|
318 | return "" | |
319 |
|
319 | |||
320 | # Try to be reasonably smart about not re-indenting pasted input more |
|
320 | # Try to be reasonably smart about not re-indenting pasted input more | |
321 | # than necessary. We do this by trimming out the auto-indent initial |
|
321 | # than necessary. We do this by trimming out the auto-indent initial | |
322 | # spaces, if the user's actual input started itself with whitespace. |
|
322 | # spaces, if the user's actual input started itself with whitespace. | |
323 | if self.autoindent: |
|
323 | if self.autoindent: | |
324 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
324 | if num_ini_spaces(line) > self.indent_current_nsp: | |
325 | line = line[self.indent_current_nsp:] |
|
325 | line = line[self.indent_current_nsp:] | |
326 | self.indent_current_nsp = 0 |
|
326 | self.indent_current_nsp = 0 | |
327 |
|
327 | |||
328 | # store the unfiltered input before the user has any chance to modify |
|
328 | # store the unfiltered input before the user has any chance to modify | |
329 | # it. |
|
329 | # it. | |
330 | if line.strip(): |
|
330 | if line.strip(): | |
331 | if continue_prompt: |
|
331 | if continue_prompt: | |
332 | if self.has_readline and self.readline_use: |
|
332 | if self.has_readline and self.readline_use: | |
333 | histlen = self.readline.get_current_history_length() |
|
333 | histlen = self.readline.get_current_history_length() | |
334 | if histlen > 1: |
|
334 | if histlen > 1: | |
335 | newhist = self.input_hist_raw[-1].rstrip() |
|
335 | newhist = self.history_manager.input_hist_raw[-1].rstrip() | |
336 | self.readline.remove_history_item(histlen-1) |
|
336 | self.readline.remove_history_item(histlen-1) | |
337 | self.readline.replace_history_item(histlen-2, |
|
337 | self.readline.replace_history_item(histlen-2, | |
338 | newhist.encode(self.stdin_encoding)) |
|
338 | newhist.encode(self.stdin_encoding)) | |
339 | else: |
|
339 | else: | |
340 | self.input_hist_raw.append('%s\n' % line) |
|
340 | self.history_manager.input_hist_raw.append('%s\n' % line) | |
341 | elif not continue_prompt: |
|
341 | elif not continue_prompt: | |
342 | self.input_hist_raw.append('\n') |
|
342 | self.history_manager.input_hist_raw.append('\n') | |
343 | try: |
|
343 | try: | |
344 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
344 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
345 | except: |
|
345 | except: | |
346 | # blanket except, in case a user-defined prefilter crashes, so it |
|
346 | # blanket except, in case a user-defined prefilter crashes, so it | |
347 | # can't take all of ipython with it. |
|
347 | # can't take all of ipython with it. | |
348 | self.showtraceback() |
|
348 | self.showtraceback() | |
349 | return '' |
|
349 | return '' | |
350 | else: |
|
350 | else: | |
351 | return lineout |
|
351 | return lineout | |
352 |
|
352 | |||
353 |
|
353 | |||
354 | def raw_input(self, prompt=''): |
|
354 | def raw_input(self, prompt=''): | |
355 | """Write a prompt and read a line. |
|
355 | """Write a prompt and read a line. | |
356 |
|
356 | |||
357 | The returned line does not include the trailing newline. |
|
357 | The returned line does not include the trailing newline. | |
358 | When the user enters the EOF key sequence, EOFError is raised. |
|
358 | When the user enters the EOF key sequence, EOFError is raised. | |
359 |
|
359 | |||
360 | Optional inputs: |
|
360 | Optional inputs: | |
361 |
|
361 | |||
362 | - prompt(''): a string to be printed to prompt the user. |
|
362 | - prompt(''): a string to be printed to prompt the user. | |
363 |
|
363 | |||
364 | - continue_prompt(False): whether this line is the first one or a |
|
364 | - continue_prompt(False): whether this line is the first one or a | |
365 | continuation in a sequence of inputs. |
|
365 | continuation in a sequence of inputs. | |
366 | """ |
|
366 | """ | |
367 | # Code run by the user may have modified the readline completer state. |
|
367 | # Code run by the user may have modified the readline completer state. | |
368 | # We must ensure that our completer is back in place. |
|
368 | # We must ensure that our completer is back in place. | |
369 |
|
369 | |||
370 | if self.has_readline: |
|
370 | if self.has_readline: | |
371 | self.set_readline_completer() |
|
371 | self.set_readline_completer() | |
372 |
|
372 | |||
373 | try: |
|
373 | try: | |
374 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
374 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
375 | except ValueError: |
|
375 | except ValueError: | |
376 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
376 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
377 | " or sys.stdout.close()!\nExiting IPython!") |
|
377 | " or sys.stdout.close()!\nExiting IPython!") | |
378 | self.ask_exit() |
|
378 | self.ask_exit() | |
379 | return "" |
|
379 | return "" | |
380 |
|
380 | |||
381 | # Try to be reasonably smart about not re-indenting pasted input more |
|
381 | # Try to be reasonably smart about not re-indenting pasted input more | |
382 | # than necessary. We do this by trimming out the auto-indent initial |
|
382 | # than necessary. We do this by trimming out the auto-indent initial | |
383 | # spaces, if the user's actual input started itself with whitespace. |
|
383 | # spaces, if the user's actual input started itself with whitespace. | |
384 | if self.autoindent: |
|
384 | if self.autoindent: | |
385 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
385 | if num_ini_spaces(line) > self.indent_current_nsp: | |
386 | line = line[self.indent_current_nsp:] |
|
386 | line = line[self.indent_current_nsp:] | |
387 | self.indent_current_nsp = 0 |
|
387 | self.indent_current_nsp = 0 | |
388 |
|
388 | |||
389 | return line |
|
389 | return line | |
390 |
|
390 | |||
391 | #------------------------------------------------------------------------- |
|
391 | #------------------------------------------------------------------------- | |
392 | # Methods to support auto-editing of SyntaxErrors. |
|
392 | # Methods to support auto-editing of SyntaxErrors. | |
393 | #------------------------------------------------------------------------- |
|
393 | #------------------------------------------------------------------------- | |
394 |
|
394 | |||
395 | def edit_syntax_error(self): |
|
395 | def edit_syntax_error(self): | |
396 | """The bottom half of the syntax error handler called in the main loop. |
|
396 | """The bottom half of the syntax error handler called in the main loop. | |
397 |
|
397 | |||
398 | Loop until syntax error is fixed or user cancels. |
|
398 | Loop until syntax error is fixed or user cancels. | |
399 | """ |
|
399 | """ | |
400 |
|
400 | |||
401 | while self.SyntaxTB.last_syntax_error: |
|
401 | while self.SyntaxTB.last_syntax_error: | |
402 | # copy and clear last_syntax_error |
|
402 | # copy and clear last_syntax_error | |
403 | err = self.SyntaxTB.clear_err_state() |
|
403 | err = self.SyntaxTB.clear_err_state() | |
404 | if not self._should_recompile(err): |
|
404 | if not self._should_recompile(err): | |
405 | return |
|
405 | return | |
406 | try: |
|
406 | try: | |
407 | # may set last_syntax_error again if a SyntaxError is raised |
|
407 | # may set last_syntax_error again if a SyntaxError is raised | |
408 | self.safe_execfile(err.filename,self.user_ns) |
|
408 | self.safe_execfile(err.filename,self.user_ns) | |
409 | except: |
|
409 | except: | |
410 | self.showtraceback() |
|
410 | self.showtraceback() | |
411 | else: |
|
411 | else: | |
412 | try: |
|
412 | try: | |
413 | f = file(err.filename) |
|
413 | f = file(err.filename) | |
414 | try: |
|
414 | try: | |
415 | # This should be inside a display_trap block and I |
|
415 | # This should be inside a display_trap block and I | |
416 | # think it is. |
|
416 | # think it is. | |
417 | sys.displayhook(f.read()) |
|
417 | sys.displayhook(f.read()) | |
418 | finally: |
|
418 | finally: | |
419 | f.close() |
|
419 | f.close() | |
420 | except: |
|
420 | except: | |
421 | self.showtraceback() |
|
421 | self.showtraceback() | |
422 |
|
422 | |||
423 | def _should_recompile(self,e): |
|
423 | def _should_recompile(self,e): | |
424 | """Utility routine for edit_syntax_error""" |
|
424 | """Utility routine for edit_syntax_error""" | |
425 |
|
425 | |||
426 | if e.filename in ('<ipython console>','<input>','<string>', |
|
426 | if e.filename in ('<ipython console>','<input>','<string>', | |
427 | '<console>','<BackgroundJob compilation>', |
|
427 | '<console>','<BackgroundJob compilation>', | |
428 | None): |
|
428 | None): | |
429 |
|
429 | |||
430 | return False |
|
430 | return False | |
431 | try: |
|
431 | try: | |
432 | if (self.autoedit_syntax and |
|
432 | if (self.autoedit_syntax and | |
433 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
433 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
434 | '[Y/n] ','y')): |
|
434 | '[Y/n] ','y')): | |
435 | return False |
|
435 | return False | |
436 | except EOFError: |
|
436 | except EOFError: | |
437 | return False |
|
437 | return False | |
438 |
|
438 | |||
439 | def int0(x): |
|
439 | def int0(x): | |
440 | try: |
|
440 | try: | |
441 | return int(x) |
|
441 | return int(x) | |
442 | except TypeError: |
|
442 | except TypeError: | |
443 | return 0 |
|
443 | return 0 | |
444 | # always pass integer line and offset values to editor hook |
|
444 | # always pass integer line and offset values to editor hook | |
445 | try: |
|
445 | try: | |
446 | self.hooks.fix_error_editor(e.filename, |
|
446 | self.hooks.fix_error_editor(e.filename, | |
447 | int0(e.lineno),int0(e.offset),e.msg) |
|
447 | int0(e.lineno),int0(e.offset),e.msg) | |
448 | except TryNext: |
|
448 | except TryNext: | |
449 | warn('Could not open editor') |
|
449 | warn('Could not open editor') | |
450 | return False |
|
450 | return False | |
451 | return True |
|
451 | return True | |
452 |
|
452 | |||
453 | #------------------------------------------------------------------------- |
|
453 | #------------------------------------------------------------------------- | |
454 | # Things related to GUI support and pylab |
|
454 | # Things related to GUI support and pylab | |
455 | #------------------------------------------------------------------------- |
|
455 | #------------------------------------------------------------------------- | |
456 |
|
456 | |||
457 | def enable_pylab(self, gui=None): |
|
457 | def enable_pylab(self, gui=None): | |
458 | """Activate pylab support at runtime. |
|
458 | """Activate pylab support at runtime. | |
459 |
|
459 | |||
460 | This turns on support for matplotlib, preloads into the interactive |
|
460 | This turns on support for matplotlib, preloads into the interactive | |
461 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
461 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
462 | interact with the GUI event loop. The GUI backend to be used can be |
|
462 | interact with the GUI event loop. The GUI backend to be used can be | |
463 | optionally selected with the optional :param:`gui` argument. |
|
463 | optionally selected with the optional :param:`gui` argument. | |
464 |
|
464 | |||
465 | Parameters |
|
465 | Parameters | |
466 | ---------- |
|
466 | ---------- | |
467 | gui : optional, string |
|
467 | gui : optional, string | |
468 |
|
468 | |||
469 | If given, dictates the choice of matplotlib GUI backend to use |
|
469 | If given, dictates the choice of matplotlib GUI backend to use | |
470 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
470 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
471 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
471 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
472 | dictated by the matplotlib build-time options plus the user's |
|
472 | dictated by the matplotlib build-time options plus the user's | |
473 | matplotlibrc configuration file). |
|
473 | matplotlibrc configuration file). | |
474 | """ |
|
474 | """ | |
475 | # We want to prevent the loading of pylab to pollute the user's |
|
475 | # We want to prevent the loading of pylab to pollute the user's | |
476 | # namespace as shown by the %who* magics, so we execute the activation |
|
476 | # namespace as shown by the %who* magics, so we execute the activation | |
477 | # code in an empty namespace, and we update *both* user_ns and |
|
477 | # code in an empty namespace, and we update *both* user_ns and | |
478 | # user_ns_hidden with this information. |
|
478 | # user_ns_hidden with this information. | |
479 | ns = {} |
|
479 | ns = {} | |
480 | gui = pylab_activate(ns, gui) |
|
480 | gui = pylab_activate(ns, gui) | |
481 | self.user_ns.update(ns) |
|
481 | self.user_ns.update(ns) | |
482 | self.user_ns_hidden.update(ns) |
|
482 | self.user_ns_hidden.update(ns) | |
483 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
483 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
484 | # plot updates into account |
|
484 | # plot updates into account | |
485 | enable_gui(gui) |
|
485 | enable_gui(gui) | |
486 | self.magic_run = self._pylab_magic_run |
|
486 | self.magic_run = self._pylab_magic_run | |
487 |
|
487 | |||
488 | #------------------------------------------------------------------------- |
|
488 | #------------------------------------------------------------------------- | |
489 | # Things related to exiting |
|
489 | # Things related to exiting | |
490 | #------------------------------------------------------------------------- |
|
490 | #------------------------------------------------------------------------- | |
491 |
|
491 | |||
492 | def ask_exit(self): |
|
492 | def ask_exit(self): | |
493 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
493 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
494 | self.exit_now = True |
|
494 | self.exit_now = True | |
495 |
|
495 | |||
496 | def exit(self): |
|
496 | def exit(self): | |
497 | """Handle interactive exit. |
|
497 | """Handle interactive exit. | |
498 |
|
498 | |||
499 | This method calls the ask_exit callback.""" |
|
499 | This method calls the ask_exit callback.""" | |
500 | if self.confirm_exit: |
|
500 | if self.confirm_exit: | |
501 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
501 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
502 | self.ask_exit() |
|
502 | self.ask_exit() | |
503 | else: |
|
503 | else: | |
504 | self.ask_exit() |
|
504 | self.ask_exit() | |
505 |
|
505 | |||
506 | #------------------------------------------------------------------------ |
|
506 | #------------------------------------------------------------------------ | |
507 | # Magic overrides |
|
507 | # Magic overrides | |
508 | #------------------------------------------------------------------------ |
|
508 | #------------------------------------------------------------------------ | |
509 | # Once the base class stops inheriting from magic, this code needs to be |
|
509 | # Once the base class stops inheriting from magic, this code needs to be | |
510 | # moved into a separate machinery as well. For now, at least isolate here |
|
510 | # moved into a separate machinery as well. For now, at least isolate here | |
511 | # the magics which this class needs to implement differently from the base |
|
511 | # the magics which this class needs to implement differently from the base | |
512 | # class, or that are unique to it. |
|
512 | # class, or that are unique to it. | |
513 |
|
513 | |||
514 | def magic_autoindent(self, parameter_s = ''): |
|
514 | def magic_autoindent(self, parameter_s = ''): | |
515 | """Toggle autoindent on/off (if available).""" |
|
515 | """Toggle autoindent on/off (if available).""" | |
516 |
|
516 | |||
517 | self.shell.set_autoindent() |
|
517 | self.shell.set_autoindent() | |
518 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
518 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
519 |
|
519 | |||
520 | def magic_cpaste(self, parameter_s=''): |
|
520 | def magic_cpaste(self, parameter_s=''): | |
521 | """Paste & execute a pre-formatted code block from clipboard. |
|
521 | """Paste & execute a pre-formatted code block from clipboard. | |
522 |
|
522 | |||
523 | You must terminate the block with '--' (two minus-signs) alone on the |
|
523 | You must terminate the block with '--' (two minus-signs) alone on the | |
524 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
524 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
525 | is the new sentinel for this operation) |
|
525 | is the new sentinel for this operation) | |
526 |
|
526 | |||
527 | The block is dedented prior to execution to enable execution of method |
|
527 | The block is dedented prior to execution to enable execution of method | |
528 | definitions. '>' and '+' characters at the beginning of a line are |
|
528 | definitions. '>' and '+' characters at the beginning of a line are | |
529 | ignored, to allow pasting directly from e-mails, diff files and |
|
529 | ignored, to allow pasting directly from e-mails, diff files and | |
530 | doctests (the '...' continuation prompt is also stripped). The |
|
530 | doctests (the '...' continuation prompt is also stripped). The | |
531 | executed block is also assigned to variable named 'pasted_block' for |
|
531 | executed block is also assigned to variable named 'pasted_block' for | |
532 | later editing with '%edit pasted_block'. |
|
532 | later editing with '%edit pasted_block'. | |
533 |
|
533 | |||
534 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
534 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
535 | This assigns the pasted block to variable 'foo' as string, without |
|
535 | This assigns the pasted block to variable 'foo' as string, without | |
536 | dedenting or executing it (preceding >>> and + is still stripped) |
|
536 | dedenting or executing it (preceding >>> and + is still stripped) | |
537 |
|
537 | |||
538 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
538 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
539 |
|
539 | |||
540 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
540 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
541 | Just press enter and type -- (and press enter again) and the block |
|
541 | Just press enter and type -- (and press enter again) and the block | |
542 | will be what was just pasted. |
|
542 | will be what was just pasted. | |
543 |
|
543 | |||
544 | IPython statements (magics, shell escapes) are not supported (yet). |
|
544 | IPython statements (magics, shell escapes) are not supported (yet). | |
545 |
|
545 | |||
546 | See also |
|
546 | See also | |
547 | -------- |
|
547 | -------- | |
548 | paste: automatically pull code from clipboard. |
|
548 | paste: automatically pull code from clipboard. | |
549 | """ |
|
549 | """ | |
550 |
|
550 | |||
551 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
551 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |
552 | par = args.strip() |
|
552 | par = args.strip() | |
553 | if opts.has_key('r'): |
|
553 | if opts.has_key('r'): | |
554 | self._rerun_pasted() |
|
554 | self._rerun_pasted() | |
555 | return |
|
555 | return | |
556 |
|
556 | |||
557 | sentinel = opts.get('s','--') |
|
557 | sentinel = opts.get('s','--') | |
558 |
|
558 | |||
559 | block = self._strip_pasted_lines_for_code( |
|
559 | block = self._strip_pasted_lines_for_code( | |
560 | self._get_pasted_lines(sentinel)) |
|
560 | self._get_pasted_lines(sentinel)) | |
561 |
|
561 | |||
562 | self._execute_block(block, par) |
|
562 | self._execute_block(block, par) | |
563 |
|
563 | |||
564 | def magic_paste(self, parameter_s=''): |
|
564 | def magic_paste(self, parameter_s=''): | |
565 | """Paste & execute a pre-formatted code block from clipboard. |
|
565 | """Paste & execute a pre-formatted code block from clipboard. | |
566 |
|
566 | |||
567 | The text is pulled directly from the clipboard without user |
|
567 | The text is pulled directly from the clipboard without user | |
568 | intervention and printed back on the screen before execution (unless |
|
568 | intervention and printed back on the screen before execution (unless | |
569 | the -q flag is given to force quiet mode). |
|
569 | the -q flag is given to force quiet mode). | |
570 |
|
570 | |||
571 | The block is dedented prior to execution to enable execution of method |
|
571 | The block is dedented prior to execution to enable execution of method | |
572 | definitions. '>' and '+' characters at the beginning of a line are |
|
572 | definitions. '>' and '+' characters at the beginning of a line are | |
573 | ignored, to allow pasting directly from e-mails, diff files and |
|
573 | ignored, to allow pasting directly from e-mails, diff files and | |
574 | doctests (the '...' continuation prompt is also stripped). The |
|
574 | doctests (the '...' continuation prompt is also stripped). The | |
575 | executed block is also assigned to variable named 'pasted_block' for |
|
575 | executed block is also assigned to variable named 'pasted_block' for | |
576 | later editing with '%edit pasted_block'. |
|
576 | later editing with '%edit pasted_block'. | |
577 |
|
577 | |||
578 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
578 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
579 | This assigns the pasted block to variable 'foo' as string, without |
|
579 | This assigns the pasted block to variable 'foo' as string, without | |
580 | dedenting or executing it (preceding >>> and + is still stripped) |
|
580 | dedenting or executing it (preceding >>> and + is still stripped) | |
581 |
|
581 | |||
582 | Options |
|
582 | Options | |
583 | ------- |
|
583 | ------- | |
584 |
|
584 | |||
585 | -r: re-executes the block previously entered by cpaste. |
|
585 | -r: re-executes the block previously entered by cpaste. | |
586 |
|
586 | |||
587 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
587 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
588 |
|
588 | |||
589 | IPython statements (magics, shell escapes) are not supported (yet). |
|
589 | IPython statements (magics, shell escapes) are not supported (yet). | |
590 |
|
590 | |||
591 | See also |
|
591 | See also | |
592 | -------- |
|
592 | -------- | |
593 | cpaste: manually paste code into terminal until you mark its end. |
|
593 | cpaste: manually paste code into terminal until you mark its end. | |
594 | """ |
|
594 | """ | |
595 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
595 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |
596 | par = args.strip() |
|
596 | par = args.strip() | |
597 | if opts.has_key('r'): |
|
597 | if opts.has_key('r'): | |
598 | self._rerun_pasted() |
|
598 | self._rerun_pasted() | |
599 | return |
|
599 | return | |
600 |
|
600 | |||
601 | text = self.shell.hooks.clipboard_get() |
|
601 | text = self.shell.hooks.clipboard_get() | |
602 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
602 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |
603 |
|
603 | |||
604 | # By default, echo back to terminal unless quiet mode is requested |
|
604 | # By default, echo back to terminal unless quiet mode is requested | |
605 | if not opts.has_key('q'): |
|
605 | if not opts.has_key('q'): | |
606 | write = self.shell.write |
|
606 | write = self.shell.write | |
607 | write(self.shell.pycolorize(block)) |
|
607 | write(self.shell.pycolorize(block)) | |
608 | if not block.endswith('\n'): |
|
608 | if not block.endswith('\n'): | |
609 | write('\n') |
|
609 | write('\n') | |
610 | write("## -- End pasted text --\n") |
|
610 | write("## -- End pasted text --\n") | |
611 |
|
611 | |||
612 | self._execute_block(block, par) |
|
612 | self._execute_block(block, par) | |
613 |
|
613 | |||
614 |
|
614 | |||
615 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
615 | InteractiveShellABC.register(TerminalInteractiveShell) |
@@ -1,87 +1,87 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ IPython extension: add %clear magic """ |
|
2 | """ IPython extension: add %clear magic """ | |
3 |
|
3 | |||
4 | from IPython.core import ipapi |
|
4 | from IPython.core import ipapi | |
5 | import gc |
|
5 | import gc | |
6 | ip = ipapi.get() |
|
6 | ip = ipapi.get() | |
7 |
|
7 | |||
8 | def clear_f(self,arg): |
|
8 | def clear_f(self,arg): | |
9 | """ Clear various data (e.g. stored history data) |
|
9 | """ Clear various data (e.g. stored history data) | |
10 |
|
10 | |||
11 | %clear in - clear input history |
|
11 | %clear in - clear input history | |
12 | %clear out - clear output history |
|
12 | %clear out - clear output history | |
13 | %clear shadow_compress - Compresses shadow history (to speed up ipython) |
|
13 | %clear shadow_compress - Compresses shadow history (to speed up ipython) | |
14 | %clear shadow_nuke - permanently erase all entries in shadow history |
|
14 | %clear shadow_nuke - permanently erase all entries in shadow history | |
15 | %clear dhist - clear dir history |
|
15 | %clear dhist - clear dir history | |
16 | %clear array - clear only variables that are NumPy arrays |
|
16 | %clear array - clear only variables that are NumPy arrays | |
17 |
|
17 | |||
18 | Examples: |
|
18 | Examples: | |
19 |
|
19 | |||
20 | In [1]: clear in |
|
20 | In [1]: clear in | |
21 | Flushing input history |
|
21 | Flushing input history | |
22 |
|
22 | |||
23 | In [2]: clear shadow_compress |
|
23 | In [2]: clear shadow_compress | |
24 | Compressing shadow history |
|
24 | Compressing shadow history | |
25 |
|
25 | |||
26 | In [3]: clear shadow_nuke |
|
26 | In [3]: clear shadow_nuke | |
27 | Erased all keys from shadow history |
|
27 | Erased all keys from shadow history | |
28 |
|
28 | |||
29 | In [4]: clear dhist |
|
29 | In [4]: clear dhist | |
30 | Clearing directory history |
|
30 | Clearing directory history | |
31 | """ |
|
31 | """ | |
32 |
|
32 | |||
33 | api = self.getapi() |
|
33 | api = self.getapi() | |
34 | user_ns = self.user_ns # local lookup, heavily used |
|
34 | user_ns = self.user_ns # local lookup, heavily used | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | for target in arg.split(): |
|
37 | for target in arg.split(): | |
38 |
|
38 | |||
39 | if target == 'out': |
|
39 | if target == 'out': | |
40 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
40 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
41 | self.outputcache.flush() |
|
41 | self.outputcache.flush() | |
42 |
|
42 | |||
43 | elif target == 'in': |
|
43 | elif target == 'in': | |
44 | print "Flushing input history" |
|
44 | print "Flushing input history" | |
45 | pc = self.outputcache.prompt_count + 1 |
|
45 | pc = self.outputcache.prompt_count + 1 | |
46 | for n in range(1, pc): |
|
46 | for n in range(1, pc): | |
47 | key = '_i'+`n` |
|
47 | key = '_i'+`n` | |
48 | user_ns.pop(key,None) |
|
48 | user_ns.pop(key,None) | |
49 | try: |
|
49 | try: | |
50 | del user_ns[key] |
|
50 | del user_ns[key] | |
51 | except: pass |
|
51 | except: pass | |
52 | # must be done in-place |
|
52 | # must be done in-place | |
53 | self.input_hist[:] = ['\n'] * pc |
|
53 | self.history_manager.input_hist_parsed[:] = ['\n'] * pc | |
54 | self.input_hist_raw[:] = ['\n'] * pc |
|
54 | self.history_manager.input_hist_raw[:] = ['\n'] * pc | |
55 |
|
55 | |||
56 | elif target == 'array': |
|
56 | elif target == 'array': | |
57 | # Support cleaning up numpy arrays |
|
57 | # Support cleaning up numpy arrays | |
58 | try: |
|
58 | try: | |
59 | from numpy import ndarray |
|
59 | from numpy import ndarray | |
60 | # This must be done with items and not iteritems because we're |
|
60 | # This must be done with items and not iteritems because we're | |
61 | # going to modify the dict in-place. |
|
61 | # going to modify the dict in-place. | |
62 | for x,val in user_ns.items(): |
|
62 | for x,val in user_ns.items(): | |
63 | if isinstance(val,ndarray): |
|
63 | if isinstance(val,ndarray): | |
64 | del user_ns[x] |
|
64 | del user_ns[x] | |
65 | except AttributeError: |
|
65 | except AttributeError: | |
66 | print "Clear array only works if Numpy is available." |
|
66 | print "Clear array only works if Numpy is available." | |
67 |
|
67 | |||
68 | elif target == 'shadow_compress': |
|
68 | elif target == 'shadow_compress': | |
69 | print "Compressing shadow history" |
|
69 | print "Compressing shadow history" | |
70 | api.db.hcompress('shadowhist') |
|
70 | api.db.hcompress('shadowhist') | |
71 |
|
71 | |||
72 | elif target == 'shadow_nuke': |
|
72 | elif target == 'shadow_nuke': | |
73 | print "Erased all keys from shadow history " |
|
73 | print "Erased all keys from shadow history " | |
74 | for k in ip.db.keys('shadowhist/*'): |
|
74 | for k in ip.db.keys('shadowhist/*'): | |
75 | del ip.db[k] |
|
75 | del ip.db[k] | |
76 |
|
76 | |||
77 | elif target == 'dhist': |
|
77 | elif target == 'dhist': | |
78 | print "Clearing directory history" |
|
78 | print "Clearing directory history" | |
79 | del user_ns['_dh'][:] |
|
79 | del user_ns['_dh'][:] | |
80 |
|
80 | |||
81 | gc.collect() |
|
81 | gc.collect() | |
82 |
|
82 | |||
83 | # Activate the extension |
|
83 | # Activate the extension | |
84 | ip.define_magic("clear",clear_f) |
|
84 | ip.define_magic("clear",clear_f) | |
85 | import ipy_completers |
|
85 | import ipy_completers | |
86 | ipy_completers.quick_completer( |
|
86 | ipy_completers.quick_completer( | |
87 | '%clear','in out shadow_nuke shadow_compress dhist') |
|
87 | '%clear','in out shadow_nuke shadow_compress dhist') |
@@ -1,312 +1,312 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | %jot magic for lightweight persistence. |
|
3 | %jot magic for lightweight persistence. | |
4 |
|
4 | |||
5 | Stores variables in Struct with some notes in PicleShare database |
|
5 | Stores variables in Struct with some notes in PicleShare database | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | from datetime import datetime |
|
10 | from datetime import datetime | |
11 | from IPython.core import ipapi |
|
11 | from IPython.core import ipapi | |
12 | ip = ipapi.get() |
|
12 | ip = ipapi.get() | |
13 |
|
13 | |||
14 | import pickleshare |
|
14 | import pickleshare | |
15 |
|
15 | |||
16 | import inspect,pickle,os,sys,textwrap |
|
16 | import inspect,pickle,os,sys,textwrap | |
17 | from IPython.core.fakemodule import FakeModule |
|
17 | from IPython.core.fakemodule import FakeModule | |
18 | from IPython.utils.ipstruct import Struct |
|
18 | from IPython.utils.ipstruct import Struct | |
19 | from IPython.utils.warn import error |
|
19 | from IPython.utils.warn import error | |
20 |
|
20 | |||
21 |
|
21 | |||
22 | def refresh_variables(ip, key=None): |
|
22 | def refresh_variables(ip, key=None): | |
23 | db = ip.db |
|
23 | db = ip.db | |
24 | if key is None: |
|
24 | if key is None: | |
25 | keys = db.keys('jot/*') |
|
25 | keys = db.keys('jot/*') | |
26 | else: |
|
26 | else: | |
27 | keys = db.keys('jot/'+key) |
|
27 | keys = db.keys('jot/'+key) | |
28 | for key in keys: |
|
28 | for key in keys: | |
29 | # strip autorestore |
|
29 | # strip autorestore | |
30 | justkey = os.path.basename(key) |
|
30 | justkey = os.path.basename(key) | |
31 | print "Restoring from", justkey, "..." |
|
31 | print "Restoring from", justkey, "..." | |
32 | try: |
|
32 | try: | |
33 | obj = db[key] |
|
33 | obj = db[key] | |
34 | except KeyError: |
|
34 | except KeyError: | |
35 | print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey |
|
35 | print "Unable to restore variable '%s', ignoring (use %%jot -d to forget!)" % justkey | |
36 | print "The error was:",sys.exc_info()[0] |
|
36 | print "The error was:",sys.exc_info()[0] | |
37 | else: |
|
37 | else: | |
38 | #print "restored",justkey,"=",obj #dbg |
|
38 | #print "restored",justkey,"=",obj #dbg | |
39 | try: |
|
39 | try: | |
40 | origname = obj.name |
|
40 | origname = obj.name | |
41 | except: |
|
41 | except: | |
42 | ip.user_ns[justkey] = obj |
|
42 | ip.user_ns[justkey] = obj | |
43 | print "Restored", justkey |
|
43 | print "Restored", justkey | |
44 | else: |
|
44 | else: | |
45 | ip.user_ns[origname] = obj['val'] |
|
45 | ip.user_ns[origname] = obj['val'] | |
46 | print "Restored", origname |
|
46 | print "Restored", origname | |
47 |
|
47 | |||
48 | def read_variables(ip, key=None): |
|
48 | def read_variables(ip, key=None): | |
49 | db = ip.db |
|
49 | db = ip.db | |
50 | if key is None: |
|
50 | if key is None: | |
51 | return None |
|
51 | return None | |
52 | else: |
|
52 | else: | |
53 | keys = db.keys('jot/'+key) |
|
53 | keys = db.keys('jot/'+key) | |
54 | for key in keys: |
|
54 | for key in keys: | |
55 | # strip autorestore |
|
55 | # strip autorestore | |
56 | justkey = os.path.basename(key) |
|
56 | justkey = os.path.basename(key) | |
57 | print "restoring from ", justkey |
|
57 | print "restoring from ", justkey | |
58 | try: |
|
58 | try: | |
59 | obj = db[key] |
|
59 | obj = db[key] | |
60 | except KeyError: |
|
60 | except KeyError: | |
61 | print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey |
|
61 | print "Unable to read variable '%s', ignoring (use %%jot -d to forget!)" % justkey | |
62 | print "The error was:",sys.exc_info()[0] |
|
62 | print "The error was:",sys.exc_info()[0] | |
63 | else: |
|
63 | else: | |
64 | return obj |
|
64 | return obj | |
65 |
|
65 | |||
66 |
|
66 | |||
67 | def detail_variables(ip, key=None): |
|
67 | def detail_variables(ip, key=None): | |
68 | db, get = ip.db, ip.db.get |
|
68 | db, get = ip.db, ip.db.get | |
69 |
|
69 | |||
70 | if key is None: |
|
70 | if key is None: | |
71 | keys = db.keys('jot/*') |
|
71 | keys = db.keys('jot/*') | |
72 | else: |
|
72 | else: | |
73 | keys = db.keys('jot/'+key) |
|
73 | keys = db.keys('jot/'+key) | |
74 | if keys: |
|
74 | if keys: | |
75 | size = max(map(len,keys)) |
|
75 | size = max(map(len,keys)) | |
76 | else: |
|
76 | else: | |
77 | size = 0 |
|
77 | size = 0 | |
78 |
|
78 | |||
79 | fmthead = '%-'+str(size)+'s [%s]' |
|
79 | fmthead = '%-'+str(size)+'s [%s]' | |
80 | fmtbody = 'Comment:\n %s' |
|
80 | fmtbody = 'Comment:\n %s' | |
81 | fmtdata = 'Data:\n %s, %s' |
|
81 | fmtdata = 'Data:\n %s, %s' | |
82 | for key in keys: |
|
82 | for key in keys: | |
83 | v = get(key,'<unavailable>') |
|
83 | v = get(key,'<unavailable>') | |
84 | justkey = os.path.basename(key) |
|
84 | justkey = os.path.basename(key) | |
85 | try: |
|
85 | try: | |
86 | print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>'))) |
|
86 | print fmthead % (justkey, datetime.ctime(v.get('time','<unavailable>'))) | |
87 | print fmtbody % (v.get('comment','<unavailable>')) |
|
87 | print fmtbody % (v.get('comment','<unavailable>')) | |
88 | d = v.get('val','unavailable') |
|
88 | d = v.get('val','unavailable') | |
89 | print fmtdata % (repr(type(d)), '') |
|
89 | print fmtdata % (repr(type(d)), '') | |
90 | print repr(d)[0:200] |
|
90 | print repr(d)[0:200] | |
91 |
|
91 | |||
92 |
|
92 | |||
93 | except AttributeError: |
|
93 | except AttributeError: | |
94 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) |
|
94 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) | |
95 |
|
95 | |||
96 |
|
96 | |||
97 | def intm(n): |
|
97 | def intm(n): | |
98 | try: |
|
98 | try: | |
99 | return int(n) |
|
99 | return int(n) | |
100 | except: |
|
100 | except: | |
101 | return 0 |
|
101 | return 0 | |
102 |
|
102 | |||
103 | def jot_obj(self, obj, name, comment=''): |
|
103 | def jot_obj(self, obj, name, comment=''): | |
104 | """ |
|
104 | """ | |
105 | write obj data to the note database, with whatever that should be noted. |
|
105 | write obj data to the note database, with whatever that should be noted. | |
106 | """ |
|
106 | """ | |
107 | had = self.db.keys('jot/'+name+'*') |
|
107 | had = self.db.keys('jot/'+name+'*') | |
108 | # if it the same name but a later version, we stupidly add a number to the |
|
108 | # if it the same name but a later version, we stupidly add a number to the | |
109 | # so the name doesn't collide. Any better idea? |
|
109 | # so the name doesn't collide. Any better idea? | |
110 | suffix = '' |
|
110 | suffix = '' | |
111 | if len(had)>0: |
|
111 | if len(had)>0: | |
112 | pre = os.path.commonprefix(had) |
|
112 | pre = os.path.commonprefix(had) | |
113 | suf = [n.split(pre)[1] for n in had] |
|
113 | suf = [n.split(pre)[1] for n in had] | |
114 | versions = map(intm, suf) |
|
114 | versions = map(intm, suf) | |
115 | suffix = str(max(versions)+1) |
|
115 | suffix = str(max(versions)+1) | |
116 |
|
116 | |||
117 | uname = 'jot/'+name+suffix |
|
117 | uname = 'jot/'+name+suffix | |
118 |
|
118 | |||
119 | # which one works better? |
|
119 | # which one works better? | |
120 | #all = ip.shadowhist.all() |
|
120 | #all = ip.shadowhist.all() | |
121 | all = ip.shell.input_hist |
|
121 | all = ip.shell.history_manager.input_hist_parsed | |
122 |
|
122 | |||
123 | # We may actually want to make snapshot of files that are run-ned. |
|
123 | # We may actually want to make snapshot of files that are run-ned. | |
124 |
|
124 | |||
125 | # get the comment |
|
125 | # get the comment | |
126 | try: |
|
126 | try: | |
127 | comment = ip.magic_edit('-x').strip() |
|
127 | comment = ip.magic_edit('-x').strip() | |
128 | except: |
|
128 | except: | |
129 | print "No comment is recorded." |
|
129 | print "No comment is recorded." | |
130 | comment = '' |
|
130 | comment = '' | |
131 |
|
131 | |||
132 | self.db[uname] = Struct({'val':obj, |
|
132 | self.db[uname] = Struct({'val':obj, | |
133 | 'time' : datetime.now(), |
|
133 | 'time' : datetime.now(), | |
134 | 'hist' : all, |
|
134 | 'hist' : all, | |
135 | 'name' : name, |
|
135 | 'name' : name, | |
136 | 'comment' : comment,}) |
|
136 | 'comment' : comment,}) | |
137 |
|
137 | |||
138 | print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__) |
|
138 | print "Jotted down notes for '%s' (%s)" % (uname, obj.__class__.__name__) | |
139 |
|
139 | |||
140 |
|
140 | |||
141 |
|
141 | |||
142 | def magic_jot(self, parameter_s=''): |
|
142 | def magic_jot(self, parameter_s=''): | |
143 | """Lightweight persistence for python variables. |
|
143 | """Lightweight persistence for python variables. | |
144 |
|
144 | |||
145 | Example: |
|
145 | Example: | |
146 |
|
146 | |||
147 | ville@badger[~]|1> A = ['hello',10,'world']\\ |
|
147 | ville@badger[~]|1> A = ['hello',10,'world']\\ | |
148 | ville@badger[~]|2> %jot A\\ |
|
148 | ville@badger[~]|2> %jot A\\ | |
149 | ville@badger[~]|3> Exit |
|
149 | ville@badger[~]|3> Exit | |
150 |
|
150 | |||
151 | (IPython session is closed and started again...) |
|
151 | (IPython session is closed and started again...) | |
152 |
|
152 | |||
153 | ville@badger:~$ ipython -p pysh\\ |
|
153 | ville@badger:~$ ipython -p pysh\\ | |
154 | ville@badger[~]|1> print A |
|
154 | ville@badger[~]|1> print A | |
155 |
|
155 | |||
156 | ['hello', 10, 'world'] |
|
156 | ['hello', 10, 'world'] | |
157 |
|
157 | |||
158 | Usage: |
|
158 | Usage: | |
159 |
|
159 | |||
160 | %jot - Show list of all variables and their current values\\ |
|
160 | %jot - Show list of all variables and their current values\\ | |
161 | %jot -l - Show list of all variables and their current values in detail\\ |
|
161 | %jot -l - Show list of all variables and their current values in detail\\ | |
162 | %jot -l <var> - Show one variable and its current values in detail\\ |
|
162 | %jot -l <var> - Show one variable and its current values in detail\\ | |
163 | %jot <var> - Store the *current* value of the variable to disk\\ |
|
163 | %jot <var> - Store the *current* value of the variable to disk\\ | |
164 | %jot -d <var> - Remove the variable and its value from storage\\ |
|
164 | %jot -d <var> - Remove the variable and its value from storage\\ | |
165 | %jot -z - Remove all variables from storage (disabled)\\ |
|
165 | %jot -z - Remove all variables from storage (disabled)\\ | |
166 | %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\ |
|
166 | %jot -r <var> - Refresh/Load variable from jot (delete current vals)\\ | |
167 | %jot foo >a.txt - Store value of foo to new file a.txt\\ |
|
167 | %jot foo >a.txt - Store value of foo to new file a.txt\\ | |
168 | %jot foo >>a.txt - Append value of foo to file a.txt\\ |
|
168 | %jot foo >>a.txt - Append value of foo to file a.txt\\ | |
169 |
|
169 | |||
170 | It should be noted that if you change the value of a variable, you |
|
170 | It should be noted that if you change the value of a variable, you | |
171 | need to %note it again if you want to persist the new value. |
|
171 | need to %note it again if you want to persist the new value. | |
172 |
|
172 | |||
173 | Note also that the variables will need to be pickleable; most basic |
|
173 | Note also that the variables will need to be pickleable; most basic | |
174 | python types can be safely %stored. |
|
174 | python types can be safely %stored. | |
175 |
|
175 | |||
176 | """ |
|
176 | """ | |
177 |
|
177 | |||
178 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') |
|
178 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') | |
179 | args = argsl.split(None,1) |
|
179 | args = argsl.split(None,1) | |
180 | ip = self.getapi() |
|
180 | ip = self.getapi() | |
181 | db = ip.db |
|
181 | db = ip.db | |
182 | # delete |
|
182 | # delete | |
183 | if opts.has_key('d'): |
|
183 | if opts.has_key('d'): | |
184 | try: |
|
184 | try: | |
185 | todel = args[0] |
|
185 | todel = args[0] | |
186 | except IndexError: |
|
186 | except IndexError: | |
187 | error('You must provide the variable to forget') |
|
187 | error('You must provide the variable to forget') | |
188 | else: |
|
188 | else: | |
189 | try: |
|
189 | try: | |
190 | del db['jot/' + todel] |
|
190 | del db['jot/' + todel] | |
191 | except: |
|
191 | except: | |
192 | error("Can't delete variable '%s'" % todel) |
|
192 | error("Can't delete variable '%s'" % todel) | |
193 | # reset the whole database |
|
193 | # reset the whole database | |
194 | elif opts.has_key('z'): |
|
194 | elif opts.has_key('z'): | |
195 | print "reseting the whole database has been disabled." |
|
195 | print "reseting the whole database has been disabled." | |
196 | #for k in db.keys('autorestore/*'): |
|
196 | #for k in db.keys('autorestore/*'): | |
197 | # del db[k] |
|
197 | # del db[k] | |
198 |
|
198 | |||
199 | elif opts.has_key('r'): |
|
199 | elif opts.has_key('r'): | |
200 | try: |
|
200 | try: | |
201 | toret = args[0] |
|
201 | toret = args[0] | |
202 | except: |
|
202 | except: | |
203 | print "restoring all the variables jotted down..." |
|
203 | print "restoring all the variables jotted down..." | |
204 | refresh_variables(ip) |
|
204 | refresh_variables(ip) | |
205 | else: |
|
205 | else: | |
206 | refresh_variables(ip, toret) |
|
206 | refresh_variables(ip, toret) | |
207 |
|
207 | |||
208 | elif opts.has_key('l'): |
|
208 | elif opts.has_key('l'): | |
209 | try: |
|
209 | try: | |
210 | tolist = args[0] |
|
210 | tolist = args[0] | |
211 | except: |
|
211 | except: | |
212 | print "List details for all the items." |
|
212 | print "List details for all the items." | |
213 | detail_variables(ip) |
|
213 | detail_variables(ip) | |
214 | else: |
|
214 | else: | |
215 | print "Details for", tolist, ":" |
|
215 | print "Details for", tolist, ":" | |
216 | detail_variables(ip, tolist) |
|
216 | detail_variables(ip, tolist) | |
217 |
|
217 | |||
218 | # run without arguments -> list noted variables & notes |
|
218 | # run without arguments -> list noted variables & notes | |
219 | elif not args: |
|
219 | elif not args: | |
220 | vars = self.db.keys('jot/*') |
|
220 | vars = self.db.keys('jot/*') | |
221 | vars.sort() |
|
221 | vars.sort() | |
222 | if vars: |
|
222 | if vars: | |
223 | size = max(map(len,vars)) - 4 |
|
223 | size = max(map(len,vars)) - 4 | |
224 | else: |
|
224 | else: | |
225 | size = 0 |
|
225 | size = 0 | |
226 |
|
226 | |||
227 | print 'Variables and their in-db values:' |
|
227 | print 'Variables and their in-db values:' | |
228 | fmt = '%-'+str(size)+'s [%s] -> %s' |
|
228 | fmt = '%-'+str(size)+'s [%s] -> %s' | |
229 | get = db.get |
|
229 | get = db.get | |
230 | for var in vars: |
|
230 | for var in vars: | |
231 | justkey = os.path.basename(var) |
|
231 | justkey = os.path.basename(var) | |
232 | v = get(var,'<unavailable>') |
|
232 | v = get(var,'<unavailable>') | |
233 | try: |
|
233 | try: | |
234 | print fmt % (justkey,\ |
|
234 | print fmt % (justkey,\ | |
235 | datetime.ctime(v.get('time','<unavailable>')),\ |
|
235 | datetime.ctime(v.get('time','<unavailable>')),\ | |
236 | v.get('comment','<unavailable>')[:70].replace('\n',' '),) |
|
236 | v.get('comment','<unavailable>')[:70].replace('\n',' '),) | |
237 | except AttributeError: |
|
237 | except AttributeError: | |
238 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) |
|
238 | print fmt % (justkey, '<unavailable>', '<unavailable>', repr(v)[:50]) | |
239 |
|
239 | |||
240 |
|
240 | |||
241 | # default action - store the variable |
|
241 | # default action - store the variable | |
242 | else: |
|
242 | else: | |
243 | # %store foo >file.txt or >>file.txt |
|
243 | # %store foo >file.txt or >>file.txt | |
244 | if len(args) > 1 and args[1].startswith('>'): |
|
244 | if len(args) > 1 and args[1].startswith('>'): | |
245 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) |
|
245 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) | |
246 | if args[1].startswith('>>'): |
|
246 | if args[1].startswith('>>'): | |
247 | fil = open(fnam,'a') |
|
247 | fil = open(fnam,'a') | |
248 | else: |
|
248 | else: | |
249 | fil = open(fnam,'w') |
|
249 | fil = open(fnam,'w') | |
250 | obj = ip.ev(args[0]) |
|
250 | obj = ip.ev(args[0]) | |
251 | print "Writing '%s' (%s) to file '%s'." % (args[0], |
|
251 | print "Writing '%s' (%s) to file '%s'." % (args[0], | |
252 | obj.__class__.__name__, fnam) |
|
252 | obj.__class__.__name__, fnam) | |
253 |
|
253 | |||
254 |
|
254 | |||
255 | if not isinstance (obj,basestring): |
|
255 | if not isinstance (obj,basestring): | |
256 | from pprint import pprint |
|
256 | from pprint import pprint | |
257 | pprint(obj,fil) |
|
257 | pprint(obj,fil) | |
258 | else: |
|
258 | else: | |
259 | fil.write(obj) |
|
259 | fil.write(obj) | |
260 | if not obj.endswith('\n'): |
|
260 | if not obj.endswith('\n'): | |
261 | fil.write('\n') |
|
261 | fil.write('\n') | |
262 |
|
262 | |||
263 | fil.close() |
|
263 | fil.close() | |
264 | return |
|
264 | return | |
265 |
|
265 | |||
266 | # %note foo |
|
266 | # %note foo | |
267 | try: |
|
267 | try: | |
268 | obj = ip.user_ns[args[0]] |
|
268 | obj = ip.user_ns[args[0]] | |
269 | except KeyError: |
|
269 | except KeyError: | |
270 | # this should not be alias, for aliases, use %store |
|
270 | # this should not be alias, for aliases, use %store | |
271 |
|
271 | |||
272 | print "Error: %s doesn't exist." % args[0] |
|
272 | print "Error: %s doesn't exist." % args[0] | |
273 |
|
273 | |||
274 | print "Use %note -r <var> to retrieve variables. This should not be used " +\ |
|
274 | print "Use %note -r <var> to retrieve variables. This should not be used " +\ | |
275 | "to store alias, for saving aliases, use %store" |
|
275 | "to store alias, for saving aliases, use %store" | |
276 | return |
|
276 | return | |
277 | else: |
|
277 | else: | |
278 | if isinstance(inspect.getmodule(obj), FakeModule): |
|
278 | if isinstance(inspect.getmodule(obj), FakeModule): | |
279 | print textwrap.dedent("""\ |
|
279 | print textwrap.dedent("""\ | |
280 | Warning:%s is %s |
|
280 | Warning:%s is %s | |
281 | Proper storage of interactively declared classes (or instances |
|
281 | Proper storage of interactively declared classes (or instances | |
282 | of those classes) is not possible! Only instances |
|
282 | of those classes) is not possible! Only instances | |
283 | of classes in real modules on file system can be %%store'd. |
|
283 | of classes in real modules on file system can be %%store'd. | |
284 | """ % (args[0], obj) ) |
|
284 | """ % (args[0], obj) ) | |
285 | return |
|
285 | return | |
286 | #pickled = pickle.dumps(obj) |
|
286 | #pickled = pickle.dumps(obj) | |
287 | #self.db[ 'jot/' + args[0] ] = obj |
|
287 | #self.db[ 'jot/' + args[0] ] = obj | |
288 | jot_obj(self, obj, args[0]) |
|
288 | jot_obj(self, obj, args[0]) | |
289 |
|
289 | |||
290 |
|
290 | |||
291 | def magic_read(self, parameter_s=''): |
|
291 | def magic_read(self, parameter_s=''): | |
292 | """ |
|
292 | """ | |
293 | %read <var> - Load variable from data that is jotted down.\\ |
|
293 | %read <var> - Load variable from data that is jotted down.\\ | |
294 |
|
294 | |||
295 | """ |
|
295 | """ | |
296 |
|
296 | |||
297 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') |
|
297 | opts,argsl = self.parse_options(parameter_s,'drzl',mode='string') | |
298 | args = argsl.split(None,1) |
|
298 | args = argsl.split(None,1) | |
299 | ip = self.getapi() |
|
299 | ip = self.getapi() | |
300 | db = ip.db |
|
300 | db = ip.db | |
301 | #if opts.has_key('r'): |
|
301 | #if opts.has_key('r'): | |
302 | try: |
|
302 | try: | |
303 | toret = args[0] |
|
303 | toret = args[0] | |
304 | except: |
|
304 | except: | |
305 | print "which record do you want to read out?" |
|
305 | print "which record do you want to read out?" | |
306 | return |
|
306 | return | |
307 | else: |
|
307 | else: | |
308 | return read_variables(ip, toret) |
|
308 | return read_variables(ip, toret) | |
309 |
|
309 | |||
310 |
|
310 | |||
311 | ip.define_magic('jot',magic_jot) |
|
311 | ip.define_magic('jot',magic_jot) | |
312 | ip.define_magic('read',magic_read) |
|
312 | ip.define_magic('read',magic_read) |
General Comments 0
You need to be logged in to leave comments.
Login now