Show More
@@ -1,128 +1,128 b'' | |||||
1 | """Implementation of magic functions that control various automatic behaviors. |
|
1 | """Implementation of magic functions that control various automatic behaviors. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Our own packages |
|
15 | # Our own packages | |
16 | from IPython.core.magic import Bunch, Magics, magics_class, line_magic |
|
16 | from IPython.core.magic import Bunch, Magics, magics_class, line_magic | |
17 | from IPython.testing.skipdoctest import skip_doctest |
|
17 | from IPython.testing.skipdoctest import skip_doctest | |
18 | from IPython.utils.warn import error |
|
18 | from IPython.utils.warn import error | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Magic implementation classes |
|
21 | # Magic implementation classes | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | @magics_class |
|
24 | @magics_class | |
25 | class AutoMagics(Magics): |
|
25 | class AutoMagics(Magics): | |
26 | """Magics that control various autoX behaviors.""" |
|
26 | """Magics that control various autoX behaviors.""" | |
27 |
|
27 | |||
28 | def __init__(self, shell): |
|
28 | def __init__(self, shell): | |
29 | super(AutoMagics, self).__init__(shell) |
|
29 | super(AutoMagics, self).__init__(shell) | |
30 | # namespace for holding state we may need |
|
30 | # namespace for holding state we may need | |
31 | self._magic_state = Bunch() |
|
31 | self._magic_state = Bunch() | |
32 |
|
32 | |||
33 | @line_magic |
|
33 | @line_magic | |
34 | def automagic(self, parameter_s=''): |
|
34 | def automagic(self, parameter_s=''): | |
35 | """Make magic functions callable without having to type the initial %. |
|
35 | """Make magic functions callable without having to type the initial %. | |
36 |
|
36 | |||
37 | Without argumentsl toggles on/off (when off, you must call it as |
|
37 | Without argumentsl toggles on/off (when off, you must call it as | |
38 | %automagic, of course). With arguments it sets the value, and you can |
|
38 | %automagic, of course). With arguments it sets the value, and you can | |
39 | use any of (case insensitive): |
|
39 | use any of (case insensitive): | |
40 |
|
40 | |||
41 | - on, 1, True: to activate |
|
41 | - on, 1, True: to activate | |
42 |
|
42 | |||
43 | - off, 0, False: to deactivate. |
|
43 | - off, 0, False: to deactivate. | |
44 |
|
44 | |||
45 | Note that magic functions have lowest priority, so if there's a |
|
45 | Note that magic functions have lowest priority, so if there's a | |
46 | variable whose name collides with that of a magic fn, automagic won't |
|
46 | variable whose name collides with that of a magic fn, automagic won't | |
47 | work for that function (you get the variable instead). However, if you |
|
47 | work for that function (you get the variable instead). However, if you | |
48 | delete the variable (del var), the previously shadowed magic function |
|
48 | delete the variable (del var), the previously shadowed magic function | |
49 | becomes visible to automagic again.""" |
|
49 | becomes visible to automagic again.""" | |
50 |
|
50 | |||
51 | arg = parameter_s.lower() |
|
51 | arg = parameter_s.lower() | |
52 | mman = self.shell.magics_manager |
|
52 | mman = self.shell.magics_manager | |
53 | if arg in ('on', '1', 'true'): |
|
53 | if arg in ('on', '1', 'true'): | |
54 | val = True |
|
54 | val = True | |
55 | elif arg in ('off', '0', 'false'): |
|
55 | elif arg in ('off', '0', 'false'): | |
56 | val = False |
|
56 | val = False | |
57 | else: |
|
57 | else: | |
58 | val = not mman.auto_magic |
|
58 | val = not mman.auto_magic | |
59 | mman.auto_magic = val |
|
59 | mman.auto_magic = val | |
60 | print '\n' + self.shell.magics_manager.auto_status() |
|
60 | print '\n' + self.shell.magics_manager.auto_status() | |
61 |
|
61 | |||
62 | @skip_doctest |
|
62 | @skip_doctest | |
63 | @line_magic |
|
63 | @line_magic | |
64 | def autocall(self, parameter_s=''): |
|
64 | def autocall(self, parameter_s=''): | |
65 | """Make functions callable without having to type parentheses. |
|
65 | """Make functions callable without having to type parentheses. | |
66 |
|
66 | |||
67 | Usage: |
|
67 | Usage: | |
68 |
|
68 | |||
69 | %autocall [mode] |
|
69 | %autocall [mode] | |
70 |
|
70 | |||
71 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
71 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
72 | value is toggled on and off (remembering the previous state). |
|
72 | value is toggled on and off (remembering the previous state). | |
73 |
|
73 | |||
74 | In more detail, these values mean: |
|
74 | In more detail, these values mean: | |
75 |
|
75 | |||
76 | 0 -> fully disabled |
|
76 | 0 -> fully disabled | |
77 |
|
77 | |||
78 | 1 -> active, but do not apply if there are no arguments on the line. |
|
78 | 1 -> active, but do not apply if there are no arguments on the line. | |
79 |
|
79 | |||
80 | In this mode, you get:: |
|
80 | In this mode, you get:: | |
81 |
|
81 | |||
82 | In [1]: callable |
|
82 | In [1]: callable | |
83 | Out[1]: <built-in function callable> |
|
83 | Out[1]: <built-in function callable> | |
84 |
|
84 | |||
85 | In [2]: callable 'hello' |
|
85 | In [2]: callable 'hello' | |
86 | ------> callable('hello') |
|
86 | ------> callable('hello') | |
87 | Out[2]: False |
|
87 | Out[2]: False | |
88 |
|
88 | |||
89 | 2 -> Active always. Even if no arguments are present, the callable |
|
89 | 2 -> Active always. Even if no arguments are present, the callable | |
90 | object is called:: |
|
90 | object is called:: | |
91 |
|
91 | |||
92 | In [2]: float |
|
92 | In [2]: float | |
93 | ------> float() |
|
93 | ------> float() | |
94 | Out[2]: 0.0 |
|
94 | Out[2]: 0.0 | |
95 |
|
95 | |||
96 | Note that even with autocall off, you can still use '/' at the start of |
|
96 | Note that even with autocall off, you can still use '/' at the start of | |
97 | a line to treat the first argument on the command line as a function |
|
97 | a line to treat the first argument on the command line as a function | |
98 | and add parentheses to it:: |
|
98 | and add parentheses to it:: | |
99 |
|
99 | |||
100 | In [8]: /str 43 |
|
100 | In [8]: /str 43 | |
101 | ------> str(43) |
|
101 | ------> str(43) | |
102 | Out[8]: '43' |
|
102 | Out[8]: '43' | |
103 |
|
103 | |||
104 | # all-random (note for auto-testing) |
|
104 | # all-random (note for auto-testing) | |
105 | """ |
|
105 | """ | |
106 |
|
106 | |||
107 | if parameter_s: |
|
107 | if parameter_s: | |
108 | arg = int(parameter_s) |
|
108 | arg = int(parameter_s) | |
109 | else: |
|
109 | else: | |
110 | arg = 'toggle' |
|
110 | arg = 'toggle' | |
111 |
|
111 | |||
112 | if not arg in (0, 1, 2,'toggle'): |
|
112 | if not arg in (0, 1, 2, 'toggle'): | |
113 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
113 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
114 | return |
|
114 | return | |
115 |
|
115 | |||
116 | if arg in (0, 1, 2): |
|
116 | if arg in (0, 1, 2): | |
117 | self.shell.autocall = arg |
|
117 | self.shell.autocall = arg | |
118 | else: # toggle |
|
118 | else: # toggle | |
119 | if self.shell.autocall: |
|
119 | if self.shell.autocall: | |
120 | self._magic_state.autocall_save = self.shell.autocall |
|
120 | self._magic_state.autocall_save = self.shell.autocall | |
121 | self.shell.autocall = 0 |
|
121 | self.shell.autocall = 0 | |
122 | else: |
|
122 | else: | |
123 | try: |
|
123 | try: | |
124 | self.shell.autocall = self._magic_state.autocall_save |
|
124 | self.shell.autocall = self._magic_state.autocall_save | |
125 | except AttributeError: |
|
125 | except AttributeError: | |
126 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
126 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
127 |
|
127 | |||
128 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
128 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
@@ -1,513 +1,513 b'' | |||||
1 | """Implementation of basic magic functions. |
|
1 | """Implementation of basic magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | from __future__ import print_function |
|
14 | from __future__ import print_function | |
15 |
|
15 | |||
16 | # Stdlib |
|
16 | # Stdlib | |
17 | import io |
|
17 | import io | |
18 | import sys |
|
18 | import sys | |
19 | from pprint import pformat |
|
19 | from pprint import pformat | |
20 |
|
20 | |||
21 | # Our own packages |
|
21 | # Our own packages | |
22 | from IPython.core.error import UsageError |
|
22 | from IPython.core.error import UsageError | |
23 | from IPython.core.magic import Magics, magics_class, line_magic |
|
23 | from IPython.core.magic import Magics, magics_class, line_magic | |
24 | from IPython.core.prefilter import ESC_MAGIC |
|
24 | from IPython.core.prefilter import ESC_MAGIC | |
25 | from IPython.utils.text import format_screen |
|
25 | from IPython.utils.text import format_screen | |
26 | from IPython.core import magic_arguments, page |
|
26 | from IPython.core import magic_arguments, page | |
27 | from IPython.testing.skipdoctest import skip_doctest |
|
27 | from IPython.testing.skipdoctest import skip_doctest | |
28 | from IPython.utils.ipstruct import Struct |
|
28 | from IPython.utils.ipstruct import Struct | |
29 | from IPython.utils.path import unquote_filename |
|
29 | from IPython.utils.path import unquote_filename | |
30 | from IPython.utils.warn import warn, error |
|
30 | from IPython.utils.warn import warn, error | |
31 |
|
31 | |||
32 | #----------------------------------------------------------------------------- |
|
32 | #----------------------------------------------------------------------------- | |
33 | # Magics class implementation |
|
33 | # Magics class implementation | |
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 |
|
35 | |||
36 | @magics_class |
|
36 | @magics_class | |
37 | class BasicMagics(Magics): |
|
37 | class BasicMagics(Magics): | |
38 | """Magics that provide central IPython functionality. |
|
38 | """Magics that provide central IPython functionality. | |
39 |
|
39 | |||
40 | These are various magics that don't fit into specific categories but that |
|
40 | These are various magics that don't fit into specific categories but that | |
41 | are all part of the base 'IPython experience'.""" |
|
41 | are all part of the base 'IPython experience'.""" | |
42 |
|
42 | |||
43 | def _lsmagic(self): |
|
43 | def _lsmagic(self): | |
44 | mesc = ESC_MAGIC |
|
44 | mesc = ESC_MAGIC | |
45 | cesc = mesc*2 |
|
45 | cesc = mesc*2 | |
46 | mman = self.shell.magics_manager |
|
46 | mman = self.shell.magics_manager | |
47 | magics = mman.lsmagic() |
|
47 | magics = mman.lsmagic() | |
48 | out = ['Available line magics:', |
|
48 | out = ['Available line magics:', | |
49 | mesc + (' '+mesc).join(magics['line']), |
|
49 | mesc + (' '+mesc).join(magics['line']), | |
50 | '', |
|
50 | '', | |
51 | 'Available cell magics:', |
|
51 | 'Available cell magics:', | |
52 | cesc + (' '+cesc).join(magics['cell']), |
|
52 | cesc + (' '+cesc).join(magics['cell']), | |
53 | '', |
|
53 | '', | |
54 | mman.auto_status()] |
|
54 | mman.auto_status()] | |
55 | return '\n'.join(out) |
|
55 | return '\n'.join(out) | |
56 |
|
56 | |||
57 | @line_magic |
|
57 | @line_magic | |
58 | def lsmagic(self, parameter_s=''): |
|
58 | def lsmagic(self, parameter_s=''): | |
59 | """List currently available magic functions.""" |
|
59 | """List currently available magic functions.""" | |
60 | print(self._lsmagic()) |
|
60 | print(self._lsmagic()) | |
61 |
|
61 | |||
62 | @line_magic |
|
62 | @line_magic | |
63 | def magic(self, parameter_s=''): |
|
63 | def magic(self, parameter_s=''): | |
64 | """Print information about the magic function system. |
|
64 | """Print information about the magic function system. | |
65 |
|
65 | |||
66 | Supported formats: -latex, -brief, -rest |
|
66 | Supported formats: -latex, -brief, -rest | |
67 | """ |
|
67 | """ | |
68 |
|
68 | |||
69 | mode = '' |
|
69 | mode = '' | |
70 | try: |
|
70 | try: | |
71 | mode = parameter_s.split()[0][1:] |
|
71 | mode = parameter_s.split()[0][1:] | |
72 | if mode == 'rest': |
|
72 | if mode == 'rest': | |
73 | rest_docs = [] |
|
73 | rest_docs = [] | |
74 | except: |
|
74 | except IndexError: | |
75 | pass |
|
75 | pass | |
76 |
|
76 | |||
77 | magic_docs = [] |
|
77 | magic_docs = [] | |
78 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) |
|
78 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) | |
79 | magics = self.shell.magics_manager.magics |
|
79 | magics = self.shell.magics_manager.magics | |
80 |
|
80 | |||
81 | for mtype in ('line', 'cell'): |
|
81 | for mtype in ('line', 'cell'): | |
82 | escape = escapes[mtype] |
|
82 | escape = escapes[mtype] | |
83 | for fname, fn in magics[mtype].iteritems(): |
|
83 | for fname, fn in magics[mtype].iteritems(): | |
84 |
|
84 | |||
85 | if mode == 'brief': |
|
85 | if mode == 'brief': | |
86 | # only first line |
|
86 | # only first line | |
87 | if fn.__doc__: |
|
87 | if fn.__doc__: | |
88 | fndoc = fn.__doc__.split('\n',1)[0] |
|
88 | fndoc = fn.__doc__.split('\n',1)[0] | |
89 | else: |
|
89 | else: | |
90 | fndoc = 'No documentation' |
|
90 | fndoc = 'No documentation' | |
91 | else: |
|
91 | else: | |
92 | if fn.__doc__: |
|
92 | if fn.__doc__: | |
93 | fndoc = fn.__doc__.rstrip() |
|
93 | fndoc = fn.__doc__.rstrip() | |
94 | else: |
|
94 | else: | |
95 | fndoc = 'No documentation' |
|
95 | fndoc = 'No documentation' | |
96 |
|
96 | |||
97 | if mode == 'rest': |
|
97 | if mode == 'rest': | |
98 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % |
|
98 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % | |
99 | (escape, fname, fndoc)) |
|
99 | (escape, fname, fndoc)) | |
100 | else: |
|
100 | else: | |
101 | magic_docs.append('%s%s:\n\t%s\n' % |
|
101 | magic_docs.append('%s%s:\n\t%s\n' % | |
102 | (escape, fname, fndoc)) |
|
102 | (escape, fname, fndoc)) | |
103 |
|
103 | |||
104 | magic_docs = ''.join(magic_docs) |
|
104 | magic_docs = ''.join(magic_docs) | |
105 |
|
105 | |||
106 | if mode == 'rest': |
|
106 | if mode == 'rest': | |
107 | return "".join(rest_docs) |
|
107 | return "".join(rest_docs) | |
108 |
|
108 | |||
109 | if mode == 'latex': |
|
109 | if mode == 'latex': | |
110 | print(self.format_latex(magic_docs)) |
|
110 | print(self.format_latex(magic_docs)) | |
111 | return |
|
111 | return | |
112 | else: |
|
112 | else: | |
113 | magic_docs = format_screen(magic_docs) |
|
113 | magic_docs = format_screen(magic_docs) | |
114 | if mode == 'brief': |
|
114 | if mode == 'brief': | |
115 | return magic_docs |
|
115 | return magic_docs | |
116 |
|
116 | |||
117 | out = [""" |
|
117 | out = [""" | |
118 | IPython's 'magic' functions |
|
118 | IPython's 'magic' functions | |
119 | =========================== |
|
119 | =========================== | |
120 |
|
120 | |||
121 | The magic function system provides a series of functions which allow you to |
|
121 | The magic function system provides a series of functions which allow you to | |
122 | control the behavior of IPython itself, plus a lot of system-type |
|
122 | control the behavior of IPython itself, plus a lot of system-type | |
123 | features. All these functions are prefixed with a % character, but parameters |
|
123 | features. All these functions are prefixed with a % character, but parameters | |
124 | are given without parentheses or quotes. |
|
124 | are given without parentheses or quotes. | |
125 |
|
125 | |||
126 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
126 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
127 | %automagic function), you don't need to type in the % explicitly. By default, |
|
127 | %automagic function), you don't need to type in the % explicitly. By default, | |
128 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
128 | IPython ships with automagic on, so you should only rarely need the % escape. | |
129 |
|
129 | |||
130 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
130 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
131 | to 'mydir', if it exists. |
|
131 | to 'mydir', if it exists. | |
132 |
|
132 | |||
133 | For a list of the available magic functions, use %lsmagic. For a description |
|
133 | For a list of the available magic functions, use %lsmagic. For a description | |
134 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
134 | of any of them, type %magic_name?, e.g. '%cd?'. | |
135 |
|
135 | |||
136 | Currently the magic system has the following functions:""", |
|
136 | Currently the magic system has the following functions:""", | |
137 | magic_docs, |
|
137 | magic_docs, | |
138 | "Summary of magic functions (from %slsmagic):", |
|
138 | "Summary of magic functions (from %slsmagic):", | |
139 | self._lsmagic(), |
|
139 | self._lsmagic(), | |
140 | ] |
|
140 | ] | |
141 | page.page('\n'.join(out)) |
|
141 | page.page('\n'.join(out)) | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | @line_magic |
|
144 | @line_magic | |
145 | def page(self, parameter_s=''): |
|
145 | def page(self, parameter_s=''): | |
146 | """Pretty print the object and display it through a pager. |
|
146 | """Pretty print the object and display it through a pager. | |
147 |
|
147 | |||
148 | %page [options] OBJECT |
|
148 | %page [options] OBJECT | |
149 |
|
149 | |||
150 | If no object is given, use _ (last output). |
|
150 | If no object is given, use _ (last output). | |
151 |
|
151 | |||
152 | Options: |
|
152 | Options: | |
153 |
|
153 | |||
154 | -r: page str(object), don't pretty-print it.""" |
|
154 | -r: page str(object), don't pretty-print it.""" | |
155 |
|
155 | |||
156 | # After a function contributed by Olivier Aubert, slightly modified. |
|
156 | # After a function contributed by Olivier Aubert, slightly modified. | |
157 |
|
157 | |||
158 | # Process options/args |
|
158 | # Process options/args | |
159 | opts, args = self.parse_options(parameter_s, 'r') |
|
159 | opts, args = self.parse_options(parameter_s, 'r') | |
160 | raw = 'r' in opts |
|
160 | raw = 'r' in opts | |
161 |
|
161 | |||
162 | oname = args and args or '_' |
|
162 | oname = args and args or '_' | |
163 | info = self._ofind(oname) |
|
163 | info = self._ofind(oname) | |
164 | if info['found']: |
|
164 | if info['found']: | |
165 | txt = (raw and str or pformat)( info['obj'] ) |
|
165 | txt = (raw and str or pformat)( info['obj'] ) | |
166 | page.page(txt) |
|
166 | page.page(txt) | |
167 | else: |
|
167 | else: | |
168 | print('Object `%s` not found' % oname) |
|
168 | print('Object `%s` not found' % oname) | |
169 |
|
169 | |||
170 | @line_magic |
|
170 | @line_magic | |
171 | def profile(self, parameter_s=''): |
|
171 | def profile(self, parameter_s=''): | |
172 | """Print your currently active IPython profile.""" |
|
172 | """Print your currently active IPython profile.""" | |
173 | from IPython.core.application import BaseIPythonApplication |
|
173 | from IPython.core.application import BaseIPythonApplication | |
174 | if BaseIPythonApplication.initialized(): |
|
174 | if BaseIPythonApplication.initialized(): | |
175 | print(BaseIPythonApplication.instance().profile) |
|
175 | print(BaseIPythonApplication.instance().profile) | |
176 | else: |
|
176 | else: | |
177 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
177 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
178 |
|
178 | |||
179 | @line_magic |
|
179 | @line_magic | |
180 | def pprint(self, parameter_s=''): |
|
180 | def pprint(self, parameter_s=''): | |
181 | """Toggle pretty printing on/off.""" |
|
181 | """Toggle pretty printing on/off.""" | |
182 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
182 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
183 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
183 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
184 | print('Pretty printing has been turned', |
|
184 | print('Pretty printing has been turned', | |
185 | ['OFF','ON'][ptformatter.pprint]) |
|
185 | ['OFF','ON'][ptformatter.pprint]) | |
186 |
|
186 | |||
187 | @line_magic |
|
187 | @line_magic | |
188 | def colors(self, parameter_s=''): |
|
188 | def colors(self, parameter_s=''): | |
189 | """Switch color scheme for prompts, info system and exception handlers. |
|
189 | """Switch color scheme for prompts, info system and exception handlers. | |
190 |
|
190 | |||
191 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
191 | Currently implemented schemes: NoColor, Linux, LightBG. | |
192 |
|
192 | |||
193 | Color scheme names are not case-sensitive. |
|
193 | Color scheme names are not case-sensitive. | |
194 |
|
194 | |||
195 | Examples |
|
195 | Examples | |
196 | -------- |
|
196 | -------- | |
197 | To get a plain black and white terminal:: |
|
197 | To get a plain black and white terminal:: | |
198 |
|
198 | |||
199 | %colors nocolor |
|
199 | %colors nocolor | |
200 | """ |
|
200 | """ | |
201 | def color_switch_err(name): |
|
201 | def color_switch_err(name): | |
202 | warn('Error changing %s color schemes.\n%s' % |
|
202 | warn('Error changing %s color schemes.\n%s' % | |
203 | (name, sys.exc_info()[1])) |
|
203 | (name, sys.exc_info()[1])) | |
204 |
|
204 | |||
205 |
|
205 | |||
206 | new_scheme = parameter_s.strip() |
|
206 | new_scheme = parameter_s.strip() | |
207 | if not new_scheme: |
|
207 | if not new_scheme: | |
208 | raise UsageError( |
|
208 | raise UsageError( | |
209 | "%colors: you must specify a color scheme. See '%colors?'") |
|
209 | "%colors: you must specify a color scheme. See '%colors?'") | |
210 | return |
|
210 | return | |
211 | # local shortcut |
|
211 | # local shortcut | |
212 | shell = self.shell |
|
212 | shell = self.shell | |
213 |
|
213 | |||
214 | import IPython.utils.rlineimpl as readline |
|
214 | import IPython.utils.rlineimpl as readline | |
215 |
|
215 | |||
216 | if not shell.colors_force and \ |
|
216 | if not shell.colors_force and \ | |
217 | not readline.have_readline and sys.platform == "win32": |
|
217 | not readline.have_readline and sys.platform == "win32": | |
218 | msg = """\ |
|
218 | msg = """\ | |
219 | Proper color support under MS Windows requires the pyreadline library. |
|
219 | Proper color support under MS Windows requires the pyreadline library. | |
220 | You can find it at: |
|
220 | You can find it at: | |
221 | http://ipython.org/pyreadline.html |
|
221 | http://ipython.org/pyreadline.html | |
222 | Gary's readline needs the ctypes module, from: |
|
222 | Gary's readline needs the ctypes module, from: | |
223 | http://starship.python.net/crew/theller/ctypes |
|
223 | http://starship.python.net/crew/theller/ctypes | |
224 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
224 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
225 |
|
225 | |||
226 | Defaulting color scheme to 'NoColor'""" |
|
226 | Defaulting color scheme to 'NoColor'""" | |
227 | new_scheme = 'NoColor' |
|
227 | new_scheme = 'NoColor' | |
228 | warn(msg) |
|
228 | warn(msg) | |
229 |
|
229 | |||
230 | # readline option is 0 |
|
230 | # readline option is 0 | |
231 | if not shell.colors_force and not shell.has_readline: |
|
231 | if not shell.colors_force and not shell.has_readline: | |
232 | new_scheme = 'NoColor' |
|
232 | new_scheme = 'NoColor' | |
233 |
|
233 | |||
234 | # Set prompt colors |
|
234 | # Set prompt colors | |
235 | try: |
|
235 | try: | |
236 | shell.prompt_manager.color_scheme = new_scheme |
|
236 | shell.prompt_manager.color_scheme = new_scheme | |
237 | except: |
|
237 | except: | |
238 | color_switch_err('prompt') |
|
238 | color_switch_err('prompt') | |
239 | else: |
|
239 | else: | |
240 | shell.colors = \ |
|
240 | shell.colors = \ | |
241 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
241 | shell.prompt_manager.color_scheme_table.active_scheme_name | |
242 | # Set exception colors |
|
242 | # Set exception colors | |
243 | try: |
|
243 | try: | |
244 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
244 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
245 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
245 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
246 | except: |
|
246 | except: | |
247 | color_switch_err('exception') |
|
247 | color_switch_err('exception') | |
248 |
|
248 | |||
249 | # Set info (for 'object?') colors |
|
249 | # Set info (for 'object?') colors | |
250 | if shell.color_info: |
|
250 | if shell.color_info: | |
251 | try: |
|
251 | try: | |
252 | shell.inspector.set_active_scheme(new_scheme) |
|
252 | shell.inspector.set_active_scheme(new_scheme) | |
253 | except: |
|
253 | except: | |
254 | color_switch_err('object inspector') |
|
254 | color_switch_err('object inspector') | |
255 | else: |
|
255 | else: | |
256 | shell.inspector.set_active_scheme('NoColor') |
|
256 | shell.inspector.set_active_scheme('NoColor') | |
257 |
|
257 | |||
258 | @line_magic |
|
258 | @line_magic | |
259 | def xmode(self, parameter_s=''): |
|
259 | def xmode(self, parameter_s=''): | |
260 | """Switch modes for the exception handlers. |
|
260 | """Switch modes for the exception handlers. | |
261 |
|
261 | |||
262 | Valid modes: Plain, Context and Verbose. |
|
262 | Valid modes: Plain, Context and Verbose. | |
263 |
|
263 | |||
264 | If called without arguments, acts as a toggle.""" |
|
264 | If called without arguments, acts as a toggle.""" | |
265 |
|
265 | |||
266 | def xmode_switch_err(name): |
|
266 | def xmode_switch_err(name): | |
267 | warn('Error changing %s exception modes.\n%s' % |
|
267 | warn('Error changing %s exception modes.\n%s' % | |
268 | (name,sys.exc_info()[1])) |
|
268 | (name,sys.exc_info()[1])) | |
269 |
|
269 | |||
270 | shell = self.shell |
|
270 | shell = self.shell | |
271 | new_mode = parameter_s.strip().capitalize() |
|
271 | new_mode = parameter_s.strip().capitalize() | |
272 | try: |
|
272 | try: | |
273 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
273 | shell.InteractiveTB.set_mode(mode=new_mode) | |
274 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
274 | print('Exception reporting mode:',shell.InteractiveTB.mode) | |
275 | except: |
|
275 | except: | |
276 | xmode_switch_err('user') |
|
276 | xmode_switch_err('user') | |
277 |
|
277 | |||
278 | @line_magic |
|
278 | @line_magic | |
279 | def quickref(self,arg): |
|
279 | def quickref(self,arg): | |
280 | """ Show a quick reference sheet """ |
|
280 | """ Show a quick reference sheet """ | |
281 | from IPython.core.usage import quick_reference |
|
281 | from IPython.core.usage import quick_reference | |
282 | qr = quick_reference + self.magic('-brief') |
|
282 | qr = quick_reference + self.magic('-brief') | |
283 | page.page(qr) |
|
283 | page.page(qr) | |
284 |
|
284 | |||
285 | @line_magic |
|
285 | @line_magic | |
286 | def doctest_mode(self, parameter_s=''): |
|
286 | def doctest_mode(self, parameter_s=''): | |
287 | """Toggle doctest mode on and off. |
|
287 | """Toggle doctest mode on and off. | |
288 |
|
288 | |||
289 | This mode is intended to make IPython behave as much as possible like a |
|
289 | This mode is intended to make IPython behave as much as possible like a | |
290 | plain Python shell, from the perspective of how its prompts, exceptions |
|
290 | plain Python shell, from the perspective of how its prompts, exceptions | |
291 | and output look. This makes it easy to copy and paste parts of a |
|
291 | and output look. This makes it easy to copy and paste parts of a | |
292 | session into doctests. It does so by: |
|
292 | session into doctests. It does so by: | |
293 |
|
293 | |||
294 | - Changing the prompts to the classic ``>>>`` ones. |
|
294 | - Changing the prompts to the classic ``>>>`` ones. | |
295 | - Changing the exception reporting mode to 'Plain'. |
|
295 | - Changing the exception reporting mode to 'Plain'. | |
296 | - Disabling pretty-printing of output. |
|
296 | - Disabling pretty-printing of output. | |
297 |
|
297 | |||
298 | Note that IPython also supports the pasting of code snippets that have |
|
298 | Note that IPython also supports the pasting of code snippets that have | |
299 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
299 | leading '>>>' and '...' prompts in them. This means that you can paste | |
300 | doctests from files or docstrings (even if they have leading |
|
300 | doctests from files or docstrings (even if they have leading | |
301 | whitespace), and the code will execute correctly. You can then use |
|
301 | whitespace), and the code will execute correctly. You can then use | |
302 | '%history -t' to see the translated history; this will give you the |
|
302 | '%history -t' to see the translated history; this will give you the | |
303 | input after removal of all the leading prompts and whitespace, which |
|
303 | input after removal of all the leading prompts and whitespace, which | |
304 | can be pasted back into an editor. |
|
304 | can be pasted back into an editor. | |
305 |
|
305 | |||
306 | With these features, you can switch into this mode easily whenever you |
|
306 | With these features, you can switch into this mode easily whenever you | |
307 | need to do testing and changes to doctests, without having to leave |
|
307 | need to do testing and changes to doctests, without having to leave | |
308 | your existing IPython session. |
|
308 | your existing IPython session. | |
309 | """ |
|
309 | """ | |
310 |
|
310 | |||
311 | # Shorthands |
|
311 | # Shorthands | |
312 | shell = self.shell |
|
312 | shell = self.shell | |
313 | pm = shell.prompt_manager |
|
313 | pm = shell.prompt_manager | |
314 | meta = shell.meta |
|
314 | meta = shell.meta | |
315 | disp_formatter = self.shell.display_formatter |
|
315 | disp_formatter = self.shell.display_formatter | |
316 | ptformatter = disp_formatter.formatters['text/plain'] |
|
316 | ptformatter = disp_formatter.formatters['text/plain'] | |
317 | # dstore is a data store kept in the instance metadata bag to track any |
|
317 | # dstore is a data store kept in the instance metadata bag to track any | |
318 | # changes we make, so we can undo them later. |
|
318 | # changes we make, so we can undo them later. | |
319 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
319 | dstore = meta.setdefault('doctest_mode',Struct()) | |
320 | save_dstore = dstore.setdefault |
|
320 | save_dstore = dstore.setdefault | |
321 |
|
321 | |||
322 | # save a few values we'll need to recover later |
|
322 | # save a few values we'll need to recover later | |
323 | mode = save_dstore('mode',False) |
|
323 | mode = save_dstore('mode',False) | |
324 | save_dstore('rc_pprint',ptformatter.pprint) |
|
324 | save_dstore('rc_pprint',ptformatter.pprint) | |
325 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
325 | save_dstore('xmode',shell.InteractiveTB.mode) | |
326 | save_dstore('rc_separate_out',shell.separate_out) |
|
326 | save_dstore('rc_separate_out',shell.separate_out) | |
327 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
327 | save_dstore('rc_separate_out2',shell.separate_out2) | |
328 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
328 | save_dstore('rc_prompts_pad_left',pm.justify) | |
329 | save_dstore('rc_separate_in',shell.separate_in) |
|
329 | save_dstore('rc_separate_in',shell.separate_in) | |
330 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
330 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
331 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
331 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) | |
332 |
|
332 | |||
333 | if mode == False: |
|
333 | if mode == False: | |
334 | # turn on |
|
334 | # turn on | |
335 | pm.in_template = '>>> ' |
|
335 | pm.in_template = '>>> ' | |
336 | pm.in2_template = '... ' |
|
336 | pm.in2_template = '... ' | |
337 | pm.out_template = '' |
|
337 | pm.out_template = '' | |
338 |
|
338 | |||
339 | # Prompt separators like plain python |
|
339 | # Prompt separators like plain python | |
340 | shell.separate_in = '' |
|
340 | shell.separate_in = '' | |
341 | shell.separate_out = '' |
|
341 | shell.separate_out = '' | |
342 | shell.separate_out2 = '' |
|
342 | shell.separate_out2 = '' | |
343 |
|
343 | |||
344 | pm.justify = False |
|
344 | pm.justify = False | |
345 |
|
345 | |||
346 | ptformatter.pprint = False |
|
346 | ptformatter.pprint = False | |
347 | disp_formatter.plain_text_only = True |
|
347 | disp_formatter.plain_text_only = True | |
348 |
|
348 | |||
349 | shell.magic('xmode Plain') |
|
349 | shell.magic('xmode Plain') | |
350 | else: |
|
350 | else: | |
351 | # turn off |
|
351 | # turn off | |
352 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
352 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates | |
353 |
|
353 | |||
354 | shell.separate_in = dstore.rc_separate_in |
|
354 | shell.separate_in = dstore.rc_separate_in | |
355 |
|
355 | |||
356 | shell.separate_out = dstore.rc_separate_out |
|
356 | shell.separate_out = dstore.rc_separate_out | |
357 | shell.separate_out2 = dstore.rc_separate_out2 |
|
357 | shell.separate_out2 = dstore.rc_separate_out2 | |
358 |
|
358 | |||
359 | pm.justify = dstore.rc_prompts_pad_left |
|
359 | pm.justify = dstore.rc_prompts_pad_left | |
360 |
|
360 | |||
361 | ptformatter.pprint = dstore.rc_pprint |
|
361 | ptformatter.pprint = dstore.rc_pprint | |
362 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
362 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
363 |
|
363 | |||
364 | shell.magic('xmode ' + dstore.xmode) |
|
364 | shell.magic('xmode ' + dstore.xmode) | |
365 |
|
365 | |||
366 | # Store new mode and inform |
|
366 | # Store new mode and inform | |
367 | dstore.mode = bool(1-int(mode)) |
|
367 | dstore.mode = bool(1-int(mode)) | |
368 | mode_label = ['OFF','ON'][dstore.mode] |
|
368 | mode_label = ['OFF','ON'][dstore.mode] | |
369 | print('Doctest mode is:', mode_label) |
|
369 | print('Doctest mode is:', mode_label) | |
370 |
|
370 | |||
371 | @line_magic |
|
371 | @line_magic | |
372 | def gui(self, parameter_s=''): |
|
372 | def gui(self, parameter_s=''): | |
373 | """Enable or disable IPython GUI event loop integration. |
|
373 | """Enable or disable IPython GUI event loop integration. | |
374 |
|
374 | |||
375 | %gui [GUINAME] |
|
375 | %gui [GUINAME] | |
376 |
|
376 | |||
377 | This magic replaces IPython's threaded shells that were activated |
|
377 | This magic replaces IPython's threaded shells that were activated | |
378 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
378 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
379 | can now be enabled at runtime and keyboard |
|
379 | can now be enabled at runtime and keyboard | |
380 | interrupts should work without any problems. The following toolkits |
|
380 | interrupts should work without any problems. The following toolkits | |
381 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
381 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
382 |
|
382 | |||
383 | %gui wx # enable wxPython event loop integration |
|
383 | %gui wx # enable wxPython event loop integration | |
384 | %gui qt4|qt # enable PyQt4 event loop integration |
|
384 | %gui qt4|qt # enable PyQt4 event loop integration | |
385 | %gui gtk # enable PyGTK event loop integration |
|
385 | %gui gtk # enable PyGTK event loop integration | |
386 | %gui gtk3 # enable Gtk3 event loop integration |
|
386 | %gui gtk3 # enable Gtk3 event loop integration | |
387 | %gui tk # enable Tk event loop integration |
|
387 | %gui tk # enable Tk event loop integration | |
388 | %gui OSX # enable Cocoa event loop integration |
|
388 | %gui OSX # enable Cocoa event loop integration | |
389 | # (requires %matplotlib 1.1) |
|
389 | # (requires %matplotlib 1.1) | |
390 | %gui # disable all event loop integration |
|
390 | %gui # disable all event loop integration | |
391 |
|
391 | |||
392 | WARNING: after any of these has been called you can simply create |
|
392 | WARNING: after any of these has been called you can simply create | |
393 | an application object, but DO NOT start the event loop yourself, as |
|
393 | an application object, but DO NOT start the event loop yourself, as | |
394 | we have already handled that. |
|
394 | we have already handled that. | |
395 | """ |
|
395 | """ | |
396 | opts, arg = self.parse_options(parameter_s, '') |
|
396 | opts, arg = self.parse_options(parameter_s, '') | |
397 | if arg=='': arg = None |
|
397 | if arg=='': arg = None | |
398 | try: |
|
398 | try: | |
399 | return self.enable_gui(arg) |
|
399 | return self.enable_gui(arg) | |
400 | except Exception as e: |
|
400 | except Exception as e: | |
401 | # print simple error message, rather than traceback if we can't |
|
401 | # print simple error message, rather than traceback if we can't | |
402 | # hook up the GUI |
|
402 | # hook up the GUI | |
403 | error(str(e)) |
|
403 | error(str(e)) | |
404 |
|
404 | |||
405 | @skip_doctest |
|
405 | @skip_doctest | |
406 | @line_magic |
|
406 | @line_magic | |
407 | def precision(self, s=''): |
|
407 | def precision(self, s=''): | |
408 | """Set floating point precision for pretty printing. |
|
408 | """Set floating point precision for pretty printing. | |
409 |
|
409 | |||
410 | Can set either integer precision or a format string. |
|
410 | Can set either integer precision or a format string. | |
411 |
|
411 | |||
412 | If numpy has been imported and precision is an int, |
|
412 | If numpy has been imported and precision is an int, | |
413 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
413 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
414 |
|
414 | |||
415 | If no argument is given, defaults will be restored. |
|
415 | If no argument is given, defaults will be restored. | |
416 |
|
416 | |||
417 | Examples |
|
417 | Examples | |
418 | -------- |
|
418 | -------- | |
419 | :: |
|
419 | :: | |
420 |
|
420 | |||
421 | In [1]: from math import pi |
|
421 | In [1]: from math import pi | |
422 |
|
422 | |||
423 | In [2]: %precision 3 |
|
423 | In [2]: %precision 3 | |
424 | Out[2]: u'%.3f' |
|
424 | Out[2]: u'%.3f' | |
425 |
|
425 | |||
426 | In [3]: pi |
|
426 | In [3]: pi | |
427 | Out[3]: 3.142 |
|
427 | Out[3]: 3.142 | |
428 |
|
428 | |||
429 | In [4]: %precision %i |
|
429 | In [4]: %precision %i | |
430 | Out[4]: u'%i' |
|
430 | Out[4]: u'%i' | |
431 |
|
431 | |||
432 | In [5]: pi |
|
432 | In [5]: pi | |
433 | Out[5]: 3 |
|
433 | Out[5]: 3 | |
434 |
|
434 | |||
435 | In [6]: %precision %e |
|
435 | In [6]: %precision %e | |
436 | Out[6]: u'%e' |
|
436 | Out[6]: u'%e' | |
437 |
|
437 | |||
438 | In [7]: pi**10 |
|
438 | In [7]: pi**10 | |
439 | Out[7]: 9.364805e+04 |
|
439 | Out[7]: 9.364805e+04 | |
440 |
|
440 | |||
441 | In [8]: %precision |
|
441 | In [8]: %precision | |
442 | Out[8]: u'%r' |
|
442 | Out[8]: u'%r' | |
443 |
|
443 | |||
444 | In [9]: pi**10 |
|
444 | In [9]: pi**10 | |
445 | Out[9]: 93648.047476082982 |
|
445 | Out[9]: 93648.047476082982 | |
446 | """ |
|
446 | """ | |
447 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
447 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
448 | ptformatter.float_precision = s |
|
448 | ptformatter.float_precision = s | |
449 | return ptformatter.float_format |
|
449 | return ptformatter.float_format | |
450 |
|
450 | |||
451 | @magic_arguments.magic_arguments() |
|
451 | @magic_arguments.magic_arguments() | |
452 | @magic_arguments.argument( |
|
452 | @magic_arguments.argument( | |
453 | '-e', '--export', action='store_true', default=False, |
|
453 | '-e', '--export', action='store_true', default=False, | |
454 | help='Export IPython history as a notebook. The filename argument ' |
|
454 | help='Export IPython history as a notebook. The filename argument ' | |
455 | 'is used to specify the notebook name and format. For example ' |
|
455 | 'is used to specify the notebook name and format. For example ' | |
456 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
456 | 'a filename of notebook.ipynb will result in a notebook name ' | |
457 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
457 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
458 | 'or ".py" file extension will write the notebook in the json ' |
|
458 | 'or ".py" file extension will write the notebook in the json ' | |
459 | 'or py formats.' |
|
459 | 'or py formats.' | |
460 | ) |
|
460 | ) | |
461 | @magic_arguments.argument( |
|
461 | @magic_arguments.argument( | |
462 | '-f', '--format', |
|
462 | '-f', '--format', | |
463 | help='Convert an existing IPython notebook to a new format. This option ' |
|
463 | help='Convert an existing IPython notebook to a new format. This option ' | |
464 | 'specifies the new format and can have the values: xml, json, py. ' |
|
464 | 'specifies the new format and can have the values: xml, json, py. ' | |
465 | 'The target filename is chosen automatically based on the new ' |
|
465 | 'The target filename is chosen automatically based on the new ' | |
466 | 'format. The filename argument gives the name of the source file.' |
|
466 | 'format. The filename argument gives the name of the source file.' | |
467 | ) |
|
467 | ) | |
468 | @magic_arguments.argument( |
|
468 | @magic_arguments.argument( | |
469 | 'filename', type=unicode, |
|
469 | 'filename', type=unicode, | |
470 | help='Notebook name or filename' |
|
470 | help='Notebook name or filename' | |
471 | ) |
|
471 | ) | |
472 | @line_magic |
|
472 | @line_magic | |
473 | def notebook(self, s): |
|
473 | def notebook(self, s): | |
474 | """Export and convert IPython notebooks. |
|
474 | """Export and convert IPython notebooks. | |
475 |
|
475 | |||
476 | This function can export the current IPython history to a notebook file |
|
476 | This function can export the current IPython history to a notebook file | |
477 | or can convert an existing notebook file into a different format. For |
|
477 | or can convert an existing notebook file into a different format. For | |
478 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
478 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
479 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
479 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
480 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
480 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
481 | formats include (json/ipynb, py). |
|
481 | formats include (json/ipynb, py). | |
482 | """ |
|
482 | """ | |
483 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
483 | args = magic_arguments.parse_argstring(self.notebook, s) | |
484 |
|
484 | |||
485 | from IPython.nbformat import current |
|
485 | from IPython.nbformat import current | |
486 | args.filename = unquote_filename(args.filename) |
|
486 | args.filename = unquote_filename(args.filename) | |
487 | if args.export: |
|
487 | if args.export: | |
488 | fname, name, format = current.parse_filename(args.filename) |
|
488 | fname, name, format = current.parse_filename(args.filename) | |
489 | cells = [] |
|
489 | cells = [] | |
490 | hist = list(self.shell.history_manager.get_range()) |
|
490 | hist = list(self.shell.history_manager.get_range()) | |
491 | for session, prompt_number, input in hist[:-1]: |
|
491 | for session, prompt_number, input in hist[:-1]: | |
492 | cells.append(current.new_code_cell(prompt_number=prompt_number, |
|
492 | cells.append(current.new_code_cell(prompt_number=prompt_number, | |
493 | input=input)) |
|
493 | input=input)) | |
494 | worksheet = current.new_worksheet(cells=cells) |
|
494 | worksheet = current.new_worksheet(cells=cells) | |
495 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
495 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
496 | with io.open(fname, 'w', encoding='utf-8') as f: |
|
496 | with io.open(fname, 'w', encoding='utf-8') as f: | |
497 | current.write(nb, f, format); |
|
497 | current.write(nb, f, format); | |
498 | elif args.format is not None: |
|
498 | elif args.format is not None: | |
499 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
499 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
500 | new_format = args.format |
|
500 | new_format = args.format | |
501 | if new_format == u'xml': |
|
501 | if new_format == u'xml': | |
502 | raise ValueError('Notebooks cannot be written as xml.') |
|
502 | raise ValueError('Notebooks cannot be written as xml.') | |
503 | elif new_format == u'ipynb' or new_format == u'json': |
|
503 | elif new_format == u'ipynb' or new_format == u'json': | |
504 | new_fname = old_name + u'.ipynb' |
|
504 | new_fname = old_name + u'.ipynb' | |
505 | new_format = u'json' |
|
505 | new_format = u'json' | |
506 | elif new_format == u'py': |
|
506 | elif new_format == u'py': | |
507 | new_fname = old_name + u'.py' |
|
507 | new_fname = old_name + u'.py' | |
508 | else: |
|
508 | else: | |
509 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
509 | raise ValueError('Invalid notebook format: %s' % new_format) | |
510 | with io.open(old_fname, 'r', encoding='utf-8') as f: |
|
510 | with io.open(old_fname, 'r', encoding='utf-8') as f: | |
511 | nb = current.read(f, old_format) |
|
511 | nb = current.read(f, old_format) | |
512 | with io.open(new_fname, 'w', encoding='utf-8') as f: |
|
512 | with io.open(new_fname, 'w', encoding='utf-8') as f: | |
513 | current.write(nb, f, new_format) |
|
513 | current.write(nb, f, new_format) |
@@ -1,478 +1,478 b'' | |||||
1 | """Implementation of code management magic functions. |
|
1 | """Implementation of code management magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import inspect |
|
16 | import inspect | |
17 | import io |
|
17 | import io | |
18 | import json |
|
18 | import json | |
19 | import os |
|
19 | import os | |
20 | import sys |
|
20 | import sys | |
21 | from urllib2 import urlopen |
|
21 | from urllib2 import urlopen | |
22 |
|
22 | |||
23 | # Our own packages |
|
23 | # Our own packages | |
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.macro import Macro |
|
25 | from IPython.core.macro import Macro | |
26 | from IPython.core.magic import Magics, magics_class, line_magic |
|
26 | from IPython.core.magic import Magics, magics_class, line_magic | |
27 | from IPython.testing.skipdoctest import skip_doctest |
|
27 | from IPython.testing.skipdoctest import skip_doctest | |
28 | from IPython.utils import openpy |
|
28 | from IPython.utils import openpy | |
29 | from IPython.utils import py3compat |
|
29 | from IPython.utils import py3compat | |
30 | from IPython.utils.io import file_read |
|
30 | from IPython.utils.io import file_read | |
31 | from IPython.utils.path import get_py_filename, unquote_filename |
|
31 | from IPython.utils.path import get_py_filename, unquote_filename | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Magic implementation classes |
|
35 | # Magic implementation classes | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 | # Used for exception handling in magic_edit |
|
38 | # Used for exception handling in magic_edit | |
39 | class MacroToEdit(ValueError): pass |
|
39 | class MacroToEdit(ValueError): pass | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | @magics_class |
|
42 | @magics_class | |
43 | class CodeMagics(Magics): |
|
43 | class CodeMagics(Magics): | |
44 | """Magics related to code management (loading, saving, editing, ...).""" |
|
44 | """Magics related to code management (loading, saving, editing, ...).""" | |
45 |
|
45 | |||
46 | @line_magic |
|
46 | @line_magic | |
47 | def save(self, parameter_s=''): |
|
47 | def save(self, parameter_s=''): | |
48 | """Save a set of lines or a macro to a given filename. |
|
48 | """Save a set of lines or a macro to a given filename. | |
49 |
|
49 | |||
50 | Usage:\\ |
|
50 | Usage:\\ | |
51 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
51 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
52 |
|
52 | |||
53 | Options: |
|
53 | Options: | |
54 |
|
54 | |||
55 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
55 | -r: use 'raw' input. By default, the 'processed' history is used, | |
56 | so that magics are loaded in their transformed version to valid |
|
56 | so that magics are loaded in their transformed version to valid | |
57 | Python. If this option is given, the raw input as typed as the |
|
57 | Python. If this option is given, the raw input as typed as the | |
58 | command line is used instead. |
|
58 | command line is used instead. | |
59 |
|
59 | |||
60 | This function uses the same syntax as %history for input ranges, |
|
60 | This function uses the same syntax as %history for input ranges, | |
61 | then saves the lines to the filename you specify. |
|
61 | then saves the lines to the filename you specify. | |
62 |
|
62 | |||
63 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
63 | It adds a '.py' extension to the file if you don't do so yourself, and | |
64 | it asks for confirmation before overwriting existing files.""" |
|
64 | it asks for confirmation before overwriting existing files.""" | |
65 |
|
65 | |||
66 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
66 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
67 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
67 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
68 | if not fname.endswith('.py'): |
|
68 | if not fname.endswith('.py'): | |
69 | fname += '.py' |
|
69 | fname += '.py' | |
70 | if os.path.isfile(fname): |
|
70 | if os.path.isfile(fname): | |
71 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
71 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
72 | if ans.lower() not in ['y','yes']: |
|
72 | if ans.lower() not in ['y','yes']: | |
73 | print 'Operation cancelled.' |
|
73 | print 'Operation cancelled.' | |
74 | return |
|
74 | return | |
75 | try: |
|
75 | try: | |
76 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
76 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
77 | except (TypeError, ValueError) as e: |
|
77 | except (TypeError, ValueError) as e: | |
78 | print e.args[0] |
|
78 | print e.args[0] | |
79 | return |
|
79 | return | |
80 | with io.open(fname,'w', encoding="utf-8") as f: |
|
80 | with io.open(fname,'w', encoding="utf-8") as f: | |
81 | f.write(u"# coding: utf-8\n") |
|
81 | f.write(u"# coding: utf-8\n") | |
82 | f.write(py3compat.cast_unicode(cmds)) |
|
82 | f.write(py3compat.cast_unicode(cmds)) | |
83 | print 'The following commands were written to file `%s`:' % fname |
|
83 | print 'The following commands were written to file `%s`:' % fname | |
84 | print cmds |
|
84 | print cmds | |
85 |
|
85 | |||
86 | @line_magic |
|
86 | @line_magic | |
87 | def pastebin(self, parameter_s=''): |
|
87 | def pastebin(self, parameter_s=''): | |
88 | """Upload code to Github's Gist paste bin, returning the URL. |
|
88 | """Upload code to Github's Gist paste bin, returning the URL. | |
89 |
|
89 | |||
90 | Usage:\\ |
|
90 | Usage:\\ | |
91 | %pastebin [-d "Custom description"] 1-7 |
|
91 | %pastebin [-d "Custom description"] 1-7 | |
92 |
|
92 | |||
93 | The argument can be an input history range, a filename, or the name of a |
|
93 | The argument can be an input history range, a filename, or the name of a | |
94 | string or macro. |
|
94 | string or macro. | |
95 |
|
95 | |||
96 | Options: |
|
96 | Options: | |
97 |
|
97 | |||
98 | -d: Pass a custom description for the gist. The default will say |
|
98 | -d: Pass a custom description for the gist. The default will say | |
99 | "Pasted from IPython". |
|
99 | "Pasted from IPython". | |
100 | """ |
|
100 | """ | |
101 | opts, args = self.parse_options(parameter_s, 'd:') |
|
101 | opts, args = self.parse_options(parameter_s, 'd:') | |
102 |
|
102 | |||
103 | try: |
|
103 | try: | |
104 | code = self.shell.find_user_code(args) |
|
104 | code = self.shell.find_user_code(args) | |
105 | except (ValueError, TypeError) as e: |
|
105 | except (ValueError, TypeError) as e: | |
106 | print e.args[0] |
|
106 | print e.args[0] | |
107 | return |
|
107 | return | |
108 |
|
108 | |||
109 | post_data = json.dumps({ |
|
109 | post_data = json.dumps({ | |
110 | "description": opts.get('d', "Pasted from IPython"), |
|
110 | "description": opts.get('d', "Pasted from IPython"), | |
111 | "public": True, |
|
111 | "public": True, | |
112 | "files": { |
|
112 | "files": { | |
113 | "file1.py": { |
|
113 | "file1.py": { | |
114 | "content": code |
|
114 | "content": code | |
115 | } |
|
115 | } | |
116 | } |
|
116 | } | |
117 | }).encode('utf-8') |
|
117 | }).encode('utf-8') | |
118 |
|
118 | |||
119 | response = urlopen("https://api.github.com/gists", post_data) |
|
119 | response = urlopen("https://api.github.com/gists", post_data) | |
120 | response_data = json.loads(response.read().decode('utf-8')) |
|
120 | response_data = json.loads(response.read().decode('utf-8')) | |
121 | return response_data['html_url'] |
|
121 | return response_data['html_url'] | |
122 |
|
122 | |||
123 | @line_magic |
|
123 | @line_magic | |
124 | def loadpy(self, arg_s): |
|
124 | def loadpy(self, arg_s): | |
125 | """Load a .py python script into the GUI console. |
|
125 | """Load a .py python script into the GUI console. | |
126 |
|
126 | |||
127 | This magic command can either take a local filename or a url:: |
|
127 | This magic command can either take a local filename or a url:: | |
128 |
|
128 | |||
129 | %loadpy myscript.py |
|
129 | %loadpy myscript.py | |
130 | %loadpy http://www.example.com/myscript.py |
|
130 | %loadpy http://www.example.com/myscript.py | |
131 | """ |
|
131 | """ | |
132 | arg_s = unquote_filename(arg_s) |
|
132 | arg_s = unquote_filename(arg_s) | |
133 | remote_url = arg_s.startswith(('http://', 'https://')) |
|
133 | remote_url = arg_s.startswith(('http://', 'https://')) | |
134 | local_url = not remote_url |
|
134 | local_url = not remote_url | |
135 | if local_url and not arg_s.endswith('.py'): |
|
135 | if local_url and not arg_s.endswith('.py'): | |
136 | # Local files must be .py; for remote URLs it's possible that the |
|
136 | # Local files must be .py; for remote URLs it's possible that the | |
137 | # fetch URL doesn't have a .py in it (many servers have an opaque |
|
137 | # fetch URL doesn't have a .py in it (many servers have an opaque | |
138 | # URL, such as scipy-central.org). |
|
138 | # URL, such as scipy-central.org). | |
139 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) |
|
139 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) | |
140 |
|
140 | |||
141 | # openpy takes care of finding the source encoding (per PEP 263) |
|
141 | # openpy takes care of finding the source encoding (per PEP 263) | |
142 | if remote_url: |
|
142 | if remote_url: | |
143 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) |
|
143 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) | |
144 | else: |
|
144 | else: | |
145 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) |
|
145 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) | |
146 |
|
146 | |||
147 | self.shell.set_next_input(contents) |
|
147 | self.shell.set_next_input(contents) | |
148 |
|
148 | |||
149 | def _find_edit_target(self, args, opts, last_call): |
|
149 | def _find_edit_target(self, args, opts, last_call): | |
150 | """Utility method used by magic_edit to find what to edit.""" |
|
150 | """Utility method used by magic_edit to find what to edit.""" | |
151 |
|
151 | |||
152 | def make_filename(arg): |
|
152 | def make_filename(arg): | |
153 | "Make a filename from the given args" |
|
153 | "Make a filename from the given args" | |
154 | arg = unquote_filename(arg) |
|
154 | arg = unquote_filename(arg) | |
155 | try: |
|
155 | try: | |
156 | filename = get_py_filename(arg) |
|
156 | filename = get_py_filename(arg) | |
157 | except IOError: |
|
157 | except IOError: | |
158 | # If it ends with .py but doesn't already exist, assume we want |
|
158 | # If it ends with .py but doesn't already exist, assume we want | |
159 | # a new file. |
|
159 | # a new file. | |
160 | if arg.endswith('.py'): |
|
160 | if arg.endswith('.py'): | |
161 | filename = arg |
|
161 | filename = arg | |
162 | else: |
|
162 | else: | |
163 | filename = None |
|
163 | filename = None | |
164 | return filename |
|
164 | return filename | |
165 |
|
165 | |||
166 | # Set a few locals from the options for convenience: |
|
166 | # Set a few locals from the options for convenience: | |
167 | opts_prev = 'p' in opts |
|
167 | opts_prev = 'p' in opts | |
168 | opts_raw = 'r' in opts |
|
168 | opts_raw = 'r' in opts | |
169 |
|
169 | |||
170 | # custom exceptions |
|
170 | # custom exceptions | |
171 | class DataIsObject(Exception): pass |
|
171 | class DataIsObject(Exception): pass | |
172 |
|
172 | |||
173 | # Default line number value |
|
173 | # Default line number value | |
174 | lineno = opts.get('n',None) |
|
174 | lineno = opts.get('n',None) | |
175 |
|
175 | |||
176 | if opts_prev: |
|
176 | if opts_prev: | |
177 | args = '_%s' % last_call[0] |
|
177 | args = '_%s' % last_call[0] | |
178 | if not self.shell.user_ns.has_key(args): |
|
178 | if not self.shell.user_ns.has_key(args): | |
179 | args = last_call[1] |
|
179 | args = last_call[1] | |
180 |
|
180 | |||
181 | # use last_call to remember the state of the previous call, but don't |
|
181 | # use last_call to remember the state of the previous call, but don't | |
182 | # let it be clobbered by successive '-p' calls. |
|
182 | # let it be clobbered by successive '-p' calls. | |
183 | try: |
|
183 | try: | |
184 | last_call[0] = self.shell.displayhook.prompt_count |
|
184 | last_call[0] = self.shell.displayhook.prompt_count | |
185 | if not opts_prev: |
|
185 | if not opts_prev: | |
186 | last_call[1] = args |
|
186 | last_call[1] = args | |
187 | except: |
|
187 | except: | |
188 | pass |
|
188 | pass | |
189 |
|
189 | |||
190 | # by default this is done with temp files, except when the given |
|
190 | # by default this is done with temp files, except when the given | |
191 | # arg is a filename |
|
191 | # arg is a filename | |
192 | use_temp = True |
|
192 | use_temp = True | |
193 |
|
193 | |||
194 | data = '' |
|
194 | data = '' | |
195 |
|
195 | |||
196 | # First, see if the arguments should be a filename. |
|
196 | # First, see if the arguments should be a filename. | |
197 | filename = make_filename(args) |
|
197 | filename = make_filename(args) | |
198 | if filename: |
|
198 | if filename: | |
199 | use_temp = False |
|
199 | use_temp = False | |
200 | elif args: |
|
200 | elif args: | |
201 | # Mode where user specifies ranges of lines, like in %macro. |
|
201 | # Mode where user specifies ranges of lines, like in %macro. | |
202 | data = self.shell.extract_input_lines(args, opts_raw) |
|
202 | data = self.shell.extract_input_lines(args, opts_raw) | |
203 | if not data: |
|
203 | if not data: | |
204 | try: |
|
204 | try: | |
205 | # Load the parameter given as a variable. If not a string, |
|
205 | # Load the parameter given as a variable. If not a string, | |
206 | # process it as an object instead (below) |
|
206 | # process it as an object instead (below) | |
207 |
|
207 | |||
208 | #print '*** args',args,'type',type(args) # dbg |
|
208 | #print '*** args',args,'type',type(args) # dbg | |
209 | data = eval(args, self.shell.user_ns) |
|
209 | data = eval(args, self.shell.user_ns) | |
210 | if not isinstance(data, basestring): |
|
210 | if not isinstance(data, basestring): | |
211 | raise DataIsObject |
|
211 | raise DataIsObject | |
212 |
|
212 | |||
213 | except (NameError,SyntaxError): |
|
213 | except (NameError,SyntaxError): | |
214 | # given argument is not a variable, try as a filename |
|
214 | # given argument is not a variable, try as a filename | |
215 | filename = make_filename(args) |
|
215 | filename = make_filename(args) | |
216 | if filename is None: |
|
216 | if filename is None: | |
217 | warn("Argument given (%s) can't be found as a variable " |
|
217 | warn("Argument given (%s) can't be found as a variable " | |
218 | "or as a filename." % args) |
|
218 | "or as a filename." % args) | |
219 | return |
|
219 | return | |
220 | use_temp = False |
|
220 | use_temp = False | |
221 |
|
221 | |||
222 | except DataIsObject: |
|
222 | except DataIsObject: | |
223 | # macros have a special edit function |
|
223 | # macros have a special edit function | |
224 | if isinstance(data, Macro): |
|
224 | if isinstance(data, Macro): | |
225 | raise MacroToEdit(data) |
|
225 | raise MacroToEdit(data) | |
226 |
|
226 | |||
227 | # For objects, try to edit the file where they are defined |
|
227 | # For objects, try to edit the file where they are defined | |
228 | try: |
|
228 | try: | |
229 | filename = inspect.getabsfile(data) |
|
229 | filename = inspect.getabsfile(data) | |
230 | if 'fakemodule' in filename.lower() and \ |
|
230 | if 'fakemodule' in filename.lower() and \ | |
231 | inspect.isclass(data): |
|
231 | inspect.isclass(data): | |
232 | # class created by %edit? Try to find source |
|
232 | # class created by %edit? Try to find source | |
233 | # by looking for method definitions instead, the |
|
233 | # by looking for method definitions instead, the | |
234 | # __module__ in those classes is FakeModule. |
|
234 | # __module__ in those classes is FakeModule. | |
235 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
235 | attrs = [getattr(data, aname) for aname in dir(data)] | |
236 | for attr in attrs: |
|
236 | for attr in attrs: | |
237 | if not inspect.ismethod(attr): |
|
237 | if not inspect.ismethod(attr): | |
238 | continue |
|
238 | continue | |
239 | filename = inspect.getabsfile(attr) |
|
239 | filename = inspect.getabsfile(attr) | |
240 | if filename and \ |
|
240 | if filename and \ | |
241 | 'fakemodule' not in filename.lower(): |
|
241 | 'fakemodule' not in filename.lower(): | |
242 | # change the attribute to be the edit |
|
242 | # change the attribute to be the edit | |
243 | # target instead |
|
243 | # target instead | |
244 | data = attr |
|
244 | data = attr | |
245 | break |
|
245 | break | |
246 |
|
246 | |||
247 | datafile = 1 |
|
247 | datafile = 1 | |
248 | except TypeError: |
|
248 | except TypeError: | |
249 | filename = make_filename(args) |
|
249 | filename = make_filename(args) | |
250 | datafile = 1 |
|
250 | datafile = 1 | |
251 | warn('Could not find file where `%s` is defined.\n' |
|
251 | warn('Could not find file where `%s` is defined.\n' | |
252 | 'Opening a file named `%s`' % (args,filename)) |
|
252 | 'Opening a file named `%s`' % (args, filename)) | |
253 | # Now, make sure we can actually read the source (if it was |
|
253 | # Now, make sure we can actually read the source (if it was | |
254 | # in a temp file it's gone by now). |
|
254 | # in a temp file it's gone by now). | |
255 | if datafile: |
|
255 | if datafile: | |
256 | try: |
|
256 | try: | |
257 | if lineno is None: |
|
257 | if lineno is None: | |
258 | lineno = inspect.getsourcelines(data)[1] |
|
258 | lineno = inspect.getsourcelines(data)[1] | |
259 | except IOError: |
|
259 | except IOError: | |
260 | filename = make_filename(args) |
|
260 | filename = make_filename(args) | |
261 | if filename is None: |
|
261 | if filename is None: | |
262 |
warn('The file `%s` where `%s` was defined |
|
262 | warn('The file `%s` where `%s` was defined ' | |
263 | 'be read.' % (filename,data)) |
|
263 | 'cannot be read.' % (filename, data)) | |
264 | return |
|
264 | return | |
265 | use_temp = False |
|
265 | use_temp = False | |
266 |
|
266 | |||
267 | if use_temp: |
|
267 | if use_temp: | |
268 | filename = self.shell.mktempfile(data) |
|
268 | filename = self.shell.mktempfile(data) | |
269 | print 'IPython will make a temporary file named:',filename |
|
269 | print 'IPython will make a temporary file named:',filename | |
270 |
|
270 | |||
271 | return filename, lineno, use_temp |
|
271 | return filename, lineno, use_temp | |
272 |
|
272 | |||
273 | def _edit_macro(self,mname,macro): |
|
273 | def _edit_macro(self,mname,macro): | |
274 | """open an editor with the macro data in a file""" |
|
274 | """open an editor with the macro data in a file""" | |
275 | filename = self.shell.mktempfile(macro.value) |
|
275 | filename = self.shell.mktempfile(macro.value) | |
276 | self.shell.hooks.editor(filename) |
|
276 | self.shell.hooks.editor(filename) | |
277 |
|
277 | |||
278 | # and make a new macro object, to replace the old one |
|
278 | # and make a new macro object, to replace the old one | |
279 | mfile = open(filename) |
|
279 | mfile = open(filename) | |
280 | mvalue = mfile.read() |
|
280 | mvalue = mfile.read() | |
281 | mfile.close() |
|
281 | mfile.close() | |
282 | self.shell.user_ns[mname] = Macro(mvalue) |
|
282 | self.shell.user_ns[mname] = Macro(mvalue) | |
283 |
|
283 | |||
284 | @line_magic |
|
284 | @line_magic | |
285 | def ed(self, parameter_s=''): |
|
285 | def ed(self, parameter_s=''): | |
286 | """Alias to %edit.""" |
|
286 | """Alias to %edit.""" | |
287 | return self.edit(parameter_s) |
|
287 | return self.edit(parameter_s) | |
288 |
|
288 | |||
289 | @skip_doctest |
|
289 | @skip_doctest | |
290 | @line_magic |
|
290 | @line_magic | |
291 | def edit(self, parameter_s='',last_call=['','']): |
|
291 | def edit(self, parameter_s='',last_call=['','']): | |
292 | """Bring up an editor and execute the resulting code. |
|
292 | """Bring up an editor and execute the resulting code. | |
293 |
|
293 | |||
294 | Usage: |
|
294 | Usage: | |
295 | %edit [options] [args] |
|
295 | %edit [options] [args] | |
296 |
|
296 | |||
297 | %edit runs IPython's editor hook. The default version of this hook is |
|
297 | %edit runs IPython's editor hook. The default version of this hook is | |
298 | set to call the editor specified by your $EDITOR environment variable. |
|
298 | set to call the editor specified by your $EDITOR environment variable. | |
299 | If this isn't found, it will default to vi under Linux/Unix and to |
|
299 | If this isn't found, it will default to vi under Linux/Unix and to | |
300 | notepad under Windows. See the end of this docstring for how to change |
|
300 | notepad under Windows. See the end of this docstring for how to change | |
301 | the editor hook. |
|
301 | the editor hook. | |
302 |
|
302 | |||
303 | You can also set the value of this editor via the |
|
303 | You can also set the value of this editor via the | |
304 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
304 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
305 | This is useful if you wish to use a different editor from your typical |
|
305 | This is useful if you wish to use a different editor from your typical | |
306 | default with IPython (and for Windows users who typically don't set |
|
306 | default with IPython (and for Windows users who typically don't set | |
307 | environment variables). |
|
307 | environment variables). | |
308 |
|
308 | |||
309 | This command allows you to conveniently edit multi-line code right in |
|
309 | This command allows you to conveniently edit multi-line code right in | |
310 | your IPython session. |
|
310 | your IPython session. | |
311 |
|
311 | |||
312 | If called without arguments, %edit opens up an empty editor with a |
|
312 | If called without arguments, %edit opens up an empty editor with a | |
313 | temporary file and will execute the contents of this file when you |
|
313 | temporary file and will execute the contents of this file when you | |
314 | close it (don't forget to save it!). |
|
314 | close it (don't forget to save it!). | |
315 |
|
315 | |||
316 |
|
316 | |||
317 | Options: |
|
317 | Options: | |
318 |
|
318 | |||
319 | -n <number>: open the editor at a specified line number. By default, |
|
319 | -n <number>: open the editor at a specified line number. By default, | |
320 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
320 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
321 | you can configure this by providing your own modified hook if your |
|
321 | you can configure this by providing your own modified hook if your | |
322 | favorite editor supports line-number specifications with a different |
|
322 | favorite editor supports line-number specifications with a different | |
323 | syntax. |
|
323 | syntax. | |
324 |
|
324 | |||
325 | -p: this will call the editor with the same data as the previous time |
|
325 | -p: this will call the editor with the same data as the previous time | |
326 | it was used, regardless of how long ago (in your current session) it |
|
326 | it was used, regardless of how long ago (in your current session) it | |
327 | was. |
|
327 | was. | |
328 |
|
328 | |||
329 | -r: use 'raw' input. This option only applies to input taken from the |
|
329 | -r: use 'raw' input. This option only applies to input taken from the | |
330 | user's history. By default, the 'processed' history is used, so that |
|
330 | user's history. By default, the 'processed' history is used, so that | |
331 | magics are loaded in their transformed version to valid Python. If |
|
331 | magics are loaded in their transformed version to valid Python. If | |
332 | this option is given, the raw input as typed as the command line is |
|
332 | this option is given, the raw input as typed as the command line is | |
333 | used instead. When you exit the editor, it will be executed by |
|
333 | used instead. When you exit the editor, it will be executed by | |
334 | IPython's own processor. |
|
334 | IPython's own processor. | |
335 |
|
335 | |||
336 | -x: do not execute the edited code immediately upon exit. This is |
|
336 | -x: do not execute the edited code immediately upon exit. This is | |
337 | mainly useful if you are editing programs which need to be called with |
|
337 | mainly useful if you are editing programs which need to be called with | |
338 | command line arguments, which you can then do using %run. |
|
338 | command line arguments, which you can then do using %run. | |
339 |
|
339 | |||
340 |
|
340 | |||
341 | Arguments: |
|
341 | Arguments: | |
342 |
|
342 | |||
343 | If arguments are given, the following possibilities exist: |
|
343 | If arguments are given, the following possibilities exist: | |
344 |
|
344 | |||
345 | - If the argument is a filename, IPython will load that into the |
|
345 | - If the argument is a filename, IPython will load that into the | |
346 | editor. It will execute its contents with execfile() when you exit, |
|
346 | editor. It will execute its contents with execfile() when you exit, | |
347 | loading any code in the file into your interactive namespace. |
|
347 | loading any code in the file into your interactive namespace. | |
348 |
|
348 | |||
349 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
349 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
350 | The syntax is the same as in the %history magic. |
|
350 | The syntax is the same as in the %history magic. | |
351 |
|
351 | |||
352 | - If the argument is a string variable, its contents are loaded |
|
352 | - If the argument is a string variable, its contents are loaded | |
353 | into the editor. You can thus edit any string which contains |
|
353 | into the editor. You can thus edit any string which contains | |
354 | python code (including the result of previous edits). |
|
354 | python code (including the result of previous edits). | |
355 |
|
355 | |||
356 | - If the argument is the name of an object (other than a string), |
|
356 | - If the argument is the name of an object (other than a string), | |
357 | IPython will try to locate the file where it was defined and open the |
|
357 | IPython will try to locate the file where it was defined and open the | |
358 | editor at the point where it is defined. You can use `%edit function` |
|
358 | editor at the point where it is defined. You can use `%edit function` | |
359 | to load an editor exactly at the point where 'function' is defined, |
|
359 | to load an editor exactly at the point where 'function' is defined, | |
360 | edit it and have the file be executed automatically. |
|
360 | edit it and have the file be executed automatically. | |
361 |
|
361 | |||
362 | - If the object is a macro (see %macro for details), this opens up your |
|
362 | - If the object is a macro (see %macro for details), this opens up your | |
363 | specified editor with a temporary file containing the macro's data. |
|
363 | specified editor with a temporary file containing the macro's data. | |
364 | Upon exit, the macro is reloaded with the contents of the file. |
|
364 | Upon exit, the macro is reloaded with the contents of the file. | |
365 |
|
365 | |||
366 | Note: opening at an exact line is only supported under Unix, and some |
|
366 | Note: opening at an exact line is only supported under Unix, and some | |
367 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
367 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
368 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
368 | '+NUMBER' parameter necessary for this feature. Good editors like | |
369 | (X)Emacs, vi, jed, pico and joe all do. |
|
369 | (X)Emacs, vi, jed, pico and joe all do. | |
370 |
|
370 | |||
371 | After executing your code, %edit will return as output the code you |
|
371 | After executing your code, %edit will return as output the code you | |
372 | typed in the editor (except when it was an existing file). This way |
|
372 | typed in the editor (except when it was an existing file). This way | |
373 | you can reload the code in further invocations of %edit as a variable, |
|
373 | you can reload the code in further invocations of %edit as a variable, | |
374 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
374 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
375 | the output. |
|
375 | the output. | |
376 |
|
376 | |||
377 | Note that %edit is also available through the alias %ed. |
|
377 | Note that %edit is also available through the alias %ed. | |
378 |
|
378 | |||
379 | This is an example of creating a simple function inside the editor and |
|
379 | This is an example of creating a simple function inside the editor and | |
380 | then modifying it. First, start up the editor:: |
|
380 | then modifying it. First, start up the editor:: | |
381 |
|
381 | |||
382 | In [1]: ed |
|
382 | In [1]: ed | |
383 | Editing... done. Executing edited code... |
|
383 | Editing... done. Executing edited code... | |
384 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
384 | Out[1]: 'def foo():\\n print "foo() was defined in an editing | |
385 | session"\\n' |
|
385 | session"\\n' | |
386 |
|
386 | |||
387 | We can then call the function foo():: |
|
387 | We can then call the function foo():: | |
388 |
|
388 | |||
389 | In [2]: foo() |
|
389 | In [2]: foo() | |
390 | foo() was defined in an editing session |
|
390 | foo() was defined in an editing session | |
391 |
|
391 | |||
392 | Now we edit foo. IPython automatically loads the editor with the |
|
392 | Now we edit foo. IPython automatically loads the editor with the | |
393 | (temporary) file where foo() was previously defined:: |
|
393 | (temporary) file where foo() was previously defined:: | |
394 |
|
394 | |||
395 | In [3]: ed foo |
|
395 | In [3]: ed foo | |
396 | Editing... done. Executing edited code... |
|
396 | Editing... done. Executing edited code... | |
397 |
|
397 | |||
398 | And if we call foo() again we get the modified version:: |
|
398 | And if we call foo() again we get the modified version:: | |
399 |
|
399 | |||
400 | In [4]: foo() |
|
400 | In [4]: foo() | |
401 | foo() has now been changed! |
|
401 | foo() has now been changed! | |
402 |
|
402 | |||
403 | Here is an example of how to edit a code snippet successive |
|
403 | Here is an example of how to edit a code snippet successive | |
404 | times. First we call the editor:: |
|
404 | times. First we call the editor:: | |
405 |
|
405 | |||
406 | In [5]: ed |
|
406 | In [5]: ed | |
407 | Editing... done. Executing edited code... |
|
407 | Editing... done. Executing edited code... | |
408 | hello |
|
408 | hello | |
409 | Out[5]: "print 'hello'\\n" |
|
409 | Out[5]: "print 'hello'\\n" | |
410 |
|
410 | |||
411 | Now we call it again with the previous output (stored in _):: |
|
411 | Now we call it again with the previous output (stored in _):: | |
412 |
|
412 | |||
413 | In [6]: ed _ |
|
413 | In [6]: ed _ | |
414 | Editing... done. Executing edited code... |
|
414 | Editing... done. Executing edited code... | |
415 | hello world |
|
415 | hello world | |
416 | Out[6]: "print 'hello world'\\n" |
|
416 | Out[6]: "print 'hello world'\\n" | |
417 |
|
417 | |||
418 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
418 | Now we call it with the output #8 (stored in _8, also as Out[8]):: | |
419 |
|
419 | |||
420 | In [7]: ed _8 |
|
420 | In [7]: ed _8 | |
421 | Editing... done. Executing edited code... |
|
421 | Editing... done. Executing edited code... | |
422 | hello again |
|
422 | hello again | |
423 | Out[7]: "print 'hello again'\\n" |
|
423 | Out[7]: "print 'hello again'\\n" | |
424 |
|
424 | |||
425 |
|
425 | |||
426 | Changing the default editor hook: |
|
426 | Changing the default editor hook: | |
427 |
|
427 | |||
428 | If you wish to write your own editor hook, you can put it in a |
|
428 | If you wish to write your own editor hook, you can put it in a | |
429 | configuration file which you load at startup time. The default hook |
|
429 | configuration file which you load at startup time. The default hook | |
430 | is defined in the IPython.core.hooks module, and you can use that as a |
|
430 | is defined in the IPython.core.hooks module, and you can use that as a | |
431 | starting example for further modifications. That file also has |
|
431 | starting example for further modifications. That file also has | |
432 | general instructions on how to set a new hook for use once you've |
|
432 | general instructions on how to set a new hook for use once you've | |
433 | defined it.""" |
|
433 | defined it.""" | |
434 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
434 | opts,args = self.parse_options(parameter_s,'prxn:') | |
435 |
|
435 | |||
436 | try: |
|
436 | try: | |
437 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
437 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
438 | except MacroToEdit as e: |
|
438 | except MacroToEdit as e: | |
439 | self._edit_macro(args, e.args[0]) |
|
439 | self._edit_macro(args, e.args[0]) | |
440 | return |
|
440 | return | |
441 |
|
441 | |||
442 | # do actual editing here |
|
442 | # do actual editing here | |
443 | print 'Editing...', |
|
443 | print 'Editing...', | |
444 | sys.stdout.flush() |
|
444 | sys.stdout.flush() | |
445 | try: |
|
445 | try: | |
446 | # Quote filenames that may have spaces in them |
|
446 | # Quote filenames that may have spaces in them | |
447 | if ' ' in filename: |
|
447 | if ' ' in filename: | |
448 | filename = "'%s'" % filename |
|
448 | filename = "'%s'" % filename | |
449 | self.shell.hooks.editor(filename,lineno) |
|
449 | self.shell.hooks.editor(filename,lineno) | |
450 | except TryNext: |
|
450 | except TryNext: | |
451 | warn('Could not open editor') |
|
451 | warn('Could not open editor') | |
452 | return |
|
452 | return | |
453 |
|
453 | |||
454 | # XXX TODO: should this be generalized for all string vars? |
|
454 | # XXX TODO: should this be generalized for all string vars? | |
455 | # For now, this is special-cased to blocks created by cpaste |
|
455 | # For now, this is special-cased to blocks created by cpaste | |
456 | if args.strip() == 'pasted_block': |
|
456 | if args.strip() == 'pasted_block': | |
457 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
457 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
458 |
|
458 | |||
459 | if 'x' in opts: # -x prevents actual execution |
|
459 | if 'x' in opts: # -x prevents actual execution | |
460 |
|
460 | |||
461 | else: |
|
461 | else: | |
462 | print 'done. Executing edited code...' |
|
462 | print 'done. Executing edited code...' | |
463 | if 'r' in opts: # Untranslated IPython code |
|
463 | if 'r' in opts: # Untranslated IPython code | |
464 | self.shell.run_cell(file_read(filename), |
|
464 | self.shell.run_cell(file_read(filename), | |
465 | store_history=False) |
|
465 | store_history=False) | |
466 | else: |
|
466 | else: | |
467 | self.shell.safe_execfile(filename, self.shell.user_ns, |
|
467 | self.shell.safe_execfile(filename, self.shell.user_ns, | |
468 | self.shell.user_ns) |
|
468 | self.shell.user_ns) | |
469 |
|
469 | |||
470 | if is_temp: |
|
470 | if is_temp: | |
471 | try: |
|
471 | try: | |
472 | return open(filename).read() |
|
472 | return open(filename).read() | |
473 | except IOError,msg: |
|
473 | except IOError,msg: | |
474 | if msg.filename == filename: |
|
474 | if msg.filename == filename: | |
475 | warn('File not found. Did you forget to save?') |
|
475 | warn('File not found. Did you forget to save?') | |
476 | return |
|
476 | return | |
477 | else: |
|
477 | else: | |
478 | self.shell.showtraceback() |
|
478 | self.shell.showtraceback() |
@@ -1,702 +1,702 b'' | |||||
1 | """Implementation of namespace-related magic functions. |
|
1 | """Implementation of namespace-related magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import gc |
|
16 | import gc | |
17 | import re |
|
17 | import re | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | # Our own packages |
|
20 | # Our own packages | |
21 | from IPython.core import page |
|
21 | from IPython.core import page | |
22 | from IPython.core.error import StdinNotImplementedError |
|
22 | from IPython.core.error import StdinNotImplementedError | |
23 | from IPython.core.magic import Magics, magics_class, line_magic |
|
23 | from IPython.core.magic import Magics, magics_class, line_magic | |
24 | from IPython.testing.skipdoctest import skip_doctest |
|
24 | from IPython.testing.skipdoctest import skip_doctest | |
25 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
25 | from IPython.utils.encoding import DEFAULT_ENCODING | |
26 | from IPython.utils.path import get_py_filename |
|
26 | from IPython.utils.path import get_py_filename | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Magic implementation classes |
|
29 | # Magic implementation classes | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | @magics_class |
|
32 | @magics_class | |
33 | class NamespaceMagics(Magics): |
|
33 | class NamespaceMagics(Magics): | |
34 | """Magics to manage various aspects of the user's namespace. |
|
34 | """Magics to manage various aspects of the user's namespace. | |
35 |
|
35 | |||
36 | These include listing variables, introspecting into them, etc. |
|
36 | These include listing variables, introspecting into them, etc. | |
37 | """ |
|
37 | """ | |
38 |
|
38 | |||
39 | @line_magic |
|
39 | @line_magic | |
40 | def pinfo(self, parameter_s='', namespaces=None): |
|
40 | def pinfo(self, parameter_s='', namespaces=None): | |
41 | """Provide detailed information about an object. |
|
41 | """Provide detailed information about an object. | |
42 |
|
42 | |||
43 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
43 | '%pinfo object' is just a synonym for object? or ?object.""" | |
44 |
|
44 | |||
45 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
45 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
48 | # detail_level: 0 -> obj? , 1 -> obj?? | |
49 | detail_level = 0 |
|
49 | detail_level = 0 | |
50 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
50 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
51 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
51 | # happen if the user types 'pinfo foo?' at the cmd line. | |
52 | pinfo,qmark1,oname,qmark2 = \ |
|
52 | pinfo,qmark1,oname,qmark2 = \ | |
53 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
53 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
54 | if pinfo or qmark1 or qmark2: |
|
54 | if pinfo or qmark1 or qmark2: | |
55 | detail_level = 1 |
|
55 | detail_level = 1 | |
56 | if "*" in oname: |
|
56 | if "*" in oname: | |
57 | self.psearch(oname) |
|
57 | self.psearch(oname) | |
58 | else: |
|
58 | else: | |
59 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
59 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
60 | namespaces=namespaces) |
|
60 | namespaces=namespaces) | |
61 |
|
61 | |||
62 | @line_magic |
|
62 | @line_magic | |
63 | def pinfo2(self, parameter_s='', namespaces=None): |
|
63 | def pinfo2(self, parameter_s='', namespaces=None): | |
64 | """Provide extra detailed information about an object. |
|
64 | """Provide extra detailed information about an object. | |
65 |
|
65 | |||
66 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
66 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
67 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
67 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
68 | namespaces=namespaces) |
|
68 | namespaces=namespaces) | |
69 |
|
69 | |||
70 | @skip_doctest |
|
70 | @skip_doctest | |
71 | @line_magic |
|
71 | @line_magic | |
72 | def pdef(self, parameter_s='', namespaces=None): |
|
72 | def pdef(self, parameter_s='', namespaces=None): | |
73 | """Print the definition header for any callable object. |
|
73 | """Print the definition header for any callable object. | |
74 |
|
74 | |||
75 | If the object is a class, print the constructor information. |
|
75 | If the object is a class, print the constructor information. | |
76 |
|
76 | |||
77 | Examples |
|
77 | Examples | |
78 | -------- |
|
78 | -------- | |
79 | :: |
|
79 | :: | |
80 |
|
80 | |||
81 | In [3]: %pdef urllib.urlopen |
|
81 | In [3]: %pdef urllib.urlopen | |
82 | urllib.urlopen(url, data=None, proxies=None) |
|
82 | urllib.urlopen(url, data=None, proxies=None) | |
83 | """ |
|
83 | """ | |
84 | self._inspect('pdef',parameter_s, namespaces) |
|
84 | self._inspect('pdef',parameter_s, namespaces) | |
85 |
|
85 | |||
86 | @line_magic |
|
86 | @line_magic | |
87 | def pdoc(self, parameter_s='', namespaces=None): |
|
87 | def pdoc(self, parameter_s='', namespaces=None): | |
88 | """Print the docstring for an object. |
|
88 | """Print the docstring for an object. | |
89 |
|
89 | |||
90 | If the given object is a class, it will print both the class and the |
|
90 | If the given object is a class, it will print both the class and the | |
91 | constructor docstrings.""" |
|
91 | constructor docstrings.""" | |
92 | self._inspect('pdoc',parameter_s, namespaces) |
|
92 | self._inspect('pdoc',parameter_s, namespaces) | |
93 |
|
93 | |||
94 | @line_magic |
|
94 | @line_magic | |
95 | def psource(self, parameter_s='', namespaces=None): |
|
95 | def psource(self, parameter_s='', namespaces=None): | |
96 | """Print (or run through pager) the source code for an object.""" |
|
96 | """Print (or run through pager) the source code for an object.""" | |
97 | self._inspect('psource',parameter_s, namespaces) |
|
97 | self._inspect('psource',parameter_s, namespaces) | |
98 |
|
98 | |||
99 | @line_magic |
|
99 | @line_magic | |
100 | def pfile(self, parameter_s=''): |
|
100 | def pfile(self, parameter_s=''): | |
101 | """Print (or run through pager) the file where an object is defined. |
|
101 | """Print (or run through pager) the file where an object is defined. | |
102 |
|
102 | |||
103 | The file opens at the line where the object definition begins. IPython |
|
103 | The file opens at the line where the object definition begins. IPython | |
104 | will honor the environment variable PAGER if set, and otherwise will |
|
104 | will honor the environment variable PAGER if set, and otherwise will | |
105 | do its best to print the file in a convenient form. |
|
105 | do its best to print the file in a convenient form. | |
106 |
|
106 | |||
107 | If the given argument is not an object currently defined, IPython will |
|
107 | If the given argument is not an object currently defined, IPython will | |
108 | try to interpret it as a filename (automatically adding a .py extension |
|
108 | try to interpret it as a filename (automatically adding a .py extension | |
109 | if needed). You can thus use %pfile as a syntax highlighting code |
|
109 | if needed). You can thus use %pfile as a syntax highlighting code | |
110 | viewer.""" |
|
110 | viewer.""" | |
111 |
|
111 | |||
112 | # first interpret argument as an object name |
|
112 | # first interpret argument as an object name | |
113 | out = self._inspect('pfile',parameter_s) |
|
113 | out = self._inspect('pfile',parameter_s) | |
114 | # if not, try the input as a filename |
|
114 | # if not, try the input as a filename | |
115 | if out == 'not found': |
|
115 | if out == 'not found': | |
116 | try: |
|
116 | try: | |
117 | filename = get_py_filename(parameter_s) |
|
117 | filename = get_py_filename(parameter_s) | |
118 | except IOError,msg: |
|
118 | except IOError,msg: | |
119 | print msg |
|
119 | print msg | |
120 | return |
|
120 | return | |
121 | page.page(self.shell.inspector.format(open(filename).read())) |
|
121 | page.page(self.shell.inspector.format(open(filename).read())) | |
122 |
|
122 | |||
123 | @line_magic |
|
123 | @line_magic | |
124 | def psearch(self, parameter_s=''): |
|
124 | def psearch(self, parameter_s=''): | |
125 | """Search for object in namespaces by wildcard. |
|
125 | """Search for object in namespaces by wildcard. | |
126 |
|
126 | |||
127 | %psearch [options] PATTERN [OBJECT TYPE] |
|
127 | %psearch [options] PATTERN [OBJECT TYPE] | |
128 |
|
128 | |||
129 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
129 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
130 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
130 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
131 | rest of the command line must be unchanged (options come first), so |
|
131 | rest of the command line must be unchanged (options come first), so | |
132 | for example the following forms are equivalent |
|
132 | for example the following forms are equivalent | |
133 |
|
133 | |||
134 | %psearch -i a* function |
|
134 | %psearch -i a* function | |
135 | -i a* function? |
|
135 | -i a* function? | |
136 | ?-i a* function |
|
136 | ?-i a* function | |
137 |
|
137 | |||
138 | Arguments: |
|
138 | Arguments: | |
139 |
|
139 | |||
140 | PATTERN |
|
140 | PATTERN | |
141 |
|
141 | |||
142 | where PATTERN is a string containing * as a wildcard similar to its |
|
142 | where PATTERN is a string containing * as a wildcard similar to its | |
143 | use in a shell. The pattern is matched in all namespaces on the |
|
143 | use in a shell. The pattern is matched in all namespaces on the | |
144 | search path. By default objects starting with a single _ are not |
|
144 | search path. By default objects starting with a single _ are not | |
145 | matched, many IPython generated objects have a single |
|
145 | matched, many IPython generated objects have a single | |
146 | underscore. The default is case insensitive matching. Matching is |
|
146 | underscore. The default is case insensitive matching. Matching is | |
147 | also done on the attributes of objects and not only on the objects |
|
147 | also done on the attributes of objects and not only on the objects | |
148 | in a module. |
|
148 | in a module. | |
149 |
|
149 | |||
150 | [OBJECT TYPE] |
|
150 | [OBJECT TYPE] | |
151 |
|
151 | |||
152 | Is the name of a python type from the types module. The name is |
|
152 | Is the name of a python type from the types module. The name is | |
153 | given in lowercase without the ending type, ex. StringType is |
|
153 | given in lowercase without the ending type, ex. StringType is | |
154 | written string. By adding a type here only objects matching the |
|
154 | written string. By adding a type here only objects matching the | |
155 | given type are matched. Using all here makes the pattern match all |
|
155 | given type are matched. Using all here makes the pattern match all | |
156 | types (this is the default). |
|
156 | types (this is the default). | |
157 |
|
157 | |||
158 | Options: |
|
158 | Options: | |
159 |
|
159 | |||
160 | -a: makes the pattern match even objects whose names start with a |
|
160 | -a: makes the pattern match even objects whose names start with a | |
161 | single underscore. These names are normally omitted from the |
|
161 | single underscore. These names are normally omitted from the | |
162 | search. |
|
162 | search. | |
163 |
|
163 | |||
164 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
164 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
165 | these options are given, the default is read from your configuration |
|
165 | these options are given, the default is read from your configuration | |
166 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
166 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
167 | If this option is not specified in your configuration file, IPython's |
|
167 | If this option is not specified in your configuration file, IPython's | |
168 | internal default is to do a case sensitive search. |
|
168 | internal default is to do a case sensitive search. | |
169 |
|
169 | |||
170 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
170 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
171 | specify can be searched in any of the following namespaces: |
|
171 | specify can be searched in any of the following namespaces: | |
172 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
172 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
173 | 'builtin' and 'user' are the search defaults. Note that you should |
|
173 | 'builtin' and 'user' are the search defaults. Note that you should | |
174 | not use quotes when specifying namespaces. |
|
174 | not use quotes when specifying namespaces. | |
175 |
|
175 | |||
176 | 'Builtin' contains the python module builtin, 'user' contains all |
|
176 | 'Builtin' contains the python module builtin, 'user' contains all | |
177 | user data, 'alias' only contain the shell aliases and no python |
|
177 | user data, 'alias' only contain the shell aliases and no python | |
178 | objects, 'internal' contains objects used by IPython. The |
|
178 | objects, 'internal' contains objects used by IPython. The | |
179 | 'user_global' namespace is only used by embedded IPython instances, |
|
179 | 'user_global' namespace is only used by embedded IPython instances, | |
180 | and it contains module-level globals. You can add namespaces to the |
|
180 | and it contains module-level globals. You can add namespaces to the | |
181 | search with -s or exclude them with -e (these options can be given |
|
181 | search with -s or exclude them with -e (these options can be given | |
182 | more than once). |
|
182 | more than once). | |
183 |
|
183 | |||
184 | Examples |
|
184 | Examples | |
185 | -------- |
|
185 | -------- | |
186 | :: |
|
186 | :: | |
187 |
|
187 | |||
188 | %psearch a* -> objects beginning with an a |
|
188 | %psearch a* -> objects beginning with an a | |
189 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
189 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
190 | %psearch a* function -> all functions beginning with an a |
|
190 | %psearch a* function -> all functions beginning with an a | |
191 | %psearch re.e* -> objects beginning with an e in module re |
|
191 | %psearch re.e* -> objects beginning with an e in module re | |
192 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
192 | %psearch r*.e* -> objects that start with e in modules starting in r | |
193 | %psearch r*.* string -> all strings in modules beginning with r |
|
193 | %psearch r*.* string -> all strings in modules beginning with r | |
194 |
|
194 | |||
195 | Case sensitive search:: |
|
195 | Case sensitive search:: | |
196 |
|
196 | |||
197 | %psearch -c a* list all object beginning with lower case a |
|
197 | %psearch -c a* list all object beginning with lower case a | |
198 |
|
198 | |||
199 | Show objects beginning with a single _:: |
|
199 | Show objects beginning with a single _:: | |
200 |
|
200 | |||
201 | %psearch -a _* list objects beginning with a single underscore |
|
201 | %psearch -a _* list objects beginning with a single underscore | |
202 | """ |
|
202 | """ | |
203 | try: |
|
203 | try: | |
204 | parameter_s.encode('ascii') |
|
204 | parameter_s.encode('ascii') | |
205 | except UnicodeEncodeError: |
|
205 | except UnicodeEncodeError: | |
206 | print 'Python identifiers can only contain ascii characters.' |
|
206 | print 'Python identifiers can only contain ascii characters.' | |
207 | return |
|
207 | return | |
208 |
|
208 | |||
209 | # default namespaces to be searched |
|
209 | # default namespaces to be searched | |
210 | def_search = ['user_local', 'user_global', 'builtin'] |
|
210 | def_search = ['user_local', 'user_global', 'builtin'] | |
211 |
|
211 | |||
212 | # Process options/args |
|
212 | # Process options/args | |
213 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
213 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
214 | opt = opts.get |
|
214 | opt = opts.get | |
215 | shell = self.shell |
|
215 | shell = self.shell | |
216 | psearch = shell.inspector.psearch |
|
216 | psearch = shell.inspector.psearch | |
217 |
|
217 | |||
218 | # select case options |
|
218 | # select case options | |
219 | if opts.has_key('i'): |
|
219 | if opts.has_key('i'): | |
220 | ignore_case = True |
|
220 | ignore_case = True | |
221 | elif opts.has_key('c'): |
|
221 | elif opts.has_key('c'): | |
222 | ignore_case = False |
|
222 | ignore_case = False | |
223 | else: |
|
223 | else: | |
224 | ignore_case = not shell.wildcards_case_sensitive |
|
224 | ignore_case = not shell.wildcards_case_sensitive | |
225 |
|
225 | |||
226 | # Build list of namespaces to search from user options |
|
226 | # Build list of namespaces to search from user options | |
227 | def_search.extend(opt('s',[])) |
|
227 | def_search.extend(opt('s',[])) | |
228 | ns_exclude = ns_exclude=opt('e',[]) |
|
228 | ns_exclude = ns_exclude=opt('e',[]) | |
229 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
229 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
230 |
|
230 | |||
231 | # Call the actual search |
|
231 | # Call the actual search | |
232 | try: |
|
232 | try: | |
233 | psearch(args,shell.ns_table,ns_search, |
|
233 | psearch(args,shell.ns_table,ns_search, | |
234 | show_all=opt('a'),ignore_case=ignore_case) |
|
234 | show_all=opt('a'),ignore_case=ignore_case) | |
235 | except: |
|
235 | except: | |
236 | shell.showtraceback() |
|
236 | shell.showtraceback() | |
237 |
|
237 | |||
238 | @skip_doctest |
|
238 | @skip_doctest | |
239 | @line_magic |
|
239 | @line_magic | |
240 | def who_ls(self, parameter_s=''): |
|
240 | def who_ls(self, parameter_s=''): | |
241 | """Return a sorted list of all interactive variables. |
|
241 | """Return a sorted list of all interactive variables. | |
242 |
|
242 | |||
243 | If arguments are given, only variables of types matching these |
|
243 | If arguments are given, only variables of types matching these | |
244 | arguments are returned. |
|
244 | arguments are returned. | |
245 |
|
245 | |||
246 | Examples |
|
246 | Examples | |
247 | -------- |
|
247 | -------- | |
248 |
|
248 | |||
249 | Define two variables and list them with who_ls:: |
|
249 | Define two variables and list them with who_ls:: | |
250 |
|
250 | |||
251 | In [1]: alpha = 123 |
|
251 | In [1]: alpha = 123 | |
252 |
|
252 | |||
253 | In [2]: beta = 'test' |
|
253 | In [2]: beta = 'test' | |
254 |
|
254 | |||
255 | In [3]: %who_ls |
|
255 | In [3]: %who_ls | |
256 | Out[3]: ['alpha', 'beta'] |
|
256 | Out[3]: ['alpha', 'beta'] | |
257 |
|
257 | |||
258 | In [4]: %who_ls int |
|
258 | In [4]: %who_ls int | |
259 | Out[4]: ['alpha'] |
|
259 | Out[4]: ['alpha'] | |
260 |
|
260 | |||
261 | In [5]: %who_ls str |
|
261 | In [5]: %who_ls str | |
262 | Out[5]: ['beta'] |
|
262 | Out[5]: ['beta'] | |
263 | """ |
|
263 | """ | |
264 |
|
264 | |||
265 | user_ns = self.shell.user_ns |
|
265 | user_ns = self.shell.user_ns | |
266 | user_ns_hidden = self.shell.user_ns_hidden |
|
266 | user_ns_hidden = self.shell.user_ns_hidden | |
267 | out = [ i for i in user_ns |
|
267 | out = [ i for i in user_ns | |
268 | if not i.startswith('_') \ |
|
268 | if not i.startswith('_') \ | |
269 | and not i in user_ns_hidden ] |
|
269 | and not i in user_ns_hidden ] | |
270 |
|
270 | |||
271 | typelist = parameter_s.split() |
|
271 | typelist = parameter_s.split() | |
272 | if typelist: |
|
272 | if typelist: | |
273 | typeset = set(typelist) |
|
273 | typeset = set(typelist) | |
274 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
274 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
275 |
|
275 | |||
276 | out.sort() |
|
276 | out.sort() | |
277 | return out |
|
277 | return out | |
278 |
|
278 | |||
279 | @skip_doctest |
|
279 | @skip_doctest | |
280 | @line_magic |
|
280 | @line_magic | |
281 | def who(self, parameter_s=''): |
|
281 | def who(self, parameter_s=''): | |
282 | """Print all interactive variables, with some minimal formatting. |
|
282 | """Print all interactive variables, with some minimal formatting. | |
283 |
|
283 | |||
284 | If any arguments are given, only variables whose type matches one of |
|
284 | If any arguments are given, only variables whose type matches one of | |
285 | these are printed. For example:: |
|
285 | these are printed. For example:: | |
286 |
|
286 | |||
287 | %who function str |
|
287 | %who function str | |
288 |
|
288 | |||
289 | will only list functions and strings, excluding all other types of |
|
289 | will only list functions and strings, excluding all other types of | |
290 | variables. To find the proper type names, simply use type(var) at a |
|
290 | variables. To find the proper type names, simply use type(var) at a | |
291 | command line to see how python prints type names. For example: |
|
291 | command line to see how python prints type names. For example: | |
292 |
|
292 | |||
293 | :: |
|
293 | :: | |
294 |
|
294 | |||
295 | In [1]: type('hello')\\ |
|
295 | In [1]: type('hello')\\ | |
296 | Out[1]: <type 'str'> |
|
296 | Out[1]: <type 'str'> | |
297 |
|
297 | |||
298 | indicates that the type name for strings is 'str'. |
|
298 | indicates that the type name for strings is 'str'. | |
299 |
|
299 | |||
300 | ``%who`` always excludes executed names loaded through your configuration |
|
300 | ``%who`` always excludes executed names loaded through your configuration | |
301 | file and things which are internal to IPython. |
|
301 | file and things which are internal to IPython. | |
302 |
|
302 | |||
303 | This is deliberate, as typically you may load many modules and the |
|
303 | This is deliberate, as typically you may load many modules and the | |
304 | purpose of %who is to show you only what you've manually defined. |
|
304 | purpose of %who is to show you only what you've manually defined. | |
305 |
|
305 | |||
306 | Examples |
|
306 | Examples | |
307 | -------- |
|
307 | -------- | |
308 |
|
308 | |||
309 | Define two variables and list them with who:: |
|
309 | Define two variables and list them with who:: | |
310 |
|
310 | |||
311 | In [1]: alpha = 123 |
|
311 | In [1]: alpha = 123 | |
312 |
|
312 | |||
313 | In [2]: beta = 'test' |
|
313 | In [2]: beta = 'test' | |
314 |
|
314 | |||
315 | In [3]: %who |
|
315 | In [3]: %who | |
316 | alpha beta |
|
316 | alpha beta | |
317 |
|
317 | |||
318 | In [4]: %who int |
|
318 | In [4]: %who int | |
319 | alpha |
|
319 | alpha | |
320 |
|
320 | |||
321 | In [5]: %who str |
|
321 | In [5]: %who str | |
322 | beta |
|
322 | beta | |
323 | """ |
|
323 | """ | |
324 |
|
324 | |||
325 | varlist = self.who_ls(parameter_s) |
|
325 | varlist = self.who_ls(parameter_s) | |
326 | if not varlist: |
|
326 | if not varlist: | |
327 | if parameter_s: |
|
327 | if parameter_s: | |
328 | print 'No variables match your requested type.' |
|
328 | print 'No variables match your requested type.' | |
329 | else: |
|
329 | else: | |
330 | print 'Interactive namespace is empty.' |
|
330 | print 'Interactive namespace is empty.' | |
331 | return |
|
331 | return | |
332 |
|
332 | |||
333 | # if we have variables, move on... |
|
333 | # if we have variables, move on... | |
334 | count = 0 |
|
334 | count = 0 | |
335 | for i in varlist: |
|
335 | for i in varlist: | |
336 | print i+'\t', |
|
336 | print i+'\t', | |
337 | count += 1 |
|
337 | count += 1 | |
338 | if count > 8: |
|
338 | if count > 8: | |
339 | count = 0 |
|
339 | count = 0 | |
340 |
|
340 | |||
341 |
|
341 | |||
342 |
|
342 | |||
343 | @skip_doctest |
|
343 | @skip_doctest | |
344 | @line_magic |
|
344 | @line_magic | |
345 | def whos(self, parameter_s=''): |
|
345 | def whos(self, parameter_s=''): | |
346 | """Like %who, but gives some extra information about each variable. |
|
346 | """Like %who, but gives some extra information about each variable. | |
347 |
|
347 | |||
348 | The same type filtering of %who can be applied here. |
|
348 | The same type filtering of %who can be applied here. | |
349 |
|
349 | |||
350 | For all variables, the type is printed. Additionally it prints: |
|
350 | For all variables, the type is printed. Additionally it prints: | |
351 |
|
351 | |||
352 | - For {},[],(): their length. |
|
352 | - For {},[],(): their length. | |
353 |
|
353 | |||
354 | - For numpy arrays, a summary with shape, number of |
|
354 | - For numpy arrays, a summary with shape, number of | |
355 | elements, typecode and size in memory. |
|
355 | elements, typecode and size in memory. | |
356 |
|
356 | |||
357 | - Everything else: a string representation, snipping their middle if |
|
357 | - Everything else: a string representation, snipping their middle if | |
358 | too long. |
|
358 | too long. | |
359 |
|
359 | |||
360 | Examples |
|
360 | Examples | |
361 | -------- |
|
361 | -------- | |
362 |
|
362 | |||
363 | Define two variables and list them with whos:: |
|
363 | Define two variables and list them with whos:: | |
364 |
|
364 | |||
365 | In [1]: alpha = 123 |
|
365 | In [1]: alpha = 123 | |
366 |
|
366 | |||
367 | In [2]: beta = 'test' |
|
367 | In [2]: beta = 'test' | |
368 |
|
368 | |||
369 | In [3]: %whos |
|
369 | In [3]: %whos | |
370 | Variable Type Data/Info |
|
370 | Variable Type Data/Info | |
371 | -------------------------------- |
|
371 | -------------------------------- | |
372 | alpha int 123 |
|
372 | alpha int 123 | |
373 | beta str test |
|
373 | beta str test | |
374 | """ |
|
374 | """ | |
375 |
|
375 | |||
376 | varnames = self.who_ls(parameter_s) |
|
376 | varnames = self.who_ls(parameter_s) | |
377 | if not varnames: |
|
377 | if not varnames: | |
378 | if parameter_s: |
|
378 | if parameter_s: | |
379 | print 'No variables match your requested type.' |
|
379 | print 'No variables match your requested type.' | |
380 | else: |
|
380 | else: | |
381 | print 'Interactive namespace is empty.' |
|
381 | print 'Interactive namespace is empty.' | |
382 | return |
|
382 | return | |
383 |
|
383 | |||
384 | # if we have variables, move on... |
|
384 | # if we have variables, move on... | |
385 |
|
385 | |||
386 | # for these types, show len() instead of data: |
|
386 | # for these types, show len() instead of data: | |
387 | seq_types = ['dict', 'list', 'tuple'] |
|
387 | seq_types = ['dict', 'list', 'tuple'] | |
388 |
|
388 | |||
389 | # for numpy arrays, display summary info |
|
389 | # for numpy arrays, display summary info | |
390 | ndarray_type = None |
|
390 | ndarray_type = None | |
391 | if 'numpy' in sys.modules: |
|
391 | if 'numpy' in sys.modules: | |
392 | try: |
|
392 | try: | |
393 | from numpy import ndarray |
|
393 | from numpy import ndarray | |
394 | except ImportError: |
|
394 | except ImportError: | |
395 | pass |
|
395 | pass | |
396 | else: |
|
396 | else: | |
397 | ndarray_type = ndarray.__name__ |
|
397 | ndarray_type = ndarray.__name__ | |
398 |
|
398 | |||
399 | # Find all variable names and types so we can figure out column sizes |
|
399 | # Find all variable names and types so we can figure out column sizes | |
400 | def get_vars(i): |
|
400 | def get_vars(i): | |
401 | return self.shell.user_ns[i] |
|
401 | return self.shell.user_ns[i] | |
402 |
|
402 | |||
403 | # some types are well known and can be shorter |
|
403 | # some types are well known and can be shorter | |
404 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
404 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
405 | def type_name(v): |
|
405 | def type_name(v): | |
406 | tn = type(v).__name__ |
|
406 | tn = type(v).__name__ | |
407 | return abbrevs.get(tn,tn) |
|
407 | return abbrevs.get(tn,tn) | |
408 |
|
408 | |||
409 | varlist = map(get_vars,varnames) |
|
409 | varlist = map(get_vars,varnames) | |
410 |
|
410 | |||
411 | typelist = [] |
|
411 | typelist = [] | |
412 | for vv in varlist: |
|
412 | for vv in varlist: | |
413 | tt = type_name(vv) |
|
413 | tt = type_name(vv) | |
414 |
|
414 | |||
415 | if tt=='instance': |
|
415 | if tt=='instance': | |
416 | typelist.append( abbrevs.get(str(vv.__class__), |
|
416 | typelist.append( abbrevs.get(str(vv.__class__), | |
417 | str(vv.__class__))) |
|
417 | str(vv.__class__))) | |
418 | else: |
|
418 | else: | |
419 | typelist.append(tt) |
|
419 | typelist.append(tt) | |
420 |
|
420 | |||
421 | # column labels and # of spaces as separator |
|
421 | # column labels and # of spaces as separator | |
422 | varlabel = 'Variable' |
|
422 | varlabel = 'Variable' | |
423 | typelabel = 'Type' |
|
423 | typelabel = 'Type' | |
424 | datalabel = 'Data/Info' |
|
424 | datalabel = 'Data/Info' | |
425 | colsep = 3 |
|
425 | colsep = 3 | |
426 | # variable format strings |
|
426 | # variable format strings | |
427 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
427 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
428 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
428 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
429 | # find the size of the columns to format the output nicely |
|
429 | # find the size of the columns to format the output nicely | |
430 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
430 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
431 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
431 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
432 | # table header |
|
432 | # table header | |
433 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
433 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
434 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
434 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
435 | # and the table itself |
|
435 | # and the table itself | |
436 | kb = 1024 |
|
436 | kb = 1024 | |
437 | Mb = 1048576 # kb**2 |
|
437 | Mb = 1048576 # kb**2 | |
438 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
438 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
439 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
439 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
440 | if vtype in seq_types: |
|
440 | if vtype in seq_types: | |
441 | print "n="+str(len(var)) |
|
441 | print "n="+str(len(var)) | |
442 | elif vtype == ndarray_type: |
|
442 | elif vtype == ndarray_type: | |
443 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
443 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
444 | if vtype==ndarray_type: |
|
444 | if vtype==ndarray_type: | |
445 | # numpy |
|
445 | # numpy | |
446 | vsize = var.size |
|
446 | vsize = var.size | |
447 | vbytes = vsize*var.itemsize |
|
447 | vbytes = vsize*var.itemsize | |
448 | vdtype = var.dtype |
|
448 | vdtype = var.dtype | |
449 |
|
449 | |||
450 | if vbytes < 100000: |
|
450 | if vbytes < 100000: | |
451 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
451 | print aformat % (vshape, vsize, vdtype, vbytes) | |
452 | else: |
|
452 | else: | |
453 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
453 | print aformat % (vshape, vsize, vdtype, vbytes), | |
454 | if vbytes < Mb: |
|
454 | if vbytes < Mb: | |
455 | print '(%s kb)' % (vbytes/kb,) |
|
455 | print '(%s kb)' % (vbytes/kb,) | |
456 | else: |
|
456 | else: | |
457 | print '(%s Mb)' % (vbytes/Mb,) |
|
457 | print '(%s Mb)' % (vbytes/Mb,) | |
458 | else: |
|
458 | else: | |
459 | try: |
|
459 | try: | |
460 | vstr = str(var) |
|
460 | vstr = str(var) | |
461 | except UnicodeEncodeError: |
|
461 | except UnicodeEncodeError: | |
462 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
462 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
463 | 'backslashreplace') |
|
463 | 'backslashreplace') | |
464 | except: |
|
464 | except: | |
465 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
465 | vstr = "<object with id %d (str() failed)>" % id(var) | |
466 | vstr = vstr.replace('\n','\\n') |
|
466 | vstr = vstr.replace('\n', '\\n') | |
467 | if len(vstr) < 50: |
|
467 | if len(vstr) < 50: | |
468 | print vstr |
|
468 | print vstr | |
469 | else: |
|
469 | else: | |
470 | print vstr[:25] + "<...>" + vstr[-25:] |
|
470 | print vstr[:25] + "<...>" + vstr[-25:] | |
471 |
|
471 | |||
472 | @line_magic |
|
472 | @line_magic | |
473 | def reset(self, parameter_s=''): |
|
473 | def reset(self, parameter_s=''): | |
474 | """Resets the namespace by removing all names defined by the user, if |
|
474 | """Resets the namespace by removing all names defined by the user, if | |
475 | called without arguments, or by removing some types of objects, such |
|
475 | called without arguments, or by removing some types of objects, such | |
476 | as everything currently in IPython's In[] and Out[] containers (see |
|
476 | as everything currently in IPython's In[] and Out[] containers (see | |
477 | the parameters for details). |
|
477 | the parameters for details). | |
478 |
|
478 | |||
479 | Parameters |
|
479 | Parameters | |
480 | ---------- |
|
480 | ---------- | |
481 | -f : force reset without asking for confirmation. |
|
481 | -f : force reset without asking for confirmation. | |
482 |
|
482 | |||
483 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
483 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
484 | References to objects may be kept. By default (without this option), |
|
484 | References to objects may be kept. By default (without this option), | |
485 | we do a 'hard' reset, giving you a new session and removing all |
|
485 | we do a 'hard' reset, giving you a new session and removing all | |
486 | references to objects from the current session. |
|
486 | references to objects from the current session. | |
487 |
|
487 | |||
488 | in : reset input history |
|
488 | in : reset input history | |
489 |
|
489 | |||
490 | out : reset output history |
|
490 | out : reset output history | |
491 |
|
491 | |||
492 | dhist : reset directory history |
|
492 | dhist : reset directory history | |
493 |
|
493 | |||
494 | array : reset only variables that are NumPy arrays |
|
494 | array : reset only variables that are NumPy arrays | |
495 |
|
495 | |||
496 | See Also |
|
496 | See Also | |
497 | -------- |
|
497 | -------- | |
498 | magic_reset_selective : invoked as ``%reset_selective`` |
|
498 | magic_reset_selective : invoked as ``%reset_selective`` | |
499 |
|
499 | |||
500 | Examples |
|
500 | Examples | |
501 | -------- |
|
501 | -------- | |
502 | :: |
|
502 | :: | |
503 |
|
503 | |||
504 | In [6]: a = 1 |
|
504 | In [6]: a = 1 | |
505 |
|
505 | |||
506 | In [7]: a |
|
506 | In [7]: a | |
507 | Out[7]: 1 |
|
507 | Out[7]: 1 | |
508 |
|
508 | |||
509 | In [8]: 'a' in _ip.user_ns |
|
509 | In [8]: 'a' in _ip.user_ns | |
510 | Out[8]: True |
|
510 | Out[8]: True | |
511 |
|
511 | |||
512 | In [9]: %reset -f |
|
512 | In [9]: %reset -f | |
513 |
|
513 | |||
514 | In [1]: 'a' in _ip.user_ns |
|
514 | In [1]: 'a' in _ip.user_ns | |
515 | Out[1]: False |
|
515 | Out[1]: False | |
516 |
|
516 | |||
517 | In [2]: %reset -f in |
|
517 | In [2]: %reset -f in | |
518 | Flushing input history |
|
518 | Flushing input history | |
519 |
|
519 | |||
520 | In [3]: %reset -f dhist in |
|
520 | In [3]: %reset -f dhist in | |
521 | Flushing directory history |
|
521 | Flushing directory history | |
522 | Flushing input history |
|
522 | Flushing input history | |
523 |
|
523 | |||
524 | Notes |
|
524 | Notes | |
525 | ----- |
|
525 | ----- | |
526 | Calling this magic from clients that do not implement standard input, |
|
526 | Calling this magic from clients that do not implement standard input, | |
527 | such as the ipython notebook interface, will reset the namespace |
|
527 | such as the ipython notebook interface, will reset the namespace | |
528 | without confirmation. |
|
528 | without confirmation. | |
529 | """ |
|
529 | """ | |
530 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
530 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
531 | if 'f' in opts: |
|
531 | if 'f' in opts: | |
532 | ans = True |
|
532 | ans = True | |
533 | else: |
|
533 | else: | |
534 | try: |
|
534 | try: | |
535 | ans = self.shell.ask_yes_no( |
|
535 | ans = self.shell.ask_yes_no( | |
536 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
536 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", | |
537 | default='n') |
|
537 | default='n') | |
538 | except StdinNotImplementedError: |
|
538 | except StdinNotImplementedError: | |
539 | ans = True |
|
539 | ans = True | |
540 | if not ans: |
|
540 | if not ans: | |
541 | print 'Nothing done.' |
|
541 | print 'Nothing done.' | |
542 | return |
|
542 | return | |
543 |
|
543 | |||
544 | if 's' in opts: # Soft reset |
|
544 | if 's' in opts: # Soft reset | |
545 | user_ns = self.shell.user_ns |
|
545 | user_ns = self.shell.user_ns | |
546 | for i in self.who_ls(): |
|
546 | for i in self.who_ls(): | |
547 | del(user_ns[i]) |
|
547 | del(user_ns[i]) | |
548 | elif len(args) == 0: # Hard reset |
|
548 | elif len(args) == 0: # Hard reset | |
549 | self.shell.reset(new_session = False) |
|
549 | self.shell.reset(new_session = False) | |
550 |
|
550 | |||
551 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
551 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
552 | ip = self.shell |
|
552 | ip = self.shell | |
553 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
553 | user_ns = self.shell.user_ns # local lookup, heavily used | |
554 |
|
554 | |||
555 | for target in args: |
|
555 | for target in args: | |
556 | target = target.lower() # make matches case insensitive |
|
556 | target = target.lower() # make matches case insensitive | |
557 | if target == 'out': |
|
557 | if target == 'out': | |
558 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
558 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
559 | self.shell.displayhook.flush() |
|
559 | self.shell.displayhook.flush() | |
560 |
|
560 | |||
561 | elif target == 'in': |
|
561 | elif target == 'in': | |
562 | print "Flushing input history" |
|
562 | print "Flushing input history" | |
563 | pc = self.shell.displayhook.prompt_count + 1 |
|
563 | pc = self.shell.displayhook.prompt_count + 1 | |
564 | for n in range(1, pc): |
|
564 | for n in range(1, pc): | |
565 | key = '_i'+repr(n) |
|
565 | key = '_i'+repr(n) | |
566 | user_ns.pop(key,None) |
|
566 | user_ns.pop(key,None) | |
567 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
567 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
568 | hm = ip.history_manager |
|
568 | hm = ip.history_manager | |
569 | # don't delete these, as %save and %macro depending on the |
|
569 | # don't delete these, as %save and %macro depending on the | |
570 | # length of these lists to be preserved |
|
570 | # length of these lists to be preserved | |
571 | hm.input_hist_parsed[:] = [''] * pc |
|
571 | hm.input_hist_parsed[:] = [''] * pc | |
572 | hm.input_hist_raw[:] = [''] * pc |
|
572 | hm.input_hist_raw[:] = [''] * pc | |
573 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
573 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
574 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
574 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
575 |
|
575 | |||
576 | elif target == 'array': |
|
576 | elif target == 'array': | |
577 | # Support cleaning up numpy arrays |
|
577 | # Support cleaning up numpy arrays | |
578 | try: |
|
578 | try: | |
579 | from numpy import ndarray |
|
579 | from numpy import ndarray | |
580 | # This must be done with items and not iteritems because |
|
580 | # This must be done with items and not iteritems because | |
581 | # we're going to modify the dict in-place. |
|
581 | # we're going to modify the dict in-place. | |
582 | for x,val in user_ns.items(): |
|
582 | for x,val in user_ns.items(): | |
583 | if isinstance(val,ndarray): |
|
583 | if isinstance(val,ndarray): | |
584 | del user_ns[x] |
|
584 | del user_ns[x] | |
585 | except ImportError: |
|
585 | except ImportError: | |
586 | print "reset array only works if Numpy is available." |
|
586 | print "reset array only works if Numpy is available." | |
587 |
|
587 | |||
588 | elif target == 'dhist': |
|
588 | elif target == 'dhist': | |
589 | print "Flushing directory history" |
|
589 | print "Flushing directory history" | |
590 | del user_ns['_dh'][:] |
|
590 | del user_ns['_dh'][:] | |
591 |
|
591 | |||
592 | else: |
|
592 | else: | |
593 | print "Don't know how to reset ", |
|
593 | print "Don't know how to reset ", | |
594 | print target + ", please run `%reset?` for details" |
|
594 | print target + ", please run `%reset?` for details" | |
595 |
|
595 | |||
596 | gc.collect() |
|
596 | gc.collect() | |
597 |
|
597 | |||
598 | @line_magic |
|
598 | @line_magic | |
599 | def reset_selective(self, parameter_s=''): |
|
599 | def reset_selective(self, parameter_s=''): | |
600 | """Resets the namespace by removing names defined by the user. |
|
600 | """Resets the namespace by removing names defined by the user. | |
601 |
|
601 | |||
602 | Input/Output history are left around in case you need them. |
|
602 | Input/Output history are left around in case you need them. | |
603 |
|
603 | |||
604 | %reset_selective [-f] regex |
|
604 | %reset_selective [-f] regex | |
605 |
|
605 | |||
606 | No action is taken if regex is not included |
|
606 | No action is taken if regex is not included | |
607 |
|
607 | |||
608 | Options |
|
608 | Options | |
609 | -f : force reset without asking for confirmation. |
|
609 | -f : force reset without asking for confirmation. | |
610 |
|
610 | |||
611 | See Also |
|
611 | See Also | |
612 | -------- |
|
612 | -------- | |
613 | magic_reset : invoked as ``%reset`` |
|
613 | magic_reset : invoked as ``%reset`` | |
614 |
|
614 | |||
615 | Examples |
|
615 | Examples | |
616 | -------- |
|
616 | -------- | |
617 |
|
617 | |||
618 | We first fully reset the namespace so your output looks identical to |
|
618 | We first fully reset the namespace so your output looks identical to | |
619 | this example for pedagogical reasons; in practice you do not need a |
|
619 | this example for pedagogical reasons; in practice you do not need a | |
620 | full reset:: |
|
620 | full reset:: | |
621 |
|
621 | |||
622 | In [1]: %reset -f |
|
622 | In [1]: %reset -f | |
623 |
|
623 | |||
624 | Now, with a clean namespace we can make a few variables and use |
|
624 | Now, with a clean namespace we can make a few variables and use | |
625 | ``%reset_selective`` to only delete names that match our regexp:: |
|
625 | ``%reset_selective`` to only delete names that match our regexp:: | |
626 |
|
626 | |||
627 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
627 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
628 |
|
628 | |||
629 | In [3]: who_ls |
|
629 | In [3]: who_ls | |
630 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
630 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
631 |
|
631 | |||
632 | In [4]: %reset_selective -f b[2-3]m |
|
632 | In [4]: %reset_selective -f b[2-3]m | |
633 |
|
633 | |||
634 | In [5]: who_ls |
|
634 | In [5]: who_ls | |
635 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
635 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
636 |
|
636 | |||
637 | In [6]: %reset_selective -f d |
|
637 | In [6]: %reset_selective -f d | |
638 |
|
638 | |||
639 | In [7]: who_ls |
|
639 | In [7]: who_ls | |
640 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
640 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
641 |
|
641 | |||
642 | In [8]: %reset_selective -f c |
|
642 | In [8]: %reset_selective -f c | |
643 |
|
643 | |||
644 | In [9]: who_ls |
|
644 | In [9]: who_ls | |
645 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
645 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
646 |
|
646 | |||
647 | In [10]: %reset_selective -f b |
|
647 | In [10]: %reset_selective -f b | |
648 |
|
648 | |||
649 | In [11]: who_ls |
|
649 | In [11]: who_ls | |
650 | Out[11]: ['a'] |
|
650 | Out[11]: ['a'] | |
651 |
|
651 | |||
652 | Notes |
|
652 | Notes | |
653 | ----- |
|
653 | ----- | |
654 | Calling this magic from clients that do not implement standard input, |
|
654 | Calling this magic from clients that do not implement standard input, | |
655 | such as the ipython notebook interface, will reset the namespace |
|
655 | such as the ipython notebook interface, will reset the namespace | |
656 | without confirmation. |
|
656 | without confirmation. | |
657 | """ |
|
657 | """ | |
658 |
|
658 | |||
659 | opts, regex = self.parse_options(parameter_s,'f') |
|
659 | opts, regex = self.parse_options(parameter_s,'f') | |
660 |
|
660 | |||
661 | if opts.has_key('f'): |
|
661 | if opts.has_key('f'): | |
662 | ans = True |
|
662 | ans = True | |
663 | else: |
|
663 | else: | |
664 | try: |
|
664 | try: | |
665 | ans = self.shell.ask_yes_no( |
|
665 | ans = self.shell.ask_yes_no( | |
666 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
666 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
667 | default='n') |
|
667 | default='n') | |
668 | except StdinNotImplementedError: |
|
668 | except StdinNotImplementedError: | |
669 | ans = True |
|
669 | ans = True | |
670 | if not ans: |
|
670 | if not ans: | |
671 | print 'Nothing done.' |
|
671 | print 'Nothing done.' | |
672 | return |
|
672 | return | |
673 | user_ns = self.shell.user_ns |
|
673 | user_ns = self.shell.user_ns | |
674 | if not regex: |
|
674 | if not regex: | |
675 | print 'No regex pattern specified. Nothing done.' |
|
675 | print 'No regex pattern specified. Nothing done.' | |
676 | return |
|
676 | return | |
677 | else: |
|
677 | else: | |
678 | try: |
|
678 | try: | |
679 | m = re.compile(regex) |
|
679 | m = re.compile(regex) | |
680 | except TypeError: |
|
680 | except TypeError: | |
681 | raise TypeError('regex must be a string or compiled pattern') |
|
681 | raise TypeError('regex must be a string or compiled pattern') | |
682 | for i in self.who_ls(): |
|
682 | for i in self.who_ls(): | |
683 | if m.search(i): |
|
683 | if m.search(i): | |
684 | del(user_ns[i]) |
|
684 | del(user_ns[i]) | |
685 |
|
685 | |||
686 | @line_magic |
|
686 | @line_magic | |
687 | def xdel(self, parameter_s=''): |
|
687 | def xdel(self, parameter_s=''): | |
688 | """Delete a variable, trying to clear it from anywhere that |
|
688 | """Delete a variable, trying to clear it from anywhere that | |
689 | IPython's machinery has references to it. By default, this uses |
|
689 | IPython's machinery has references to it. By default, this uses | |
690 | the identity of the named object in the user namespace to remove |
|
690 | the identity of the named object in the user namespace to remove | |
691 | references held under other names. The object is also removed |
|
691 | references held under other names. The object is also removed | |
692 | from the output history. |
|
692 | from the output history. | |
693 |
|
693 | |||
694 | Options |
|
694 | Options | |
695 | -n : Delete the specified name from all namespaces, without |
|
695 | -n : Delete the specified name from all namespaces, without | |
696 | checking their identity. |
|
696 | checking their identity. | |
697 | """ |
|
697 | """ | |
698 | opts, varname = self.parse_options(parameter_s,'n') |
|
698 | opts, varname = self.parse_options(parameter_s,'n') | |
699 | try: |
|
699 | try: | |
700 | self.shell.del_var(varname, ('n' in opts)) |
|
700 | self.shell.del_var(varname, ('n' in opts)) | |
701 | except (NameError, ValueError) as e: |
|
701 | except (NameError, ValueError) as e: | |
702 | print type(e).__name__ +": "+ str(e) |
|
702 | print type(e).__name__ +": "+ str(e) |
@@ -1,674 +1,674 b'' | |||||
1 | """Implementation of magic functions for interaction with the OS. |
|
1 | """Implementation of magic functions for interaction with the OS. | |
2 |
|
2 | |||
3 | Note: this module is named 'osm' instead of 'os' to avoid a collision with the |
|
3 | Note: this module is named 'osm' instead of 'os' to avoid a collision with the | |
4 | builtin. |
|
4 | builtin. | |
5 | """ |
|
5 | """ | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (c) 2012 The IPython Development Team. |
|
7 | # Copyright (c) 2012 The IPython Development Team. | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the Modified BSD License. |
|
9 | # Distributed under the terms of the Modified BSD License. | |
10 | # |
|
10 | # | |
11 | # The full license is in the file COPYING.txt, distributed with this software. |
|
11 | # The full license is in the file COPYING.txt, distributed with this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | import sys |
|
21 | import sys | |
22 | from pprint import pformat |
|
22 | from pprint import pformat | |
23 |
|
23 | |||
24 | # Our own packages |
|
24 | # Our own packages | |
25 | from IPython.core import oinspect |
|
25 | from IPython.core import oinspect | |
26 | from IPython.core import page |
|
26 | from IPython.core import page | |
27 | from IPython.core.error import UsageError |
|
27 | from IPython.core.error import UsageError | |
28 | from IPython.core.magic import (Magics, compress_dhist, magics_class, |
|
28 | from IPython.core.magic import (Magics, compress_dhist, magics_class, | |
29 | line_magic) |
|
29 | line_magic) | |
30 | from IPython.testing.skipdoctest import skip_doctest |
|
30 | from IPython.testing.skipdoctest import skip_doctest | |
31 | from IPython.utils.io import file_read, nlprint |
|
31 | from IPython.utils.io import file_read, nlprint | |
32 | from IPython.utils.path import get_py_filename, unquote_filename |
|
32 | from IPython.utils.path import get_py_filename, unquote_filename | |
33 | from IPython.utils.process import abbrev_cwd |
|
33 | from IPython.utils.process import abbrev_cwd | |
34 | from IPython.utils.terminal import set_term_title |
|
34 | from IPython.utils.terminal import set_term_title | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 | # Magic implementation classes |
|
36 | # Magic implementation classes | |
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | @magics_class |
|
38 | @magics_class | |
39 | class OSMagics(Magics): |
|
39 | class OSMagics(Magics): | |
40 | """Magics to interact with the underlying OS (shell-type functionality). |
|
40 | """Magics to interact with the underlying OS (shell-type functionality). | |
41 | """ |
|
41 | """ | |
42 |
|
42 | |||
43 | @skip_doctest |
|
43 | @skip_doctest | |
44 | @line_magic |
|
44 | @line_magic | |
45 | def alias(self, parameter_s=''): |
|
45 | def alias(self, parameter_s=''): | |
46 | """Define an alias for a system command. |
|
46 | """Define an alias for a system command. | |
47 |
|
47 | |||
48 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
48 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
49 |
|
49 | |||
50 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
50 | Then, typing 'alias_name params' will execute the system command 'cmd | |
51 | params' (from your underlying operating system). |
|
51 | params' (from your underlying operating system). | |
52 |
|
52 | |||
53 | Aliases have lower precedence than magic functions and Python normal |
|
53 | Aliases have lower precedence than magic functions and Python normal | |
54 | variables, so if 'foo' is both a Python variable and an alias, the |
|
54 | variables, so if 'foo' is both a Python variable and an alias, the | |
55 | alias can not be executed until 'del foo' removes the Python variable. |
|
55 | alias can not be executed until 'del foo' removes the Python variable. | |
56 |
|
56 | |||
57 | You can use the %l specifier in an alias definition to represent the |
|
57 | You can use the %l specifier in an alias definition to represent the | |
58 | whole line when the alias is called. For example:: |
|
58 | whole line when the alias is called. For example:: | |
59 |
|
59 | |||
60 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
60 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
61 | In [3]: bracket hello world |
|
61 | In [3]: bracket hello world | |
62 | Input in brackets: <hello world> |
|
62 | Input in brackets: <hello world> | |
63 |
|
63 | |||
64 | You can also define aliases with parameters using %s specifiers (one |
|
64 | You can also define aliases with parameters using %s specifiers (one | |
65 | per parameter):: |
|
65 | per parameter):: | |
66 |
|
66 | |||
67 | In [1]: alias parts echo first %s second %s |
|
67 | In [1]: alias parts echo first %s second %s | |
68 | In [2]: %parts A B |
|
68 | In [2]: %parts A B | |
69 | first A second B |
|
69 | first A second B | |
70 | In [3]: %parts A |
|
70 | In [3]: %parts A | |
71 | Incorrect number of arguments: 2 expected. |
|
71 | Incorrect number of arguments: 2 expected. | |
72 | parts is an alias to: 'echo first %s second %s' |
|
72 | parts is an alias to: 'echo first %s second %s' | |
73 |
|
73 | |||
74 | Note that %l and %s are mutually exclusive. You can only use one or |
|
74 | Note that %l and %s are mutually exclusive. You can only use one or | |
75 | the other in your aliases. |
|
75 | the other in your aliases. | |
76 |
|
76 | |||
77 | Aliases expand Python variables just like system calls using ! or !! |
|
77 | Aliases expand Python variables just like system calls using ! or !! | |
78 | do: all expressions prefixed with '$' get expanded. For details of |
|
78 | do: all expressions prefixed with '$' get expanded. For details of | |
79 | the semantic rules, see PEP-215: |
|
79 | the semantic rules, see PEP-215: | |
80 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
80 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
81 | IPython for variable expansion. If you want to access a true shell |
|
81 | IPython for variable expansion. If you want to access a true shell | |
82 | variable, an extra $ is necessary to prevent its expansion by |
|
82 | variable, an extra $ is necessary to prevent its expansion by | |
83 | IPython:: |
|
83 | IPython:: | |
84 |
|
84 | |||
85 | In [6]: alias show echo |
|
85 | In [6]: alias show echo | |
86 | In [7]: PATH='A Python string' |
|
86 | In [7]: PATH='A Python string' | |
87 | In [8]: show $PATH |
|
87 | In [8]: show $PATH | |
88 | A Python string |
|
88 | A Python string | |
89 | In [9]: show $$PATH |
|
89 | In [9]: show $$PATH | |
90 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
90 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
91 |
|
91 | |||
92 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
92 | You can use the alias facility to acess all of $PATH. See the %rehash | |
93 | and %rehashx functions, which automatically create aliases for the |
|
93 | and %rehashx functions, which automatically create aliases for the | |
94 | contents of your $PATH. |
|
94 | contents of your $PATH. | |
95 |
|
95 | |||
96 | If called with no parameters, %alias prints the current alias table.""" |
|
96 | If called with no parameters, %alias prints the current alias table.""" | |
97 |
|
97 | |||
98 | par = parameter_s.strip() |
|
98 | par = parameter_s.strip() | |
99 | if not par: |
|
99 | if not par: | |
100 | aliases = sorted(self.shell.alias_manager.aliases) |
|
100 | aliases = sorted(self.shell.alias_manager.aliases) | |
101 | # stored = self.shell.db.get('stored_aliases', {} ) |
|
101 | # stored = self.shell.db.get('stored_aliases', {} ) | |
102 | # for k, v in stored: |
|
102 | # for k, v in stored: | |
103 | # atab.append(k, v[0]) |
|
103 | # atab.append(k, v[0]) | |
104 |
|
104 | |||
105 | print "Total number of aliases:", len(aliases) |
|
105 | print "Total number of aliases:", len(aliases) | |
106 | sys.stdout.flush() |
|
106 | sys.stdout.flush() | |
107 | return aliases |
|
107 | return aliases | |
108 |
|
108 | |||
109 | # Now try to define a new one |
|
109 | # Now try to define a new one | |
110 | try: |
|
110 | try: | |
111 | alias,cmd = par.split(None, 1) |
|
111 | alias,cmd = par.split(None, 1) | |
112 | except: |
|
112 | except: | |
113 | print oinspect.getdoc(self.alias) |
|
113 | print oinspect.getdoc(self.alias) | |
114 | else: |
|
114 | else: | |
115 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
115 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
116 | # end magic_alias |
|
116 | # end magic_alias | |
117 |
|
117 | |||
118 | @line_magic |
|
118 | @line_magic | |
119 | def unalias(self, parameter_s=''): |
|
119 | def unalias(self, parameter_s=''): | |
120 | """Remove an alias""" |
|
120 | """Remove an alias""" | |
121 |
|
121 | |||
122 | aname = parameter_s.strip() |
|
122 | aname = parameter_s.strip() | |
123 | self.shell.alias_manager.undefine_alias(aname) |
|
123 | self.shell.alias_manager.undefine_alias(aname) | |
124 | stored = self.shell.db.get('stored_aliases', {} ) |
|
124 | stored = self.shell.db.get('stored_aliases', {} ) | |
125 | if aname in stored: |
|
125 | if aname in stored: | |
126 | print "Removing %stored alias",aname |
|
126 | print "Removing %stored alias",aname | |
127 | del stored[aname] |
|
127 | del stored[aname] | |
128 | self.shell.db['stored_aliases'] = stored |
|
128 | self.shell.db['stored_aliases'] = stored | |
129 |
|
129 | |||
130 | @line_magic |
|
130 | @line_magic | |
131 | def rehashx(self, parameter_s=''): |
|
131 | def rehashx(self, parameter_s=''): | |
132 | """Update the alias table with all executable files in $PATH. |
|
132 | """Update the alias table with all executable files in $PATH. | |
133 |
|
133 | |||
134 | This version explicitly checks that every entry in $PATH is a file |
|
134 | This version explicitly checks that every entry in $PATH is a file | |
135 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
135 | with execute access (os.X_OK), so it is much slower than %rehash. | |
136 |
|
136 | |||
137 | Under Windows, it checks executability as a match against a |
|
137 | Under Windows, it checks executability as a match against a | |
138 | '|'-separated string of extensions, stored in the IPython config |
|
138 | '|'-separated string of extensions, stored in the IPython config | |
139 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
139 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
140 |
|
140 | |||
141 | This function also resets the root module cache of module completer, |
|
141 | This function also resets the root module cache of module completer, | |
142 | used on slow filesystems. |
|
142 | used on slow filesystems. | |
143 | """ |
|
143 | """ | |
144 | from IPython.core.alias import InvalidAliasError |
|
144 | from IPython.core.alias import InvalidAliasError | |
145 |
|
145 | |||
146 | # for the benefit of module completer in ipy_completers.py |
|
146 | # for the benefit of module completer in ipy_completers.py | |
147 | del self.shell.db['rootmodules'] |
|
147 | del self.shell.db['rootmodules'] | |
148 |
|
148 | |||
149 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
149 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
150 | os.environ.get('PATH','').split(os.pathsep)] |
|
150 | os.environ.get('PATH','').split(os.pathsep)] | |
151 | path = filter(os.path.isdir,path) |
|
151 | path = filter(os.path.isdir,path) | |
152 |
|
152 | |||
153 | syscmdlist = [] |
|
153 | syscmdlist = [] | |
154 | # Now define isexec in a cross platform manner. |
|
154 | # Now define isexec in a cross platform manner. | |
155 | if os.name == 'posix': |
|
155 | if os.name == 'posix': | |
156 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
156 | isexec = lambda fname:os.path.isfile(fname) and \ | |
157 | os.access(fname,os.X_OK) |
|
157 | os.access(fname,os.X_OK) | |
158 | else: |
|
158 | else: | |
159 | try: |
|
159 | try: | |
160 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
160 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
161 | except KeyError: |
|
161 | except KeyError: | |
162 | winext = 'exe|com|bat|py' |
|
162 | winext = 'exe|com|bat|py' | |
163 | if 'py' not in winext: |
|
163 | if 'py' not in winext: | |
164 | winext += '|py' |
|
164 | winext += '|py' | |
165 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
165 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
166 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
166 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
167 | savedir = os.getcwdu() |
|
167 | savedir = os.getcwdu() | |
168 |
|
168 | |||
169 | # Now walk the paths looking for executables to alias. |
|
169 | # Now walk the paths looking for executables to alias. | |
170 | try: |
|
170 | try: | |
171 | # write the whole loop for posix/Windows so we don't have an if in |
|
171 | # write the whole loop for posix/Windows so we don't have an if in | |
172 | # the innermost part |
|
172 | # the innermost part | |
173 | if os.name == 'posix': |
|
173 | if os.name == 'posix': | |
174 | for pdir in path: |
|
174 | for pdir in path: | |
175 | os.chdir(pdir) |
|
175 | os.chdir(pdir) | |
176 | for ff in os.listdir(pdir): |
|
176 | for ff in os.listdir(pdir): | |
177 | if isexec(ff): |
|
177 | if isexec(ff): | |
178 | try: |
|
178 | try: | |
179 | # Removes dots from the name since ipython |
|
179 | # Removes dots from the name since ipython | |
180 | # will assume names with dots to be python. |
|
180 | # will assume names with dots to be python. | |
181 | self.shell.alias_manager.define_alias( |
|
181 | self.shell.alias_manager.define_alias( | |
182 | ff.replace('.',''), ff) |
|
182 | ff.replace('.',''), ff) | |
183 | except InvalidAliasError: |
|
183 | except InvalidAliasError: | |
184 | pass |
|
184 | pass | |
185 | else: |
|
185 | else: | |
186 | syscmdlist.append(ff) |
|
186 | syscmdlist.append(ff) | |
187 | else: |
|
187 | else: | |
188 | no_alias = self.shell.alias_manager.no_alias |
|
188 | no_alias = self.shell.alias_manager.no_alias | |
189 | for pdir in path: |
|
189 | for pdir in path: | |
190 | os.chdir(pdir) |
|
190 | os.chdir(pdir) | |
191 | for ff in os.listdir(pdir): |
|
191 | for ff in os.listdir(pdir): | |
192 | base, ext = os.path.splitext(ff) |
|
192 | base, ext = os.path.splitext(ff) | |
193 | if isexec(ff) and base.lower() not in no_alias: |
|
193 | if isexec(ff) and base.lower() not in no_alias: | |
194 | if ext.lower() == '.exe': |
|
194 | if ext.lower() == '.exe': | |
195 | ff = base |
|
195 | ff = base | |
196 | try: |
|
196 | try: | |
197 | # Removes dots from the name since ipython |
|
197 | # Removes dots from the name since ipython | |
198 | # will assume names with dots to be python. |
|
198 | # will assume names with dots to be python. | |
199 | self.shell.alias_manager.define_alias( |
|
199 | self.shell.alias_manager.define_alias( | |
200 | base.lower().replace('.',''), ff) |
|
200 | base.lower().replace('.',''), ff) | |
201 | except InvalidAliasError: |
|
201 | except InvalidAliasError: | |
202 | pass |
|
202 | pass | |
203 | syscmdlist.append(ff) |
|
203 | syscmdlist.append(ff) | |
204 | self.shell.db['syscmdlist'] = syscmdlist |
|
204 | self.shell.db['syscmdlist'] = syscmdlist | |
205 | finally: |
|
205 | finally: | |
206 | os.chdir(savedir) |
|
206 | os.chdir(savedir) | |
207 |
|
207 | |||
208 | @skip_doctest |
|
208 | @skip_doctest | |
209 | @line_magic |
|
209 | @line_magic | |
210 | def pwd(self, parameter_s=''): |
|
210 | def pwd(self, parameter_s=''): | |
211 | """Return the current working directory path. |
|
211 | """Return the current working directory path. | |
212 |
|
212 | |||
213 | Examples |
|
213 | Examples | |
214 | -------- |
|
214 | -------- | |
215 | :: |
|
215 | :: | |
216 |
|
216 | |||
217 | In [9]: pwd |
|
217 | In [9]: pwd | |
218 | Out[9]: '/home/tsuser/sprint/ipython' |
|
218 | Out[9]: '/home/tsuser/sprint/ipython' | |
219 | """ |
|
219 | """ | |
220 | return os.getcwdu() |
|
220 | return os.getcwdu() | |
221 |
|
221 | |||
222 | @skip_doctest |
|
222 | @skip_doctest | |
223 | @line_magic |
|
223 | @line_magic | |
224 | def cd(self, parameter_s=''): |
|
224 | def cd(self, parameter_s=''): | |
225 | """Change the current working directory. |
|
225 | """Change the current working directory. | |
226 |
|
226 | |||
227 | This command automatically maintains an internal list of directories |
|
227 | This command automatically maintains an internal list of directories | |
228 | you visit during your IPython session, in the variable _dh. The |
|
228 | you visit during your IPython session, in the variable _dh. The | |
229 | command %dhist shows this history nicely formatted. You can also |
|
229 | command %dhist shows this history nicely formatted. You can also | |
230 | do 'cd -<tab>' to see directory history conveniently. |
|
230 | do 'cd -<tab>' to see directory history conveniently. | |
231 |
|
231 | |||
232 | Usage: |
|
232 | Usage: | |
233 |
|
233 | |||
234 | cd 'dir': changes to directory 'dir'. |
|
234 | cd 'dir': changes to directory 'dir'. | |
235 |
|
235 | |||
236 | cd -: changes to the last visited directory. |
|
236 | cd -: changes to the last visited directory. | |
237 |
|
237 | |||
238 | cd -<n>: changes to the n-th directory in the directory history. |
|
238 | cd -<n>: changes to the n-th directory in the directory history. | |
239 |
|
239 | |||
240 | cd --foo: change to directory that matches 'foo' in history |
|
240 | cd --foo: change to directory that matches 'foo' in history | |
241 |
|
241 | |||
242 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
242 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
243 | (note: cd <bookmark_name> is enough if there is no |
|
243 | (note: cd <bookmark_name> is enough if there is no | |
244 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
244 | directory <bookmark_name>, but a bookmark with the name exists.) | |
245 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
245 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
246 |
|
246 | |||
247 | Options: |
|
247 | Options: | |
248 |
|
248 | |||
249 | -q: quiet. Do not print the working directory after the cd command is |
|
249 | -q: quiet. Do not print the working directory after the cd command is | |
250 | executed. By default IPython's cd command does print this directory, |
|
250 | executed. By default IPython's cd command does print this directory, | |
251 | since the default prompts do not display path information. |
|
251 | since the default prompts do not display path information. | |
252 |
|
252 | |||
253 | Note that !cd doesn't work for this purpose because the shell where |
|
253 | Note that !cd doesn't work for this purpose because the shell where | |
254 | !command runs is immediately discarded after executing 'command'. |
|
254 | !command runs is immediately discarded after executing 'command'. | |
255 |
|
255 | |||
256 | Examples |
|
256 | Examples | |
257 | -------- |
|
257 | -------- | |
258 | :: |
|
258 | :: | |
259 |
|
259 | |||
260 | In [10]: cd parent/child |
|
260 | In [10]: cd parent/child | |
261 | /home/tsuser/parent/child |
|
261 | /home/tsuser/parent/child | |
262 | """ |
|
262 | """ | |
263 |
|
263 | |||
264 | oldcwd = os.getcwdu() |
|
264 | oldcwd = os.getcwdu() | |
265 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
265 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
266 | # jump in directory history by number |
|
266 | # jump in directory history by number | |
267 | if numcd: |
|
267 | if numcd: | |
268 | nn = int(numcd.group(2)) |
|
268 | nn = int(numcd.group(2)) | |
269 | try: |
|
269 | try: | |
270 | ps = self.shell.user_ns['_dh'][nn] |
|
270 | ps = self.shell.user_ns['_dh'][nn] | |
271 | except IndexError: |
|
271 | except IndexError: | |
272 | print 'The requested directory does not exist in history.' |
|
272 | print 'The requested directory does not exist in history.' | |
273 | return |
|
273 | return | |
274 | else: |
|
274 | else: | |
275 | opts = {} |
|
275 | opts = {} | |
276 | elif parameter_s.startswith('--'): |
|
276 | elif parameter_s.startswith('--'): | |
277 | ps = None |
|
277 | ps = None | |
278 | fallback = None |
|
278 | fallback = None | |
279 | pat = parameter_s[2:] |
|
279 | pat = parameter_s[2:] | |
280 | dh = self.shell.user_ns['_dh'] |
|
280 | dh = self.shell.user_ns['_dh'] | |
281 | # first search only by basename (last component) |
|
281 | # first search only by basename (last component) | |
282 | for ent in reversed(dh): |
|
282 | for ent in reversed(dh): | |
283 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
283 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
284 | ps = ent |
|
284 | ps = ent | |
285 | break |
|
285 | break | |
286 |
|
286 | |||
287 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
287 | if fallback is None and pat in ent and os.path.isdir(ent): | |
288 | fallback = ent |
|
288 | fallback = ent | |
289 |
|
289 | |||
290 | # if we have no last part match, pick the first full path match |
|
290 | # if we have no last part match, pick the first full path match | |
291 | if ps is None: |
|
291 | if ps is None: | |
292 | ps = fallback |
|
292 | ps = fallback | |
293 |
|
293 | |||
294 | if ps is None: |
|
294 | if ps is None: | |
295 | print "No matching entry in directory history" |
|
295 | print "No matching entry in directory history" | |
296 | return |
|
296 | return | |
297 | else: |
|
297 | else: | |
298 | opts = {} |
|
298 | opts = {} | |
299 |
|
299 | |||
300 |
|
300 | |||
301 | else: |
|
301 | else: | |
302 | #turn all non-space-escaping backslashes to slashes, |
|
302 | #turn all non-space-escaping backslashes to slashes, | |
303 | # for c:\windows\directory\names\ |
|
303 | # for c:\windows\directory\names\ | |
304 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
304 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
305 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
305 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
306 | # jump to previous |
|
306 | # jump to previous | |
307 | if ps == '-': |
|
307 | if ps == '-': | |
308 | try: |
|
308 | try: | |
309 | ps = self.shell.user_ns['_dh'][-2] |
|
309 | ps = self.shell.user_ns['_dh'][-2] | |
310 | except IndexError: |
|
310 | except IndexError: | |
311 | raise UsageError('%cd -: No previous directory to change to.') |
|
311 | raise UsageError('%cd -: No previous directory to change to.') | |
312 | # jump to bookmark if needed |
|
312 | # jump to bookmark if needed | |
313 | else: |
|
313 | else: | |
314 | if not os.path.isdir(ps) or 'b' in opts: |
|
314 | if not os.path.isdir(ps) or 'b' in opts: | |
315 | bkms = self.shell.db.get('bookmarks', {}) |
|
315 | bkms = self.shell.db.get('bookmarks', {}) | |
316 |
|
316 | |||
317 | if ps in bkms: |
|
317 | if ps in bkms: | |
318 | target = bkms[ps] |
|
318 | target = bkms[ps] | |
319 | print '(bookmark:%s) -> %s' % (ps,target) |
|
319 | print '(bookmark:%s) -> %s' % (ps, target) | |
320 | ps = target |
|
320 | ps = target | |
321 | else: |
|
321 | else: | |
322 | if 'b' in opts: |
|
322 | if 'b' in opts: | |
323 | raise UsageError("Bookmark '%s' not found. " |
|
323 | raise UsageError("Bookmark '%s' not found. " | |
324 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
324 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
325 |
|
325 | |||
326 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
326 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
327 | ps = unquote_filename(ps) |
|
327 | ps = unquote_filename(ps) | |
328 | # at this point ps should point to the target dir |
|
328 | # at this point ps should point to the target dir | |
329 | if ps: |
|
329 | if ps: | |
330 | try: |
|
330 | try: | |
331 | os.chdir(os.path.expanduser(ps)) |
|
331 | os.chdir(os.path.expanduser(ps)) | |
332 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
332 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
333 | set_term_title('IPython: ' + abbrev_cwd()) |
|
333 | set_term_title('IPython: ' + abbrev_cwd()) | |
334 | except OSError: |
|
334 | except OSError: | |
335 | print sys.exc_info()[1] |
|
335 | print sys.exc_info()[1] | |
336 | else: |
|
336 | else: | |
337 | cwd = os.getcwdu() |
|
337 | cwd = os.getcwdu() | |
338 | dhist = self.shell.user_ns['_dh'] |
|
338 | dhist = self.shell.user_ns['_dh'] | |
339 | if oldcwd != cwd: |
|
339 | if oldcwd != cwd: | |
340 | dhist.append(cwd) |
|
340 | dhist.append(cwd) | |
341 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
341 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
342 |
|
342 | |||
343 | else: |
|
343 | else: | |
344 | os.chdir(self.shell.home_dir) |
|
344 | os.chdir(self.shell.home_dir) | |
345 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
345 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
346 | set_term_title('IPython: ' + '~') |
|
346 | set_term_title('IPython: ' + '~') | |
347 | cwd = os.getcwdu() |
|
347 | cwd = os.getcwdu() | |
348 | dhist = self.shell.user_ns['_dh'] |
|
348 | dhist = self.shell.user_ns['_dh'] | |
349 |
|
349 | |||
350 | if oldcwd != cwd: |
|
350 | if oldcwd != cwd: | |
351 | dhist.append(cwd) |
|
351 | dhist.append(cwd) | |
352 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
352 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
353 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
353 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
354 | print self.shell.user_ns['_dh'][-1] |
|
354 | print self.shell.user_ns['_dh'][-1] | |
355 |
|
355 | |||
356 |
|
356 | |||
357 | @line_magic |
|
357 | @line_magic | |
358 | def env(self, parameter_s=''): |
|
358 | def env(self, parameter_s=''): | |
359 | """List environment variables.""" |
|
359 | """List environment variables.""" | |
360 |
|
360 | |||
361 | return dict(os.environ) |
|
361 | return dict(os.environ) | |
362 |
|
362 | |||
363 | @line_magic |
|
363 | @line_magic | |
364 | def pushd(self, parameter_s=''): |
|
364 | def pushd(self, parameter_s=''): | |
365 | """Place the current dir on stack and change directory. |
|
365 | """Place the current dir on stack and change directory. | |
366 |
|
366 | |||
367 | Usage:\\ |
|
367 | Usage:\\ | |
368 | %pushd ['dirname'] |
|
368 | %pushd ['dirname'] | |
369 | """ |
|
369 | """ | |
370 |
|
370 | |||
371 | dir_s = self.shell.dir_stack |
|
371 | dir_s = self.shell.dir_stack | |
372 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
372 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
373 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') |
|
373 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') | |
374 | if tgt: |
|
374 | if tgt: | |
375 | self.cd(parameter_s) |
|
375 | self.cd(parameter_s) | |
376 | dir_s.insert(0,cwd) |
|
376 | dir_s.insert(0,cwd) | |
377 | return self.shell.magic('dirs') |
|
377 | return self.shell.magic('dirs') | |
378 |
|
378 | |||
379 | @line_magic |
|
379 | @line_magic | |
380 | def popd(self, parameter_s=''): |
|
380 | def popd(self, parameter_s=''): | |
381 | """Change to directory popped off the top of the stack. |
|
381 | """Change to directory popped off the top of the stack. | |
382 | """ |
|
382 | """ | |
383 | if not self.shell.dir_stack: |
|
383 | if not self.shell.dir_stack: | |
384 | raise UsageError("%popd on empty stack") |
|
384 | raise UsageError("%popd on empty stack") | |
385 | top = self.shell.dir_stack.pop(0) |
|
385 | top = self.shell.dir_stack.pop(0) | |
386 | self.cd(top) |
|
386 | self.cd(top) | |
387 | print "popd ->",top |
|
387 | print "popd ->",top | |
388 |
|
388 | |||
389 | @line_magic |
|
389 | @line_magic | |
390 | def dirs(self, parameter_s=''): |
|
390 | def dirs(self, parameter_s=''): | |
391 | """Return the current directory stack.""" |
|
391 | """Return the current directory stack.""" | |
392 |
|
392 | |||
393 | return self.shell.dir_stack |
|
393 | return self.shell.dir_stack | |
394 |
|
394 | |||
395 | @line_magic |
|
395 | @line_magic | |
396 | def dhist(self, parameter_s=''): |
|
396 | def dhist(self, parameter_s=''): | |
397 | """Print your history of visited directories. |
|
397 | """Print your history of visited directories. | |
398 |
|
398 | |||
399 | %dhist -> print full history\\ |
|
399 | %dhist -> print full history\\ | |
400 | %dhist n -> print last n entries only\\ |
|
400 | %dhist n -> print last n entries only\\ | |
401 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
401 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
402 |
|
402 | |||
403 | This history is automatically maintained by the %cd command, and |
|
403 | This history is automatically maintained by the %cd command, and | |
404 | always available as the global list variable _dh. You can use %cd -<n> |
|
404 | always available as the global list variable _dh. You can use %cd -<n> | |
405 | to go to directory number <n>. |
|
405 | to go to directory number <n>. | |
406 |
|
406 | |||
407 | Note that most of time, you should view directory history by entering |
|
407 | Note that most of time, you should view directory history by entering | |
408 | cd -<TAB>. |
|
408 | cd -<TAB>. | |
409 |
|
409 | |||
410 | """ |
|
410 | """ | |
411 |
|
411 | |||
412 | dh = self.shell.user_ns['_dh'] |
|
412 | dh = self.shell.user_ns['_dh'] | |
413 | if parameter_s: |
|
413 | if parameter_s: | |
414 | try: |
|
414 | try: | |
415 | args = map(int,parameter_s.split()) |
|
415 | args = map(int,parameter_s.split()) | |
416 | except: |
|
416 | except: | |
417 | self.arg_err(self.dhist) |
|
417 | self.arg_err(self.dhist) | |
418 | return |
|
418 | return | |
419 | if len(args) == 1: |
|
419 | if len(args) == 1: | |
420 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
420 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
421 | elif len(args) == 2: |
|
421 | elif len(args) == 2: | |
422 | ini,fin = args |
|
422 | ini,fin = args | |
423 | else: |
|
423 | else: | |
424 | self.arg_err(self.dhist) |
|
424 | self.arg_err(self.dhist) | |
425 | return |
|
425 | return | |
426 | else: |
|
426 | else: | |
427 | ini,fin = 0,len(dh) |
|
427 | ini,fin = 0,len(dh) | |
428 | nlprint(dh, |
|
428 | nlprint(dh, | |
429 | header = 'Directory history (kept in _dh)', |
|
429 | header = 'Directory history (kept in _dh)', | |
430 | start=ini,stop=fin) |
|
430 | start=ini,stop=fin) | |
431 |
|
431 | |||
432 | @skip_doctest |
|
432 | @skip_doctest | |
433 | @line_magic |
|
433 | @line_magic | |
434 | def sc(self, parameter_s=''): |
|
434 | def sc(self, parameter_s=''): | |
435 | """Shell capture - execute a shell command and capture its output. |
|
435 | """Shell capture - execute a shell command and capture its output. | |
436 |
|
436 | |||
437 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
437 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
438 |
|
438 | |||
439 | You should use the form 'var = !command' instead. Example: |
|
439 | You should use the form 'var = !command' instead. Example: | |
440 |
|
440 | |||
441 | "%sc -l myfiles = ls ~" should now be written as |
|
441 | "%sc -l myfiles = ls ~" should now be written as | |
442 |
|
442 | |||
443 | "myfiles = !ls ~" |
|
443 | "myfiles = !ls ~" | |
444 |
|
444 | |||
445 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
445 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
446 | below. |
|
446 | below. | |
447 |
|
447 | |||
448 | -- |
|
448 | -- | |
449 | %sc [options] varname=command |
|
449 | %sc [options] varname=command | |
450 |
|
450 | |||
451 | IPython will run the given command using commands.getoutput(), and |
|
451 | IPython will run the given command using commands.getoutput(), and | |
452 | will then update the user's interactive namespace with a variable |
|
452 | will then update the user's interactive namespace with a variable | |
453 | called varname, containing the value of the call. Your command can |
|
453 | called varname, containing the value of the call. Your command can | |
454 | contain shell wildcards, pipes, etc. |
|
454 | contain shell wildcards, pipes, etc. | |
455 |
|
455 | |||
456 | The '=' sign in the syntax is mandatory, and the variable name you |
|
456 | The '=' sign in the syntax is mandatory, and the variable name you | |
457 | supply must follow Python's standard conventions for valid names. |
|
457 | supply must follow Python's standard conventions for valid names. | |
458 |
|
458 | |||
459 | (A special format without variable name exists for internal use) |
|
459 | (A special format without variable name exists for internal use) | |
460 |
|
460 | |||
461 | Options: |
|
461 | Options: | |
462 |
|
462 | |||
463 | -l: list output. Split the output on newlines into a list before |
|
463 | -l: list output. Split the output on newlines into a list before | |
464 | assigning it to the given variable. By default the output is stored |
|
464 | assigning it to the given variable. By default the output is stored | |
465 | as a single string. |
|
465 | as a single string. | |
466 |
|
466 | |||
467 | -v: verbose. Print the contents of the variable. |
|
467 | -v: verbose. Print the contents of the variable. | |
468 |
|
468 | |||
469 | In most cases you should not need to split as a list, because the |
|
469 | In most cases you should not need to split as a list, because the | |
470 | returned value is a special type of string which can automatically |
|
470 | returned value is a special type of string which can automatically | |
471 | provide its contents either as a list (split on newlines) or as a |
|
471 | provide its contents either as a list (split on newlines) or as a | |
472 | space-separated string. These are convenient, respectively, either |
|
472 | space-separated string. These are convenient, respectively, either | |
473 | for sequential processing or to be passed to a shell command. |
|
473 | for sequential processing or to be passed to a shell command. | |
474 |
|
474 | |||
475 | For example:: |
|
475 | For example:: | |
476 |
|
476 | |||
477 | # Capture into variable a |
|
477 | # Capture into variable a | |
478 | In [1]: sc a=ls *py |
|
478 | In [1]: sc a=ls *py | |
479 |
|
479 | |||
480 | # a is a string with embedded newlines |
|
480 | # a is a string with embedded newlines | |
481 | In [2]: a |
|
481 | In [2]: a | |
482 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
482 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
483 |
|
483 | |||
484 | # which can be seen as a list: |
|
484 | # which can be seen as a list: | |
485 | In [3]: a.l |
|
485 | In [3]: a.l | |
486 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
486 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
487 |
|
487 | |||
488 | # or as a whitespace-separated string: |
|
488 | # or as a whitespace-separated string: | |
489 | In [4]: a.s |
|
489 | In [4]: a.s | |
490 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
490 | Out[4]: 'setup.py win32_manual_post_install.py' | |
491 |
|
491 | |||
492 | # a.s is useful to pass as a single command line: |
|
492 | # a.s is useful to pass as a single command line: | |
493 | In [5]: !wc -l $a.s |
|
493 | In [5]: !wc -l $a.s | |
494 | 146 setup.py |
|
494 | 146 setup.py | |
495 | 130 win32_manual_post_install.py |
|
495 | 130 win32_manual_post_install.py | |
496 | 276 total |
|
496 | 276 total | |
497 |
|
497 | |||
498 | # while the list form is useful to loop over: |
|
498 | # while the list form is useful to loop over: | |
499 | In [6]: for f in a.l: |
|
499 | In [6]: for f in a.l: | |
500 | ...: !wc -l $f |
|
500 | ...: !wc -l $f | |
501 | ...: |
|
501 | ...: | |
502 | 146 setup.py |
|
502 | 146 setup.py | |
503 | 130 win32_manual_post_install.py |
|
503 | 130 win32_manual_post_install.py | |
504 |
|
504 | |||
505 | Similarly, the lists returned by the -l option are also special, in |
|
505 | Similarly, the lists returned by the -l option are also special, in | |
506 | the sense that you can equally invoke the .s attribute on them to |
|
506 | the sense that you can equally invoke the .s attribute on them to | |
507 | automatically get a whitespace-separated string from their contents:: |
|
507 | automatically get a whitespace-separated string from their contents:: | |
508 |
|
508 | |||
509 | In [7]: sc -l b=ls *py |
|
509 | In [7]: sc -l b=ls *py | |
510 |
|
510 | |||
511 | In [8]: b |
|
511 | In [8]: b | |
512 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
512 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
513 |
|
513 | |||
514 | In [9]: b.s |
|
514 | In [9]: b.s | |
515 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
515 | Out[9]: 'setup.py win32_manual_post_install.py' | |
516 |
|
516 | |||
517 | In summary, both the lists and strings used for output capture have |
|
517 | In summary, both the lists and strings used for output capture have | |
518 | the following special attributes:: |
|
518 | the following special attributes:: | |
519 |
|
519 | |||
520 | .l (or .list) : value as list. |
|
520 | .l (or .list) : value as list. | |
521 | .n (or .nlstr): value as newline-separated string. |
|
521 | .n (or .nlstr): value as newline-separated string. | |
522 | .s (or .spstr): value as space-separated string. |
|
522 | .s (or .spstr): value as space-separated string. | |
523 | """ |
|
523 | """ | |
524 |
|
524 | |||
525 | opts,args = self.parse_options(parameter_s,'lv') |
|
525 | opts,args = self.parse_options(parameter_s, 'lv') | |
526 | # Try to get a variable name and command to run |
|
526 | # Try to get a variable name and command to run | |
527 | try: |
|
527 | try: | |
528 | # the variable name must be obtained from the parse_options |
|
528 | # the variable name must be obtained from the parse_options | |
529 | # output, which uses shlex.split to strip options out. |
|
529 | # output, which uses shlex.split to strip options out. | |
530 | var,_ = args.split('=',1) |
|
530 | var,_ = args.split('=', 1) | |
531 | var = var.strip() |
|
531 | var = var.strip() | |
532 | # But the command has to be extracted from the original input |
|
532 | # But the command has to be extracted from the original input | |
533 | # parameter_s, not on what parse_options returns, to avoid the |
|
533 | # parameter_s, not on what parse_options returns, to avoid the | |
534 | # quote stripping which shlex.split performs on it. |
|
534 | # quote stripping which shlex.split performs on it. | |
535 | _,cmd = parameter_s.split('=',1) |
|
535 | _,cmd = parameter_s.split('=', 1) | |
536 | except ValueError: |
|
536 | except ValueError: | |
537 | var,cmd = '','' |
|
537 | var,cmd = '','' | |
538 | # If all looks ok, proceed |
|
538 | # If all looks ok, proceed | |
539 | split = 'l' in opts |
|
539 | split = 'l' in opts | |
540 | out = self.shell.getoutput(cmd, split=split) |
|
540 | out = self.shell.getoutput(cmd, split=split) | |
541 | if 'v' in opts: |
|
541 | if 'v' in opts: | |
542 | print '%s ==\n%s' % (var,pformat(out)) |
|
542 | print '%s ==\n%s' % (var, pformat(out)) | |
543 | if var: |
|
543 | if var: | |
544 | self.shell.user_ns.update({var:out}) |
|
544 | self.shell.user_ns.update({var:out}) | |
545 | else: |
|
545 | else: | |
546 | return out |
|
546 | return out | |
547 |
|
547 | |||
548 | @line_magic |
|
548 | @line_magic | |
549 | def sx(self, parameter_s=''): |
|
549 | def sx(self, parameter_s=''): | |
550 | """Shell execute - run a shell command and capture its output. |
|
550 | """Shell execute - run a shell command and capture its output. | |
551 |
|
551 | |||
552 | %sx command |
|
552 | %sx command | |
553 |
|
553 | |||
554 | IPython will run the given command using commands.getoutput(), and |
|
554 | IPython will run the given command using commands.getoutput(), and | |
555 | return the result formatted as a list (split on '\\n'). Since the |
|
555 | return the result formatted as a list (split on '\\n'). Since the | |
556 | output is _returned_, it will be stored in ipython's regular output |
|
556 | output is _returned_, it will be stored in ipython's regular output | |
557 | cache Out[N] and in the '_N' automatic variables. |
|
557 | cache Out[N] and in the '_N' automatic variables. | |
558 |
|
558 | |||
559 | Notes: |
|
559 | Notes: | |
560 |
|
560 | |||
561 | 1) If an input line begins with '!!', then %sx is automatically |
|
561 | 1) If an input line begins with '!!', then %sx is automatically | |
562 | invoked. That is, while:: |
|
562 | invoked. That is, while:: | |
563 |
|
563 | |||
564 | !ls |
|
564 | !ls | |
565 |
|
565 | |||
566 | causes ipython to simply issue system('ls'), typing:: |
|
566 | causes ipython to simply issue system('ls'), typing:: | |
567 |
|
567 | |||
568 | !!ls |
|
568 | !!ls | |
569 |
|
569 | |||
570 | is a shorthand equivalent to:: |
|
570 | is a shorthand equivalent to:: | |
571 |
|
571 | |||
572 | %sx ls |
|
572 | %sx ls | |
573 |
|
573 | |||
574 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
574 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
575 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
575 | like '%sc -l'. The reason for this is to make it as easy as possible | |
576 | to process line-oriented shell output via further python commands. |
|
576 | to process line-oriented shell output via further python commands. | |
577 | %sc is meant to provide much finer control, but requires more |
|
577 | %sc is meant to provide much finer control, but requires more | |
578 | typing. |
|
578 | typing. | |
579 |
|
579 | |||
580 | 3) Just like %sc -l, this is a list with special attributes: |
|
580 | 3) Just like %sc -l, this is a list with special attributes: | |
581 | :: |
|
581 | :: | |
582 |
|
582 | |||
583 | .l (or .list) : value as list. |
|
583 | .l (or .list) : value as list. | |
584 | .n (or .nlstr): value as newline-separated string. |
|
584 | .n (or .nlstr): value as newline-separated string. | |
585 | .s (or .spstr): value as whitespace-separated string. |
|
585 | .s (or .spstr): value as whitespace-separated string. | |
586 |
|
586 | |||
587 | This is very useful when trying to use such lists as arguments to |
|
587 | This is very useful when trying to use such lists as arguments to | |
588 | system commands.""" |
|
588 | system commands.""" | |
589 |
|
589 | |||
590 | if parameter_s: |
|
590 | if parameter_s: | |
591 | return self.shell.getoutput(parameter_s) |
|
591 | return self.shell.getoutput(parameter_s) | |
592 |
|
592 | |||
593 |
|
593 | |||
594 | @line_magic |
|
594 | @line_magic | |
595 | def bookmark(self, parameter_s=''): |
|
595 | def bookmark(self, parameter_s=''): | |
596 | """Manage IPython's bookmark system. |
|
596 | """Manage IPython's bookmark system. | |
597 |
|
597 | |||
598 | %bookmark <name> - set bookmark to current dir |
|
598 | %bookmark <name> - set bookmark to current dir | |
599 | %bookmark <name> <dir> - set bookmark to <dir> |
|
599 | %bookmark <name> <dir> - set bookmark to <dir> | |
600 | %bookmark -l - list all bookmarks |
|
600 | %bookmark -l - list all bookmarks | |
601 | %bookmark -d <name> - remove bookmark |
|
601 | %bookmark -d <name> - remove bookmark | |
602 | %bookmark -r - remove all bookmarks |
|
602 | %bookmark -r - remove all bookmarks | |
603 |
|
603 | |||
604 | You can later on access a bookmarked folder with:: |
|
604 | You can later on access a bookmarked folder with:: | |
605 |
|
605 | |||
606 | %cd -b <name> |
|
606 | %cd -b <name> | |
607 |
|
607 | |||
608 | or simply '%cd <name>' if there is no directory called <name> AND |
|
608 | or simply '%cd <name>' if there is no directory called <name> AND | |
609 | there is such a bookmark defined. |
|
609 | there is such a bookmark defined. | |
610 |
|
610 | |||
611 | Your bookmarks persist through IPython sessions, but they are |
|
611 | Your bookmarks persist through IPython sessions, but they are | |
612 | associated with each profile.""" |
|
612 | associated with each profile.""" | |
613 |
|
613 | |||
614 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
614 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
615 | if len(args) > 2: |
|
615 | if len(args) > 2: | |
616 | raise UsageError("%bookmark: too many arguments") |
|
616 | raise UsageError("%bookmark: too many arguments") | |
617 |
|
617 | |||
618 | bkms = self.shell.db.get('bookmarks',{}) |
|
618 | bkms = self.shell.db.get('bookmarks',{}) | |
619 |
|
619 | |||
620 | if 'd' in opts: |
|
620 | if 'd' in opts: | |
621 | try: |
|
621 | try: | |
622 | todel = args[0] |
|
622 | todel = args[0] | |
623 | except IndexError: |
|
623 | except IndexError: | |
624 | raise UsageError( |
|
624 | raise UsageError( | |
625 | "%bookmark -d: must provide a bookmark to delete") |
|
625 | "%bookmark -d: must provide a bookmark to delete") | |
626 | else: |
|
626 | else: | |
627 | try: |
|
627 | try: | |
628 | del bkms[todel] |
|
628 | del bkms[todel] | |
629 | except KeyError: |
|
629 | except KeyError: | |
630 | raise UsageError( |
|
630 | raise UsageError( | |
631 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
631 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
632 |
|
632 | |||
633 | elif 'r' in opts: |
|
633 | elif 'r' in opts: | |
634 | bkms = {} |
|
634 | bkms = {} | |
635 | elif 'l' in opts: |
|
635 | elif 'l' in opts: | |
636 | bks = bkms.keys() |
|
636 | bks = bkms.keys() | |
637 | bks.sort() |
|
637 | bks.sort() | |
638 | if bks: |
|
638 | if bks: | |
639 | size = max(map(len, bks)) |
|
639 | size = max(map(len, bks)) | |
640 | else: |
|
640 | else: | |
641 | size = 0 |
|
641 | size = 0 | |
642 | fmt = '%-'+str(size)+'s -> %s' |
|
642 | fmt = '%-'+str(size)+'s -> %s' | |
643 | print 'Current bookmarks:' |
|
643 | print 'Current bookmarks:' | |
644 | for bk in bks: |
|
644 | for bk in bks: | |
645 | print fmt % (bk, bkms[bk]) |
|
645 | print fmt % (bk, bkms[bk]) | |
646 | else: |
|
646 | else: | |
647 | if not args: |
|
647 | if not args: | |
648 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
648 | raise UsageError("%bookmark: You must specify the bookmark name") | |
649 | elif len(args)==1: |
|
649 | elif len(args)==1: | |
650 | bkms[args[0]] = os.getcwdu() |
|
650 | bkms[args[0]] = os.getcwdu() | |
651 | elif len(args)==2: |
|
651 | elif len(args)==2: | |
652 | bkms[args[0]] = args[1] |
|
652 | bkms[args[0]] = args[1] | |
653 | self.shell.db['bookmarks'] = bkms |
|
653 | self.shell.db['bookmarks'] = bkms | |
654 |
|
654 | |||
655 | @line_magic |
|
655 | @line_magic | |
656 | def pycat(self, parameter_s=''): |
|
656 | def pycat(self, parameter_s=''): | |
657 | """Show a syntax-highlighted file through a pager. |
|
657 | """Show a syntax-highlighted file through a pager. | |
658 |
|
658 | |||
659 | This magic is similar to the cat utility, but it will assume the file |
|
659 | This magic is similar to the cat utility, but it will assume the file | |
660 | to be Python source and will show it with syntax highlighting. """ |
|
660 | to be Python source and will show it with syntax highlighting. """ | |
661 |
|
661 | |||
662 | try: |
|
662 | try: | |
663 | filename = get_py_filename(parameter_s) |
|
663 | filename = get_py_filename(parameter_s) | |
664 | cont = file_read(filename) |
|
664 | cont = file_read(filename) | |
665 | except IOError: |
|
665 | except IOError: | |
666 | try: |
|
666 | try: | |
667 | cont = eval(parameter_s, self.shell.user_ns) |
|
667 | cont = eval(parameter_s, self.shell.user_ns) | |
668 | except NameError: |
|
668 | except NameError: | |
669 | cont = None |
|
669 | cont = None | |
670 | if cont is None: |
|
670 | if cont is None: | |
671 | print "Error: no such file or variable" |
|
671 | print "Error: no such file or variable" | |
672 | return |
|
672 | return | |
673 |
|
673 | |||
674 | page.page(self.shell.pycolorize(cont)) |
|
674 | page.page(self.shell.pycolorize(cont)) |
@@ -1,218 +1,218 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | %store magic for lightweight persistence. |
|
3 | %store magic for lightweight persistence. | |
4 |
|
4 | |||
5 | Stores variables, aliases and macros in IPython's database. |
|
5 | Stores variables, aliases and macros in IPython's database. | |
6 |
|
6 | |||
7 | To automatically restore stored variables at startup, add this to your |
|
7 | To automatically restore stored variables at startup, add this to your | |
8 | :file:`ipython_config.py` file:: |
|
8 | :file:`ipython_config.py` file:: | |
9 |
|
9 | |||
10 | c.StoreMagic.autorestore = True |
|
10 | c.StoreMagic.autorestore = True | |
11 | """ |
|
11 | """ | |
12 |
|
12 | |||
13 | import inspect, os, sys, textwrap |
|
13 | import inspect, os, sys, textwrap | |
14 |
|
14 | |||
15 | from IPython.core.error import UsageError |
|
15 | from IPython.core.error import UsageError | |
16 | from IPython.core.fakemodule import FakeModule |
|
16 | from IPython.core.fakemodule import FakeModule | |
17 | from IPython.core.magic import Magics, magics_class, line_magic |
|
17 | from IPython.core.magic import Magics, magics_class, line_magic | |
18 | from IPython.core.plugin import Plugin |
|
18 | from IPython.core.plugin import Plugin | |
19 | from IPython.testing.skipdoctest import skip_doctest |
|
19 | from IPython.testing.skipdoctest import skip_doctest | |
20 | from IPython.utils.traitlets import Bool, Instance |
|
20 | from IPython.utils.traitlets import Bool, Instance | |
21 |
|
21 | |||
22 |
|
22 | |||
23 | def restore_aliases(ip): |
|
23 | def restore_aliases(ip): | |
24 | staliases = ip.db.get('stored_aliases', {}) |
|
24 | staliases = ip.db.get('stored_aliases', {}) | |
25 | for k,v in staliases.items(): |
|
25 | for k,v in staliases.items(): | |
26 | #print "restore alias",k,v # dbg |
|
26 | #print "restore alias",k,v # dbg | |
27 | #self.alias_table[k] = v |
|
27 | #self.alias_table[k] = v | |
28 | ip.alias_manager.define_alias(k,v) |
|
28 | ip.alias_manager.define_alias(k,v) | |
29 |
|
29 | |||
30 |
|
30 | |||
31 | def refresh_variables(ip): |
|
31 | def refresh_variables(ip): | |
32 | db = ip.db |
|
32 | db = ip.db | |
33 | for key in db.keys('autorestore/*'): |
|
33 | for key in db.keys('autorestore/*'): | |
34 | # strip autorestore |
|
34 | # strip autorestore | |
35 | justkey = os.path.basename(key) |
|
35 | justkey = os.path.basename(key) | |
36 | try: |
|
36 | try: | |
37 | obj = db[key] |
|
37 | obj = db[key] | |
38 | except KeyError: |
|
38 | except KeyError: | |
39 | print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey |
|
39 | print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey | |
40 | print "The error was:", sys.exc_info()[0] |
|
40 | print "The error was:", sys.exc_info()[0] | |
41 | else: |
|
41 | else: | |
42 | #print "restored",justkey,"=",obj #dbg |
|
42 | #print "restored",justkey,"=",obj #dbg | |
43 | ip.user_ns[justkey] = obj |
|
43 | ip.user_ns[justkey] = obj | |
44 |
|
44 | |||
45 |
|
45 | |||
46 | def restore_dhist(ip): |
|
46 | def restore_dhist(ip): | |
47 | ip.user_ns['_dh'] = ip.db.get('dhist',[]) |
|
47 | ip.user_ns['_dh'] = ip.db.get('dhist',[]) | |
48 |
|
48 | |||
49 |
|
49 | |||
50 | def restore_data(ip): |
|
50 | def restore_data(ip): | |
51 | refresh_variables(ip) |
|
51 | refresh_variables(ip) | |
52 | restore_aliases(ip) |
|
52 | restore_aliases(ip) | |
53 | restore_dhist(ip) |
|
53 | restore_dhist(ip) | |
54 |
|
54 | |||
55 |
|
55 | |||
56 | @magics_class |
|
56 | @magics_class | |
57 | class StoreMagics(Magics): |
|
57 | class StoreMagics(Magics): | |
58 | """Lightweight persistence for python variables. |
|
58 | """Lightweight persistence for python variables. | |
59 |
|
59 | |||
60 | Provides the %store magic.""" |
|
60 | Provides the %store magic.""" | |
61 |
|
61 | |||
62 | @skip_doctest |
|
62 | @skip_doctest | |
63 | @line_magic |
|
63 | @line_magic | |
64 | def store(self, parameter_s=''): |
|
64 | def store(self, parameter_s=''): | |
65 | """Lightweight persistence for python variables. |
|
65 | """Lightweight persistence for python variables. | |
66 |
|
66 | |||
67 | Example:: |
|
67 | Example:: | |
68 |
|
68 | |||
69 | In [1]: l = ['hello',10,'world'] |
|
69 | In [1]: l = ['hello',10,'world'] | |
70 | In [2]: %store l |
|
70 | In [2]: %store l | |
71 | In [3]: exit |
|
71 | In [3]: exit | |
72 |
|
72 | |||
73 | (IPython session is closed and started again...) |
|
73 | (IPython session is closed and started again...) | |
74 |
|
74 | |||
75 | ville@badger:~$ ipython |
|
75 | ville@badger:~$ ipython | |
76 | In [1]: l |
|
76 | In [1]: l | |
77 | Out[1]: ['hello', 10, 'world'] |
|
77 | Out[1]: ['hello', 10, 'world'] | |
78 |
|
78 | |||
79 | Usage: |
|
79 | Usage: | |
80 |
|
80 | |||
81 | * ``%store`` - Show list of all variables and their current |
|
81 | * ``%store`` - Show list of all variables and their current | |
82 | values |
|
82 | values | |
83 | * ``%store spam`` - Store the *current* value of the variable spam |
|
83 | * ``%store spam`` - Store the *current* value of the variable spam | |
84 | to disk |
|
84 | to disk | |
85 | * ``%store -d spam`` - Remove the variable and its value from storage |
|
85 | * ``%store -d spam`` - Remove the variable and its value from storage | |
86 | * ``%store -z`` - Remove all variables from storage |
|
86 | * ``%store -z`` - Remove all variables from storage | |
87 | * ``%store -r`` - Refresh all variables from store (delete |
|
87 | * ``%store -r`` - Refresh all variables from store (delete | |
88 | current vals) |
|
88 | current vals) | |
89 | * ``%store foo >a.txt`` - Store value of foo to new file a.txt |
|
89 | * ``%store foo >a.txt`` - Store value of foo to new file a.txt | |
90 | * ``%store foo >>a.txt`` - Append value of foo to file a.txt |
|
90 | * ``%store foo >>a.txt`` - Append value of foo to file a.txt | |
91 |
|
91 | |||
92 | It should be noted that if you change the value of a variable, you |
|
92 | It should be noted that if you change the value of a variable, you | |
93 | need to %store it again if you want to persist the new value. |
|
93 | need to %store it again if you want to persist the new value. | |
94 |
|
94 | |||
95 | Note also that the variables will need to be pickleable; most basic |
|
95 | Note also that the variables will need to be pickleable; most basic | |
96 | python types can be safely %store'd. |
|
96 | python types can be safely %store'd. | |
97 |
|
97 | |||
98 | Also aliases can be %store'd across sessions. |
|
98 | Also aliases can be %store'd across sessions. | |
99 | """ |
|
99 | """ | |
100 |
|
100 | |||
101 | opts,argsl = self.parse_options(parameter_s,'drz',mode='string') |
|
101 | opts,argsl = self.parse_options(parameter_s,'drz',mode='string') | |
102 | args = argsl.split(None,1) |
|
102 | args = argsl.split(None,1) | |
103 | ip = self.shell |
|
103 | ip = self.shell | |
104 | db = ip.db |
|
104 | db = ip.db | |
105 | # delete |
|
105 | # delete | |
106 | if opts.has_key('d'): |
|
106 | if opts.has_key('d'): | |
107 | try: |
|
107 | try: | |
108 | todel = args[0] |
|
108 | todel = args[0] | |
109 | except IndexError: |
|
109 | except IndexError: | |
110 | raise UsageError('You must provide the variable to forget') |
|
110 | raise UsageError('You must provide the variable to forget') | |
111 | else: |
|
111 | else: | |
112 | try: |
|
112 | try: | |
113 | del db['autorestore/' + todel] |
|
113 | del db['autorestore/' + todel] | |
114 | except: |
|
114 | except: | |
115 | raise UsageError("Can't delete variable '%s'" % todel) |
|
115 | raise UsageError("Can't delete variable '%s'" % todel) | |
116 | # reset |
|
116 | # reset | |
117 | elif opts.has_key('z'): |
|
117 | elif opts.has_key('z'): | |
118 | for k in db.keys('autorestore/*'): |
|
118 | for k in db.keys('autorestore/*'): | |
119 | del db[k] |
|
119 | del db[k] | |
120 |
|
120 | |||
121 | elif opts.has_key('r'): |
|
121 | elif opts.has_key('r'): | |
122 | refresh_variables(ip) |
|
122 | refresh_variables(ip) | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | # run without arguments -> list variables & values |
|
125 | # run without arguments -> list variables & values | |
126 | elif not args: |
|
126 | elif not args: | |
127 | vars = self.db.keys('autorestore/*') |
|
127 | vars = self.db.keys('autorestore/*') | |
128 | vars.sort() |
|
128 | vars.sort() | |
129 | if vars: |
|
129 | if vars: | |
130 | size = max(map(len,vars)) |
|
130 | size = max(map(len, vars)) | |
131 | else: |
|
131 | else: | |
132 | size = 0 |
|
132 | size = 0 | |
133 |
|
133 | |||
134 | print 'Stored variables and their in-db values:' |
|
134 | print 'Stored variables and their in-db values:' | |
135 | fmt = '%-'+str(size)+'s -> %s' |
|
135 | fmt = '%-'+str(size)+'s -> %s' | |
136 | get = db.get |
|
136 | get = db.get | |
137 | for var in vars: |
|
137 | for var in vars: | |
138 | justkey = os.path.basename(var) |
|
138 | justkey = os.path.basename(var) | |
139 | # print 30 first characters from every var |
|
139 | # print 30 first characters from every var | |
140 | print fmt % (justkey,repr(get(var,'<unavailable>'))[:50]) |
|
140 | print fmt % (justkey, repr(get(var, '<unavailable>'))[:50]) | |
141 |
|
141 | |||
142 | # default action - store the variable |
|
142 | # default action - store the variable | |
143 | else: |
|
143 | else: | |
144 | # %store foo >file.txt or >>file.txt |
|
144 | # %store foo >file.txt or >>file.txt | |
145 | if len(args) > 1 and args[1].startswith('>'): |
|
145 | if len(args) > 1 and args[1].startswith('>'): | |
146 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) |
|
146 | fnam = os.path.expanduser(args[1].lstrip('>').lstrip()) | |
147 | if args[1].startswith('>>'): |
|
147 | if args[1].startswith('>>'): | |
148 | fil = open(fnam,'a') |
|
148 | fil = open(fnam, 'a') | |
149 | else: |
|
149 | else: | |
150 | fil = open(fnam,'w') |
|
150 | fil = open(fnam, 'w') | |
151 | obj = ip.ev(args[0]) |
|
151 | obj = ip.ev(args[0]) | |
152 | print "Writing '%s' (%s) to file '%s'." % (args[0], |
|
152 | print "Writing '%s' (%s) to file '%s'." % (args[0], | |
153 | obj.__class__.__name__, fnam) |
|
153 | obj.__class__.__name__, fnam) | |
154 |
|
154 | |||
155 |
|
155 | |||
156 | if not isinstance (obj,basestring): |
|
156 | if not isinstance (obj, basestring): | |
157 | from pprint import pprint |
|
157 | from pprint import pprint | |
158 | pprint(obj,fil) |
|
158 | pprint(obj, fil) | |
159 | else: |
|
159 | else: | |
160 | fil.write(obj) |
|
160 | fil.write(obj) | |
161 | if not obj.endswith('\n'): |
|
161 | if not obj.endswith('\n'): | |
162 | fil.write('\n') |
|
162 | fil.write('\n') | |
163 |
|
163 | |||
164 | fil.close() |
|
164 | fil.close() | |
165 | return |
|
165 | return | |
166 |
|
166 | |||
167 | # %store foo |
|
167 | # %store foo | |
168 | try: |
|
168 | try: | |
169 | obj = ip.user_ns[args[0]] |
|
169 | obj = ip.user_ns[args[0]] | |
170 | except KeyError: |
|
170 | except KeyError: | |
171 | # it might be an alias |
|
171 | # it might be an alias | |
172 | # This needs to be refactored to use the new AliasManager stuff. |
|
172 | # This needs to be refactored to use the new AliasManager stuff. | |
173 | if args[0] in self.alias_manager: |
|
173 | if args[0] in self.alias_manager: | |
174 | name = args[0] |
|
174 | name = args[0] | |
175 | nargs, cmd = self.alias_manager.alias_table[ name ] |
|
175 | nargs, cmd = self.alias_manager.alias_table[ name ] | |
176 | staliases = db.get('stored_aliases',{}) |
|
176 | staliases = db.get('stored_aliases',{}) | |
177 | staliases[ name ] = cmd |
|
177 | staliases[ name ] = cmd | |
178 | db['stored_aliases'] = staliases |
|
178 | db['stored_aliases'] = staliases | |
179 | print "Alias stored: %s (%s)" % (name, cmd) |
|
179 | print "Alias stored: %s (%s)" % (name, cmd) | |
180 | return |
|
180 | return | |
181 | else: |
|
181 | else: | |
182 | raise UsageError("Unknown variable '%s'" % args[0]) |
|
182 | raise UsageError("Unknown variable '%s'" % args[0]) | |
183 |
|
183 | |||
184 | else: |
|
184 | else: | |
185 | if isinstance(inspect.getmodule(obj), FakeModule): |
|
185 | if isinstance(inspect.getmodule(obj), FakeModule): | |
186 | print textwrap.dedent("""\ |
|
186 | print textwrap.dedent("""\ | |
187 | Warning:%s is %s |
|
187 | Warning:%s is %s | |
188 | Proper storage of interactively declared classes (or instances |
|
188 | Proper storage of interactively declared classes (or instances | |
189 | of those classes) is not possible! Only instances |
|
189 | of those classes) is not possible! Only instances | |
190 | of classes in real modules on file system can be %%store'd. |
|
190 | of classes in real modules on file system can be %%store'd. | |
191 | """ % (args[0], obj) ) |
|
191 | """ % (args[0], obj) ) | |
192 | return |
|
192 | return | |
193 | #pickled = pickle.dumps(obj) |
|
193 | #pickled = pickle.dumps(obj) | |
194 | self.db[ 'autorestore/' + args[0] ] = obj |
|
194 | self.db[ 'autorestore/' + args[0] ] = obj | |
195 | print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__) |
|
195 | print "Stored '%s' (%s)" % (args[0], obj.__class__.__name__) | |
196 |
|
196 | |||
197 |
|
197 | |||
198 | class StoreMagic(Plugin): |
|
198 | class StoreMagic(Plugin): | |
199 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
199 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
200 | autorestore = Bool(False, config=True) |
|
200 | autorestore = Bool(False, config=True) | |
201 |
|
201 | |||
202 | def __init__(self, shell, config): |
|
202 | def __init__(self, shell, config): | |
203 | super(StoreMagic, self).__init__(shell=shell, config=config) |
|
203 | super(StoreMagic, self).__init__(shell=shell, config=config) | |
204 | shell.register_magics(StoreMagics) |
|
204 | shell.register_magics(StoreMagics) | |
205 |
|
205 | |||
206 | if self.autorestore: |
|
206 | if self.autorestore: | |
207 | restore_data(shell) |
|
207 | restore_data(shell) | |
208 |
|
208 | |||
209 |
|
209 | |||
210 | _loaded = False |
|
210 | _loaded = False | |
211 |
|
211 | |||
212 | def load_ipython_extension(ip): |
|
212 | def load_ipython_extension(ip): | |
213 | """Load the extension in IPython.""" |
|
213 | """Load the extension in IPython.""" | |
214 | global _loaded |
|
214 | global _loaded | |
215 | if not _loaded: |
|
215 | if not _loaded: | |
216 | plugin = StoreMagic(shell=ip, config=ip.config) |
|
216 | plugin = StoreMagic(shell=ip, config=ip.config) | |
217 | ip.plugin_manager.register_plugin('storemagic', plugin) |
|
217 | ip.plugin_manager.register_plugin('storemagic', plugin) | |
218 | _loaded = True |
|
218 | _loaded = True |
General Comments 0
You need to be logged in to leave comments.
Login now