##// END OF EJS Templates
Lots of work on command line options and env vars....
Brian Granger -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,148 +1,148 b''
1 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # Set this to determine the detail of what is logged at startup.
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
16 # c.Global.log_level = 20
17
17
18 # This should be a list of importable Python modules that have an
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
23 # c.Global.extensions = [
24 # 'myextension'
24 # 'myextension'
25 # ]
25 # ]
26
26
27 # These lines are run in IPython in the user's namespace after extensions
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
29 # c.Global.exec_lines = [
30 # 'import numpy',
30 # 'import numpy',
31 # 'a = 10; b = 20',
31 # 'a = 10; b = 20',
32 # '1/0'
32 # '1/0'
33 # ]
33 # ]
34
34
35 # These files are run in IPython in the user's namespace. Files with a .py
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipythondir or be absolute paths.
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
39 # c.Global.exec_files = [
40 # 'mycode.py',
40 # 'mycode.py',
41 # 'fancy.ipy'
41 # 'fancy.ipy'
42 # ]
42 # ]
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 # c.InteractiveShell.autocall = 1
48 # c.InteractiveShell.autocall = 1
49
49
50 # c.InteractiveShell.autoedit_syntax = False
50 # c.InteractiveShell.autoedit_syntax = False
51
51
52 # c.InteractiveShell.autoindent = True
52 # c.InteractiveShell.autoindent = True
53
53
54 # c.InteractiveShell.automagic = False
54 # c.InteractiveShell.automagic = False
55
55
56 # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
57
58 # c.InteractiveShell.banner2 = "This is for extra banner text"
58 # c.InteractiveShell.banner2 = "This is for extra banner text"
59
59
60 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
62 # c.InteractiveShell.colors = 'LightBG'
62 # c.InteractiveShell.colors = 'LightBG'
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.InteractiveShell.confirm_exit = True
66 # c.InteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.InteractiveShell.editor = 'nano'
70 # c.InteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
74 # c.InteractiveShell.logfile = 'ipython_log.py'
74 # c.InteractiveShell.logfile = 'ipython_log.py'
75
75
76 # c.InteractiveShell.logappend = 'mylog.py'
76 # c.InteractiveShell.logappend = 'mylog.py'
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.InteractiveShell.pager = 'less'
80 # c.InteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
84 # c.InteractiveShell.pprint = True
84 # c.InteractiveShell.pprint = True
85
85
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 # c.InteractiveShell.prompts_pad_left = True
89 # c.InteractiveShell.prompts_pad_left = True
90
90
91 # c.InteractiveShell.quiet = False
91 # c.InteractiveShell.quiet = False
92
92
93 # Readline
93 # Readline
94 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
95
95
96 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
112 # ]
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit_names = 0
115 # c.InteractiveShell.readline_omit_names = 0
116
116
117 # c.InteractiveShell.screen_length = 0
117 # c.InteractiveShell.screen_length = 0
118
118
119 # c.InteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
122
122
123 # c.InteractiveShell.system_header = "IPython system call: "
123 # c.InteractiveShell.system_header = "IPython system call: "
124
124
125 # c.InteractiveShell.system_verbose = True
125 # c.InteractiveShell.system_verbose = True
126
126
127 # c.InteractiveShell.term_title = False
127 # c.InteractiveShell.term_title = False
128
128
129 # c.InteractiveShell.wildcards_case_sensitive = True
129 # c.InteractiveShell.wildcards_case_sensitive = True
130
130
131 # c.InteractiveShell.xmode = 'Context'
131 # c.InteractiveShell.xmode = 'Context'
132
132
133 #-----------------------------------------------------------------------------
133 #-----------------------------------------------------------------------------
134 # PrefilterManager options
134 # PrefilterManager options
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136
136
137 # c.PrefilterManager.multi_line_specials = True
137 # c.PrefilterManager.multi_line_specials = True
138
138
139 #-----------------------------------------------------------------------------
139 #-----------------------------------------------------------------------------
140 # AliasManager options
140 # AliasManager options
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142
142
143 # Do this to disable all defaults
143 # Do this to disable all defaults
144 # c.AliasManager.default_aliases = []
144 # c.AliasManager.default_aliases = []
145
145
146 # c.AliasManager.user_aliases = [
146 # c.AliasManager.user_aliases = [
147 # ('foo', 'echo Hi')
147 # ('foo', 'echo Hi')
148 # ] No newline at end of file
148 # ]
@@ -1,364 +1,364 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An application for IPython.
4 An application for IPython.
5
5
6 All top-level applications should use the classes in this module for
6 All top-level applications should use the classes in this module for
7 handling configuration and creating componenets.
7 handling configuration and creating componenets.
8
8
9 The job of an :class:`Application` is to create the master configuration
9 The job of an :class:`Application` is to create the master configuration
10 object and then create the components, passing the config to them.
10 object and then create the components, passing the config to them.
11
11
12 Authors:
12 Authors:
13
13
14 * Brian Granger
14 * Brian Granger
15 * Fernando Perez
15 * Fernando Perez
16
16
17 Notes
17 Notes
18 -----
18 -----
19 """
19 """
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Copyright (C) 2008-2009 The IPython Development Team
22 # Copyright (C) 2008-2009 The IPython Development Team
23 #
23 #
24 # Distributed under the terms of the BSD License. The full license is in
24 # Distributed under the terms of the BSD License. The full license is in
25 # the file COPYING, distributed as part of this software.
25 # the file COPYING, distributed as part of this software.
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Imports
29 # Imports
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 import logging
32 import logging
33 import os
33 import os
34 import sys
34 import sys
35
35
36 from IPython.core import release
36 from IPython.core import release
37 from IPython.utils.genutils import get_ipython_dir
37 from IPython.utils.genutils import get_ipython_dir
38 from IPython.config.loader import (
38 from IPython.config.loader import (
39 PyFileConfigLoader,
39 PyFileConfigLoader,
40 ArgParseConfigLoader,
40 ArgParseConfigLoader,
41 Config,
41 Config,
42 NoConfigDefault
42 NoConfigDefault
43 )
43 )
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Classes and functions
46 # Classes and functions
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49
49
50 class BaseAppArgParseConfigLoader(ArgParseConfigLoader):
50 class BaseAppArgParseConfigLoader(ArgParseConfigLoader):
51 """Default command line options for IPython based applications."""
51 """Default command line options for IPython based applications."""
52
52
53 def _add_other_arguments(self):
53 def _add_other_arguments(self):
54 self.parser.add_argument('-ipythondir', '--ipython-dir',
54 self.parser.add_argument('--ipython-dir',
55 dest='Global.ipythondir',type=str,
55 dest='Global.ipython_dir',type=str,
56 help='Set to override default location of Global.ipythondir.',
56 help='Set to override default location of Global.ipython_dir.',
57 default=NoConfigDefault,
57 default=NoConfigDefault,
58 metavar='Global.ipythondir')
58 metavar='Global.ipython_dir')
59 self.parser.add_argument('-p','-profile', '--profile',
59 self.parser.add_argument('-p', '--profile',
60 dest='Global.profile',type=str,
60 dest='Global.profile',type=str,
61 help='The string name of the ipython profile to be used.',
61 help='The string name of the ipython profile to be used.',
62 default=NoConfigDefault,
62 default=NoConfigDefault,
63 metavar='Global.profile')
63 metavar='Global.profile')
64 self.parser.add_argument('-log_level', '--log-level',
64 self.parser.add_argument('--log-level',
65 dest="Global.log_level",type=int,
65 dest="Global.log_level",type=int,
66 help='Set the log level (0,10,20,30,40,50). Default is 30.',
66 help='Set the log level (0,10,20,30,40,50). Default is 30.',
67 default=NoConfigDefault,
67 default=NoConfigDefault,
68 metavar='Global.log_level')
68 metavar='Global.log_level')
69 self.parser.add_argument('-config_file', '--config-file',
69 self.parser.add_argument('--config-file',
70 dest='Global.config_file',type=str,
70 dest='Global.config_file',type=str,
71 help='Set the config file name to override default.',
71 help='Set the config file name to override default.',
72 default=NoConfigDefault,
72 default=NoConfigDefault,
73 metavar='Global.config_file')
73 metavar='Global.config_file')
74
74
75
75
76 class ApplicationError(Exception):
76 class ApplicationError(Exception):
77 pass
77 pass
78
78
79
79
80 class Application(object):
80 class Application(object):
81 """Load a config, construct components and set them running."""
81 """Load a config, construct components and set them running."""
82
82
83 name = 'ipython'
83 name = 'ipython'
84 description = 'IPython: an enhanced interactive Python shell.'
84 description = 'IPython: an enhanced interactive Python shell.'
85 config_file_name = 'ipython_config.py'
85 config_file_name = 'ipython_config.py'
86 default_log_level = logging.WARN
86 default_log_level = logging.WARN
87
87
88 def __init__(self):
88 def __init__(self):
89 self._exiting = False
89 self._exiting = False
90 self.init_logger()
90 self.init_logger()
91 # Track the default and actual separately because some messages are
91 # Track the default and actual separately because some messages are
92 # only printed if we aren't using the default.
92 # only printed if we aren't using the default.
93 self.default_config_file_name = self.config_file_name
93 self.default_config_file_name = self.config_file_name
94
94
95 def init_logger(self):
95 def init_logger(self):
96 self.log = logging.getLogger(self.__class__.__name__)
96 self.log = logging.getLogger(self.__class__.__name__)
97 # This is used as the default until the command line arguments are read.
97 # This is used as the default until the command line arguments are read.
98 self.log.setLevel(self.default_log_level)
98 self.log.setLevel(self.default_log_level)
99 self._log_handler = logging.StreamHandler()
99 self._log_handler = logging.StreamHandler()
100 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
100 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
101 self._log_handler.setFormatter(self._log_formatter)
101 self._log_handler.setFormatter(self._log_formatter)
102 self.log.addHandler(self._log_handler)
102 self.log.addHandler(self._log_handler)
103
103
104 def _set_log_level(self, level):
104 def _set_log_level(self, level):
105 self.log.setLevel(level)
105 self.log.setLevel(level)
106
106
107 def _get_log_level(self):
107 def _get_log_level(self):
108 return self.log.level
108 return self.log.level
109
109
110 log_level = property(_get_log_level, _set_log_level)
110 log_level = property(_get_log_level, _set_log_level)
111
111
112 def start(self):
112 def start(self):
113 """Start the application."""
113 """Start the application."""
114 self.attempt(self.create_default_config)
114 self.attempt(self.create_default_config)
115 self.log_default_config()
115 self.log_default_config()
116 self.set_default_config_log_level()
116 self.set_default_config_log_level()
117 self.attempt(self.pre_load_command_line_config)
117 self.attempt(self.pre_load_command_line_config)
118 self.attempt(self.load_command_line_config, action='abort')
118 self.attempt(self.load_command_line_config, action='abort')
119 self.set_command_line_config_log_level()
119 self.set_command_line_config_log_level()
120 self.attempt(self.post_load_command_line_config)
120 self.attempt(self.post_load_command_line_config)
121 self.log_command_line_config()
121 self.log_command_line_config()
122 self.attempt(self.find_ipythondir)
122 self.attempt(self.find_ipython_dir)
123 self.attempt(self.find_resources)
123 self.attempt(self.find_resources)
124 self.attempt(self.find_config_file_name)
124 self.attempt(self.find_config_file_name)
125 self.attempt(self.find_config_file_paths)
125 self.attempt(self.find_config_file_paths)
126 self.attempt(self.pre_load_file_config)
126 self.attempt(self.pre_load_file_config)
127 self.attempt(self.load_file_config)
127 self.attempt(self.load_file_config)
128 self.set_file_config_log_level()
128 self.set_file_config_log_level()
129 self.attempt(self.post_load_file_config)
129 self.attempt(self.post_load_file_config)
130 self.log_file_config()
130 self.log_file_config()
131 self.attempt(self.merge_configs)
131 self.attempt(self.merge_configs)
132 self.log_master_config()
132 self.log_master_config()
133 self.attempt(self.pre_construct)
133 self.attempt(self.pre_construct)
134 self.attempt(self.construct)
134 self.attempt(self.construct)
135 self.attempt(self.post_construct)
135 self.attempt(self.post_construct)
136 self.attempt(self.start_app)
136 self.attempt(self.start_app)
137
137
138 #-------------------------------------------------------------------------
138 #-------------------------------------------------------------------------
139 # Various stages of Application creation
139 # Various stages of Application creation
140 #-------------------------------------------------------------------------
140 #-------------------------------------------------------------------------
141
141
142 def create_default_config(self):
142 def create_default_config(self):
143 """Create defaults that can't be set elsewhere.
143 """Create defaults that can't be set elsewhere.
144
144
145 For the most part, we try to set default in the class attributes
145 For the most part, we try to set default in the class attributes
146 of Components. But, defaults the top-level Application (which is
146 of Components. But, defaults the top-level Application (which is
147 not a HasTraitlets or Component) are not set in this way. Instead
147 not a HasTraitlets or Component) are not set in this way. Instead
148 we set them here. The Global section is for variables like this that
148 we set them here. The Global section is for variables like this that
149 don't belong to a particular component.
149 don't belong to a particular component.
150 """
150 """
151 self.default_config = Config()
151 self.default_config = Config()
152 self.default_config.Global.ipythondir = get_ipython_dir()
152 self.default_config.Global.ipython_dir = get_ipython_dir()
153 self.default_config.Global.log_level = self.log_level
153 self.default_config.Global.log_level = self.log_level
154
154
155 def log_default_config(self):
155 def log_default_config(self):
156 self.log.debug('Default config loaded:')
156 self.log.debug('Default config loaded:')
157 self.log.debug(repr(self.default_config))
157 self.log.debug(repr(self.default_config))
158
158
159 def set_default_config_log_level(self):
159 def set_default_config_log_level(self):
160 try:
160 try:
161 self.log_level = self.default_config.Global.log_level
161 self.log_level = self.default_config.Global.log_level
162 except AttributeError:
162 except AttributeError:
163 # Fallback to the default_log_level class attribute
163 # Fallback to the default_log_level class attribute
164 pass
164 pass
165
165
166 def create_command_line_config(self):
166 def create_command_line_config(self):
167 """Create and return a command line config loader."""
167 """Create and return a command line config loader."""
168 return BaseAppArgParseConfigLoader(
168 return BaseAppArgParseConfigLoader(
169 description=self.description,
169 description=self.description,
170 version=release.version
170 version=release.version
171 )
171 )
172
172
173 def pre_load_command_line_config(self):
173 def pre_load_command_line_config(self):
174 """Do actions just before loading the command line config."""
174 """Do actions just before loading the command line config."""
175 pass
175 pass
176
176
177 def load_command_line_config(self):
177 def load_command_line_config(self):
178 """Load the command line config."""
178 """Load the command line config."""
179 loader = self.create_command_line_config()
179 loader = self.create_command_line_config()
180 self.command_line_config = loader.load_config()
180 self.command_line_config = loader.load_config()
181 self.extra_args = loader.get_extra_args()
181 self.extra_args = loader.get_extra_args()
182
182
183 def set_command_line_config_log_level(self):
183 def set_command_line_config_log_level(self):
184 try:
184 try:
185 self.log_level = self.command_line_config.Global.log_level
185 self.log_level = self.command_line_config.Global.log_level
186 except AttributeError:
186 except AttributeError:
187 pass
187 pass
188
188
189 def post_load_command_line_config(self):
189 def post_load_command_line_config(self):
190 """Do actions just after loading the command line config."""
190 """Do actions just after loading the command line config."""
191 pass
191 pass
192
192
193 def log_command_line_config(self):
193 def log_command_line_config(self):
194 self.log.debug("Command line config loaded:")
194 self.log.debug("Command line config loaded:")
195 self.log.debug(repr(self.command_line_config))
195 self.log.debug(repr(self.command_line_config))
196
196
197 def find_ipythondir(self):
197 def find_ipython_dir(self):
198 """Set the IPython directory.
198 """Set the IPython directory.
199
199
200 This sets ``self.ipythondir``, but the actual value that is passed
200 This sets ``self.ipython_dir``, but the actual value that is passed
201 to the application is kept in either ``self.default_config`` or
201 to the application is kept in either ``self.default_config`` or
202 ``self.command_line_config``. This also adds ``self.ipythondir`` to
202 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
203 ``sys.path`` so config files there can be references by other config
203 ``sys.path`` so config files there can be references by other config
204 files.
204 files.
205 """
205 """
206
206
207 try:
207 try:
208 self.ipythondir = self.command_line_config.Global.ipythondir
208 self.ipython_dir = self.command_line_config.Global.ipython_dir
209 except AttributeError:
209 except AttributeError:
210 self.ipythondir = self.default_config.Global.ipythondir
210 self.ipython_dir = self.default_config.Global.ipython_dir
211 sys.path.append(os.path.abspath(self.ipythondir))
211 sys.path.append(os.path.abspath(self.ipython_dir))
212 if not os.path.isdir(self.ipythondir):
212 if not os.path.isdir(self.ipython_dir):
213 os.makedirs(self.ipythondir, mode=0777)
213 os.makedirs(self.ipython_dir, mode=0777)
214 self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir)
214 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
215
215
216 def find_resources(self):
216 def find_resources(self):
217 """Find other resources that need to be in place.
217 """Find other resources that need to be in place.
218
218
219 Things like cluster directories need to be in place to find the
219 Things like cluster directories need to be in place to find the
220 config file. These happen right after the IPython directory has
220 config file. These happen right after the IPython directory has
221 been set.
221 been set.
222 """
222 """
223 pass
223 pass
224
224
225 def find_config_file_name(self):
225 def find_config_file_name(self):
226 """Find the config file name for this application.
226 """Find the config file name for this application.
227
227
228 This must set ``self.config_file_name`` to the filename of the
228 This must set ``self.config_file_name`` to the filename of the
229 config file to use (just the filename). The search paths for the
229 config file to use (just the filename). The search paths for the
230 config file are set in :meth:`find_config_file_paths` and then passed
230 config file are set in :meth:`find_config_file_paths` and then passed
231 to the config file loader where they are resolved to an absolute path.
231 to the config file loader where they are resolved to an absolute path.
232
232
233 If a profile has been set at the command line, this will resolve
233 If a profile has been set at the command line, this will resolve
234 it.
234 it.
235 """
235 """
236
236
237 try:
237 try:
238 self.config_file_name = self.command_line_config.Global.config_file
238 self.config_file_name = self.command_line_config.Global.config_file
239 except AttributeError:
239 except AttributeError:
240 pass
240 pass
241
241
242 try:
242 try:
243 self.profile_name = self.command_line_config.Global.profile
243 self.profile_name = self.command_line_config.Global.profile
244 name_parts = self.config_file_name.split('.')
244 name_parts = self.config_file_name.split('.')
245 name_parts.insert(1, '_' + self.profile_name + '.')
245 name_parts.insert(1, '_' + self.profile_name + '.')
246 self.config_file_name = ''.join(name_parts)
246 self.config_file_name = ''.join(name_parts)
247 except AttributeError:
247 except AttributeError:
248 pass
248 pass
249
249
250 def find_config_file_paths(self):
250 def find_config_file_paths(self):
251 """Set the search paths for resolving the config file.
251 """Set the search paths for resolving the config file.
252
252
253 This must set ``self.config_file_paths`` to a sequence of search
253 This must set ``self.config_file_paths`` to a sequence of search
254 paths to pass to the config file loader.
254 paths to pass to the config file loader.
255 """
255 """
256 self.config_file_paths = (os.getcwd(), self.ipythondir)
256 self.config_file_paths = (os.getcwd(), self.ipython_dir)
257
257
258 def pre_load_file_config(self):
258 def pre_load_file_config(self):
259 """Do actions before the config file is loaded."""
259 """Do actions before the config file is loaded."""
260 pass
260 pass
261
261
262 def load_file_config(self):
262 def load_file_config(self):
263 """Load the config file.
263 """Load the config file.
264
264
265 This tries to load the config file from disk. If successful, the
265 This tries to load the config file from disk. If successful, the
266 ``CONFIG_FILE`` config variable is set to the resolved config file
266 ``CONFIG_FILE`` config variable is set to the resolved config file
267 location. If not successful, an empty config is used.
267 location. If not successful, an empty config is used.
268 """
268 """
269 self.log.debug("Attempting to load config file: %s" % self.config_file_name)
269 self.log.debug("Attempting to load config file: %s" % self.config_file_name)
270 loader = PyFileConfigLoader(self.config_file_name,
270 loader = PyFileConfigLoader(self.config_file_name,
271 path=self.config_file_paths)
271 path=self.config_file_paths)
272 try:
272 try:
273 self.file_config = loader.load_config()
273 self.file_config = loader.load_config()
274 self.file_config.Global.config_file = loader.full_filename
274 self.file_config.Global.config_file = loader.full_filename
275 except IOError:
275 except IOError:
276 # Only warn if the default config file was NOT being used.
276 # Only warn if the default config file was NOT being used.
277 if not self.config_file_name==self.default_config_file_name:
277 if not self.config_file_name==self.default_config_file_name:
278 self.log.warn("Config file not found, skipping: %s" % \
278 self.log.warn("Config file not found, skipping: %s" % \
279 self.config_file_name, exc_info=True)
279 self.config_file_name, exc_info=True)
280 self.file_config = Config()
280 self.file_config = Config()
281 except:
281 except:
282 self.log.warn("Error loading config file: %s" % \
282 self.log.warn("Error loading config file: %s" % \
283 self.config_file_name, exc_info=True)
283 self.config_file_name, exc_info=True)
284 self.file_config = Config()
284 self.file_config = Config()
285
285
286 def set_file_config_log_level(self):
286 def set_file_config_log_level(self):
287 # We need to keeep self.log_level updated. But we only use the value
287 # We need to keeep self.log_level updated. But we only use the value
288 # of the file_config if a value was not specified at the command
288 # of the file_config if a value was not specified at the command
289 # line, because the command line overrides everything.
289 # line, because the command line overrides everything.
290 if not hasattr(self.command_line_config.Global, 'log_level'):
290 if not hasattr(self.command_line_config.Global, 'log_level'):
291 try:
291 try:
292 self.log_level = self.file_config.Global.log_level
292 self.log_level = self.file_config.Global.log_level
293 except AttributeError:
293 except AttributeError:
294 pass # Use existing value
294 pass # Use existing value
295
295
296 def post_load_file_config(self):
296 def post_load_file_config(self):
297 """Do actions after the config file is loaded."""
297 """Do actions after the config file is loaded."""
298 pass
298 pass
299
299
300 def log_file_config(self):
300 def log_file_config(self):
301 if hasattr(self.file_config.Global, 'config_file'):
301 if hasattr(self.file_config.Global, 'config_file'):
302 self.log.debug("Config file loaded: %s" % self.file_config.Global.config_file)
302 self.log.debug("Config file loaded: %s" % self.file_config.Global.config_file)
303 self.log.debug(repr(self.file_config))
303 self.log.debug(repr(self.file_config))
304
304
305 def merge_configs(self):
305 def merge_configs(self):
306 """Merge the default, command line and file config objects."""
306 """Merge the default, command line and file config objects."""
307 config = Config()
307 config = Config()
308 config._merge(self.default_config)
308 config._merge(self.default_config)
309 config._merge(self.file_config)
309 config._merge(self.file_config)
310 config._merge(self.command_line_config)
310 config._merge(self.command_line_config)
311 self.master_config = config
311 self.master_config = config
312
312
313 def log_master_config(self):
313 def log_master_config(self):
314 self.log.debug("Master config created:")
314 self.log.debug("Master config created:")
315 self.log.debug(repr(self.master_config))
315 self.log.debug(repr(self.master_config))
316
316
317 def pre_construct(self):
317 def pre_construct(self):
318 """Do actions after the config has been built, but before construct."""
318 """Do actions after the config has been built, but before construct."""
319 pass
319 pass
320
320
321 def construct(self):
321 def construct(self):
322 """Construct the main components that make up this app."""
322 """Construct the main components that make up this app."""
323 self.log.debug("Constructing components for application")
323 self.log.debug("Constructing components for application")
324
324
325 def post_construct(self):
325 def post_construct(self):
326 """Do actions after construct, but before starting the app."""
326 """Do actions after construct, but before starting the app."""
327 pass
327 pass
328
328
329 def start_app(self):
329 def start_app(self):
330 """Actually start the app."""
330 """Actually start the app."""
331 self.log.debug("Starting application")
331 self.log.debug("Starting application")
332
332
333 #-------------------------------------------------------------------------
333 #-------------------------------------------------------------------------
334 # Utility methods
334 # Utility methods
335 #-------------------------------------------------------------------------
335 #-------------------------------------------------------------------------
336
336
337 def abort(self):
337 def abort(self):
338 """Abort the starting of the application."""
338 """Abort the starting of the application."""
339 if self._exiting:
339 if self._exiting:
340 pass
340 pass
341 else:
341 else:
342 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
342 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
343 self._exiting = True
343 self._exiting = True
344 sys.exit(1)
344 sys.exit(1)
345
345
346 def exit(self):
346 def exit(self):
347 if self._exiting:
347 if self._exiting:
348 pass
348 pass
349 else:
349 else:
350 self.log.debug("Exiting application: %s" % self.name)
350 self.log.debug("Exiting application: %s" % self.name)
351 self._exiting = True
351 self._exiting = True
352 sys.exit(1)
352 sys.exit(1)
353
353
354 def attempt(self, func, action='abort'):
354 def attempt(self, func, action='abort'):
355 try:
355 try:
356 func()
356 func()
357 except SystemExit:
357 except SystemExit:
358 raise
358 raise
359 except:
359 except:
360 if action == 'abort':
360 if action == 'abort':
361 self.abort()
361 self.abort()
362 elif action == 'exit':
362 elif action == 'exit':
363 self.exit()
363 self.exit()
364
364
@@ -1,229 +1,229 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4
4
5 Authors
5 Authors
6 -------
6 -------
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
7 - Fernando Perez <Fernando.Perez@berkeley.edu>
8 """
8 """
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2008-2009 The IPython Development Team
11 # Copyright (C) 2008-2009 The IPython Development Team
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 #****************************************************************************
18 #****************************************************************************
19 # Required modules
19 # Required modules
20
20
21 # From the standard library
21 # From the standard library
22 import os
22 import os
23 import sys
23 import sys
24 from pprint import pformat
24 from pprint import pformat
25
25
26 # Our own
26 # Our own
27 from IPython.core import release
27 from IPython.core import release
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.external.Itpl import itpl
29 from IPython.external.Itpl import itpl
30
30
31 from IPython.utils.genutils import *
31 from IPython.utils.genutils import *
32
32
33 #****************************************************************************
33 #****************************************************************************
34 class CrashHandler:
34 class CrashHandler:
35 """Customizable crash handlers for IPython-based systems.
35 """Customizable crash handlers for IPython-based systems.
36
36
37 Instances of this class provide a __call__ method which can be used as a
37 Instances of this class provide a __call__ method which can be used as a
38 sys.excepthook, i.e., the __call__ signature is:
38 sys.excepthook, i.e., the __call__ signature is:
39
39
40 def __call__(self,etype, evalue, etb)
40 def __call__(self,etype, evalue, etb)
41
41
42 """
42 """
43
43
44 def __init__(self,IP,app_name,contact_name,contact_email,
44 def __init__(self,IP,app_name,contact_name,contact_email,
45 bug_tracker,crash_report_fname,
45 bug_tracker,crash_report_fname,
46 show_crash_traceback=True):
46 show_crash_traceback=True):
47 """New crash handler.
47 """New crash handler.
48
48
49 Inputs:
49 Inputs:
50
50
51 - IP: a running IPython instance, which will be queried at crash time
51 - IP: a running IPython instance, which will be queried at crash time
52 for internal information.
52 for internal information.
53
53
54 - app_name: a string containing the name of your application.
54 - app_name: a string containing the name of your application.
55
55
56 - contact_name: a string with the name of the person to contact.
56 - contact_name: a string with the name of the person to contact.
57
57
58 - contact_email: a string with the email address of the contact.
58 - contact_email: a string with the email address of the contact.
59
59
60 - bug_tracker: a string with the URL for your project's bug tracker.
60 - bug_tracker: a string with the URL for your project's bug tracker.
61
61
62 - crash_report_fname: a string with the filename for the crash report
62 - crash_report_fname: a string with the filename for the crash report
63 to be saved in. These reports are left in the ipython user directory
63 to be saved in. These reports are left in the ipython user directory
64 as determined by the running IPython instance.
64 as determined by the running IPython instance.
65
65
66 Optional inputs:
66 Optional inputs:
67
67
68 - show_crash_traceback(True): if false, don't print the crash
68 - show_crash_traceback(True): if false, don't print the crash
69 traceback on stderr, only generate the on-disk report
69 traceback on stderr, only generate the on-disk report
70
70
71
71
72 Non-argument instance attributes:
72 Non-argument instance attributes:
73
73
74 These instances contain some non-argument attributes which allow for
74 These instances contain some non-argument attributes which allow for
75 further customization of the crash handler's behavior. Please see the
75 further customization of the crash handler's behavior. Please see the
76 source for further details.
76 source for further details.
77 """
77 """
78
78
79 # apply args into instance
79 # apply args into instance
80 self.IP = IP # IPython instance
80 self.IP = IP # IPython instance
81 self.app_name = app_name
81 self.app_name = app_name
82 self.contact_name = contact_name
82 self.contact_name = contact_name
83 self.contact_email = contact_email
83 self.contact_email = contact_email
84 self.bug_tracker = bug_tracker
84 self.bug_tracker = bug_tracker
85 self.crash_report_fname = crash_report_fname
85 self.crash_report_fname = crash_report_fname
86 self.show_crash_traceback = show_crash_traceback
86 self.show_crash_traceback = show_crash_traceback
87
87
88 # Hardcoded defaults, which can be overridden either by subclasses or
88 # Hardcoded defaults, which can be overridden either by subclasses or
89 # at runtime for the instance.
89 # at runtime for the instance.
90
90
91 # Template for the user message. Subclasses which completely override
91 # Template for the user message. Subclasses which completely override
92 # this, or user apps, can modify it to suit their tastes. It gets
92 # this, or user apps, can modify it to suit their tastes. It gets
93 # expanded using itpl, so calls of the kind $self.foo are valid.
93 # expanded using itpl, so calls of the kind $self.foo are valid.
94 self.user_message_template = """
94 self.user_message_template = """
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
95 Oops, $self.app_name crashed. We do our best to make it stable, but...
96
96
97 A crash report was automatically generated with the following information:
97 A crash report was automatically generated with the following information:
98 - A verbatim copy of the crash traceback.
98 - A verbatim copy of the crash traceback.
99 - A copy of your input history during this session.
99 - A copy of your input history during this session.
100 - Data on your current $self.app_name configuration.
100 - Data on your current $self.app_name configuration.
101
101
102 It was left in the file named:
102 It was left in the file named:
103 \t'$self.crash_report_fname'
103 \t'$self.crash_report_fname'
104 If you can email this file to the developers, the information in it will help
104 If you can email this file to the developers, the information in it will help
105 them in understanding and correcting the problem.
105 them in understanding and correcting the problem.
106
106
107 You can mail it to: $self.contact_name at $self.contact_email
107 You can mail it to: $self.contact_name at $self.contact_email
108 with the subject '$self.app_name Crash Report'.
108 with the subject '$self.app_name Crash Report'.
109
109
110 If you want to do it now, the following command will work (under Unix):
110 If you want to do it now, the following command will work (under Unix):
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
111 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
112
112
113 To ensure accurate tracking of this issue, please file a report about it at:
113 To ensure accurate tracking of this issue, please file a report about it at:
114 $self.bug_tracker
114 $self.bug_tracker
115 """
115 """
116
116
117 def __call__(self,etype, evalue, etb):
117 def __call__(self,etype, evalue, etb):
118 """Handle an exception, call for compatible with sys.excepthook"""
118 """Handle an exception, call for compatible with sys.excepthook"""
119
119
120 # Report tracebacks shouldn't use color in general (safer for users)
120 # Report tracebacks shouldn't use color in general (safer for users)
121 color_scheme = 'NoColor'
121 color_scheme = 'NoColor'
122
122
123 # Use this ONLY for developer debugging (keep commented out for release)
123 # Use this ONLY for developer debugging (keep commented out for release)
124 #color_scheme = 'Linux' # dbg
124 #color_scheme = 'Linux' # dbg
125
125
126 try:
126 try:
127 rptdir = self.IP.config.IPYTHONDIR
127 rptdir = self.IP.ipython_dir
128 except:
128 except:
129 rptdir = os.getcwd()
129 rptdir = os.getcwd()
130 if not os.path.isdir(rptdir):
130 if not os.path.isdir(rptdir):
131 rptdir = os.getcwd()
131 rptdir = os.getcwd()
132 report_name = os.path.join(rptdir,self.crash_report_fname)
132 report_name = os.path.join(rptdir,self.crash_report_fname)
133 # write the report filename into the instance dict so it can get
133 # write the report filename into the instance dict so it can get
134 # properly expanded out in the user message template
134 # properly expanded out in the user message template
135 self.crash_report_fname = report_name
135 self.crash_report_fname = report_name
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
136 TBhandler = ultratb.VerboseTB(color_scheme=color_scheme,
137 long_header=1)
137 long_header=1)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
139
140 # print traceback to screen
140 # print traceback to screen
141 if self.show_crash_traceback:
141 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
142 print >> sys.stderr, traceback
143
143
144 # and generate a complete report on disk
144 # and generate a complete report on disk
145 try:
145 try:
146 report = open(report_name,'w')
146 report = open(report_name,'w')
147 except:
147 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
148 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
149 return
150
150
151 # Inform user on stderr of what happened
151 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
152 msg = itpl('\n'+'*'*70+'\n'+self.user_message_template)
153 print >> sys.stderr, msg
153 print >> sys.stderr, msg
154
154
155 # Construct report on disk
155 # Construct report on disk
156 report.write(self.make_report(traceback))
156 report.write(self.make_report(traceback))
157 report.close()
157 report.close()
158 raw_input("Press enter to exit:")
158 raw_input("Press enter to exit:")
159
159
160 def make_report(self,traceback):
160 def make_report(self,traceback):
161 """Return a string containing a crash report."""
161 """Return a string containing a crash report."""
162
162
163 sec_sep = '\n\n'+'*'*75+'\n\n'
163 sec_sep = '\n\n'+'*'*75+'\n\n'
164
164
165 report = []
165 report = []
166 rpt_add = report.append
166 rpt_add = report.append
167
167
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
168 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
169 rpt_add('IPython version: %s \n\n' % release.version)
169 rpt_add('IPython version: %s \n\n' % release.version)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
170 rpt_add('BZR revision : %s \n\n' % release.revision)
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
171 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
172 (os.name,sys.platform) )
172 (os.name,sys.platform) )
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
173 rpt_add(sec_sep+'Current user configuration structure:\n\n')
174 rpt_add(pformat(self.IP.dict()))
174 rpt_add(pformat(self.IP.dict()))
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
175 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 try:
176 try:
177 rpt_add(sec_sep+"History of session input:")
177 rpt_add(sec_sep+"History of session input:")
178 for line in self.IP.user_ns['_ih']:
178 for line in self.IP.user_ns['_ih']:
179 rpt_add(line)
179 rpt_add(line)
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
180 rpt_add('\n*** Last line of input (may not be in above history):\n')
181 rpt_add(self.IP._last_input_line+'\n')
181 rpt_add(self.IP._last_input_line+'\n')
182 except:
182 except:
183 pass
183 pass
184
184
185 return ''.join(report)
185 return ''.join(report)
186
186
187 class IPythonCrashHandler(CrashHandler):
187 class IPythonCrashHandler(CrashHandler):
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
188 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
189
189
190 def __init__(self,IP):
190 def __init__(self,IP):
191
191
192 # Set here which of the IPython authors should be listed as contact
192 # Set here which of the IPython authors should be listed as contact
193 AUTHOR_CONTACT = 'Fernando'
193 AUTHOR_CONTACT = 'Fernando'
194
194
195 # Set argument defaults
195 # Set argument defaults
196 app_name = 'IPython'
196 app_name = 'IPython'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
197 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
198 contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2]
199 crash_report_fname = 'IPython_crash_report.txt'
199 crash_report_fname = 'IPython_crash_report.txt'
200 # Call parent constructor
200 # Call parent constructor
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
201 CrashHandler.__init__(self,IP,app_name,contact_name,contact_email,
202 bug_tracker,crash_report_fname)
202 bug_tracker,crash_report_fname)
203
203
204 def make_report(self,traceback):
204 def make_report(self,traceback):
205 """Return a string containing a crash report."""
205 """Return a string containing a crash report."""
206
206
207 sec_sep = '\n\n'+'*'*75+'\n\n'
207 sec_sep = '\n\n'+'*'*75+'\n\n'
208
208
209 report = []
209 report = []
210 rpt_add = report.append
210 rpt_add = report.append
211
211
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
212 rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n')
213 rpt_add('IPython version: %s \n\n' % release.version)
213 rpt_add('IPython version: %s \n\n' % release.version)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
214 rpt_add('BZR revision : %s \n\n' % release.revision)
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
215 rpt_add('Platform info : os.name -> %s, sys.platform -> %s' %
216 (os.name,sys.platform) )
216 (os.name,sys.platform) )
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
217 rpt_add(sec_sep+'Current user configuration structure:\n\n')
218 # rpt_add(pformat(self.IP.dict()))
218 # rpt_add(pformat(self.IP.dict()))
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
219 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
220 try:
220 try:
221 rpt_add(sec_sep+"History of session input:")
221 rpt_add(sec_sep+"History of session input:")
222 for line in self.IP.user_ns['_ih']:
222 for line in self.IP.user_ns['_ih']:
223 rpt_add(line)
223 rpt_add(line)
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
224 rpt_add('\n*** Last line of input (may not be in above history):\n')
225 rpt_add(self.IP._last_input_line+'\n')
225 rpt_add(self.IP._last_input_line+'\n')
226 except:
226 except:
227 pass
227 pass
228
228
229 return ''.join(report)
229 return ''.join(report)
@@ -1,272 +1,272 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 An embedded IPython shell.
4 An embedded IPython shell.
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 from __future__ import with_statement
26 from __future__ import with_statement
27
27
28 import sys
28 import sys
29 from contextlib import nested
29 from contextlib import nested
30
30
31 from IPython.core import ultratb
31 from IPython.core import ultratb
32 from IPython.core.iplib import InteractiveShell
32 from IPython.core.iplib import InteractiveShell
33 from IPython.core.ipapp import load_default_config
33 from IPython.core.ipapp import load_default_config
34
34
35 from IPython.utils.traitlets import Bool, Str, CBool
35 from IPython.utils.traitlets import Bool, Str, CBool
36 from IPython.utils.genutils import ask_yes_no
36 from IPython.utils.genutils import ask_yes_no
37
37
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Classes and functions
40 # Classes and functions
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 # This is an additional magic that is exposed in embedded shells.
43 # This is an additional magic that is exposed in embedded shells.
44 def kill_embedded(self,parameter_s=''):
44 def kill_embedded(self,parameter_s=''):
45 """%kill_embedded : deactivate for good the current embedded IPython.
45 """%kill_embedded : deactivate for good the current embedded IPython.
46
46
47 This function (after asking for confirmation) sets an internal flag so that
47 This function (after asking for confirmation) sets an internal flag so that
48 an embedded IPython will never activate again. This is useful to
48 an embedded IPython will never activate again. This is useful to
49 permanently disable a shell that is being called inside a loop: once you've
49 permanently disable a shell that is being called inside a loop: once you've
50 figured out what you needed from it, you may then kill it and the program
50 figured out what you needed from it, you may then kill it and the program
51 will then continue to run without the interactive shell interfering again.
51 will then continue to run without the interactive shell interfering again.
52 """
52 """
53
53
54 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
54 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
55 "(y/n)? [y/N] ",'n')
55 "(y/n)? [y/N] ",'n')
56 if kill:
56 if kill:
57 self.embedded_active = False
57 self.embedded_active = False
58 print "This embedded IPython will not reactivate anymore once you exit."
58 print "This embedded IPython will not reactivate anymore once you exit."
59
59
60
60
61 class InteractiveShellEmbed(InteractiveShell):
61 class InteractiveShellEmbed(InteractiveShell):
62
62
63 dummy_mode = Bool(False)
63 dummy_mode = Bool(False)
64 exit_msg = Str('')
64 exit_msg = Str('')
65 embedded = CBool(True)
65 embedded = CBool(True)
66 embedded_active = CBool(True)
66 embedded_active = CBool(True)
67 # Like the base class display_banner is not configurable, but here it
67 # Like the base class display_banner is not configurable, but here it
68 # is True by default.
68 # is True by default.
69 display_banner = CBool(True)
69 display_banner = CBool(True)
70
70
71 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
71 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
72 user_ns=None, user_global_ns=None,
72 user_ns=None, user_global_ns=None,
73 banner1=None, banner2=None, display_banner=None,
73 banner1=None, banner2=None, display_banner=None,
74 custom_exceptions=((),None), exit_msg=''):
74 custom_exceptions=((),None), exit_msg=''):
75
75
76 self.save_sys_ipcompleter()
76 self.save_sys_ipcompleter()
77
77
78 super(InteractiveShellEmbed,self).__init__(
78 super(InteractiveShellEmbed,self).__init__(
79 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
79 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
80 user_ns=user_ns, user_global_ns=user_global_ns,
80 user_ns=user_ns, user_global_ns=user_global_ns,
81 banner1=banner1, banner2=banner2, display_banner=display_banner,
81 banner1=banner1, banner2=banner2, display_banner=display_banner,
82 custom_exceptions=custom_exceptions)
82 custom_exceptions=custom_exceptions)
83
83
84 self.exit_msg = exit_msg
84 self.exit_msg = exit_msg
85 self.define_magic("kill_embedded", kill_embedded)
85 self.define_magic("kill_embedded", kill_embedded)
86
86
87 # don't use the ipython crash handler so that user exceptions aren't
87 # don't use the ipython crash handler so that user exceptions aren't
88 # trapped
88 # trapped
89 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
89 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
90 mode=self.xmode,
90 mode=self.xmode,
91 call_pdb=self.pdb)
91 call_pdb=self.pdb)
92
92
93 self.restore_sys_ipcompleter()
93 self.restore_sys_ipcompleter()
94
94
95 def init_sys_modules(self):
95 def init_sys_modules(self):
96 pass
96 pass
97
97
98 def save_sys_ipcompleter(self):
98 def save_sys_ipcompleter(self):
99 """Save readline completer status."""
99 """Save readline completer status."""
100 try:
100 try:
101 #print 'Save completer',sys.ipcompleter # dbg
101 #print 'Save completer',sys.ipcompleter # dbg
102 self.sys_ipcompleter_orig = sys.ipcompleter
102 self.sys_ipcompleter_orig = sys.ipcompleter
103 except:
103 except:
104 pass # not nested with IPython
104 pass # not nested with IPython
105
105
106 def restore_sys_ipcompleter(self):
106 def restore_sys_ipcompleter(self):
107 """Restores the readline completer which was in place.
107 """Restores the readline completer which was in place.
108
108
109 This allows embedded IPython within IPython not to disrupt the
109 This allows embedded IPython within IPython not to disrupt the
110 parent's completion.
110 parent's completion.
111 """
111 """
112 try:
112 try:
113 self.readline.set_completer(self.sys_ipcompleter_orig)
113 self.readline.set_completer(self.sys_ipcompleter_orig)
114 sys.ipcompleter = self.sys_ipcompleter_orig
114 sys.ipcompleter = self.sys_ipcompleter_orig
115 except:
115 except:
116 pass
116 pass
117
117
118 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
118 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
119 stack_depth=1):
119 stack_depth=1):
120 """Activate the interactive interpreter.
120 """Activate the interactive interpreter.
121
121
122 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
122 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
123 the interpreter shell with the given local and global namespaces, and
123 the interpreter shell with the given local and global namespaces, and
124 optionally print a header string at startup.
124 optionally print a header string at startup.
125
125
126 The shell can be globally activated/deactivated using the
126 The shell can be globally activated/deactivated using the
127 set/get_dummy_mode methods. This allows you to turn off a shell used
127 set/get_dummy_mode methods. This allows you to turn off a shell used
128 for debugging globally.
128 for debugging globally.
129
129
130 However, *each* time you call the shell you can override the current
130 However, *each* time you call the shell you can override the current
131 state of dummy_mode with the optional keyword parameter 'dummy'. For
131 state of dummy_mode with the optional keyword parameter 'dummy'. For
132 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
132 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
133 can still have a specific call work by making it as IPShell(dummy=0).
133 can still have a specific call work by making it as IPShell(dummy=0).
134
134
135 The optional keyword parameter dummy controls whether the call
135 The optional keyword parameter dummy controls whether the call
136 actually does anything.
136 actually does anything.
137 """
137 """
138
138
139 # If the user has turned it off, go away
139 # If the user has turned it off, go away
140 if not self.embedded_active:
140 if not self.embedded_active:
141 return
141 return
142
142
143 # Normal exits from interactive mode set this flag, so the shell can't
143 # Normal exits from interactive mode set this flag, so the shell can't
144 # re-enter (it checks this variable at the start of interactive mode).
144 # re-enter (it checks this variable at the start of interactive mode).
145 self.exit_now = False
145 self.exit_now = False
146
146
147 # Allow the dummy parameter to override the global __dummy_mode
147 # Allow the dummy parameter to override the global __dummy_mode
148 if dummy or (dummy != 0 and self.dummy_mode):
148 if dummy or (dummy != 0 and self.dummy_mode):
149 return
149 return
150
150
151 if self.has_readline:
151 if self.has_readline:
152 self.set_completer()
152 self.set_completer()
153
153
154 # self.banner is auto computed
154 # self.banner is auto computed
155 if header:
155 if header:
156 self.old_banner2 = self.banner2
156 self.old_banner2 = self.banner2
157 self.banner2 = self.banner2 + '\n' + header + '\n'
157 self.banner2 = self.banner2 + '\n' + header + '\n'
158
158
159 # Call the embedding code with a stack depth of 1 so it can skip over
159 # Call the embedding code with a stack depth of 1 so it can skip over
160 # our call and get the original caller's namespaces.
160 # our call and get the original caller's namespaces.
161 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
161 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
162
162
163 self.banner2 = self.old_banner2
163 self.banner2 = self.old_banner2
164
164
165 if self.exit_msg is not None:
165 if self.exit_msg is not None:
166 print self.exit_msg
166 print self.exit_msg
167
167
168 self.restore_sys_ipcompleter()
168 self.restore_sys_ipcompleter()
169
169
170 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
170 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
171 display_banner=None):
171 display_banner=None):
172 """Embeds IPython into a running python program.
172 """Embeds IPython into a running python program.
173
173
174 Input:
174 Input:
175
175
176 - header: An optional header message can be specified.
176 - header: An optional header message can be specified.
177
177
178 - local_ns, global_ns: working namespaces. If given as None, the
178 - local_ns, global_ns: working namespaces. If given as None, the
179 IPython-initialized one is updated with __main__.__dict__, so that
179 IPython-initialized one is updated with __main__.__dict__, so that
180 program variables become visible but user-specific configuration
180 program variables become visible but user-specific configuration
181 remains possible.
181 remains possible.
182
182
183 - stack_depth: specifies how many levels in the stack to go to
183 - stack_depth: specifies how many levels in the stack to go to
184 looking for namespaces (when local_ns and global_ns are None). This
184 looking for namespaces (when local_ns and global_ns are None). This
185 allows an intermediate caller to make sure that this function gets
185 allows an intermediate caller to make sure that this function gets
186 the namespace from the intended level in the stack. By default (0)
186 the namespace from the intended level in the stack. By default (0)
187 it will get its locals and globals from the immediate caller.
187 it will get its locals and globals from the immediate caller.
188
188
189 Warning: it's possible to use this in a program which is being run by
189 Warning: it's possible to use this in a program which is being run by
190 IPython itself (via %run), but some funny things will happen (a few
190 IPython itself (via %run), but some funny things will happen (a few
191 globals get overwritten). In the future this will be cleaned up, as
191 globals get overwritten). In the future this will be cleaned up, as
192 there is no fundamental reason why it can't work perfectly."""
192 there is no fundamental reason why it can't work perfectly."""
193
193
194 # Get locals and globals from caller
194 # Get locals and globals from caller
195 if local_ns is None or global_ns is None:
195 if local_ns is None or global_ns is None:
196 call_frame = sys._getframe(stack_depth).f_back
196 call_frame = sys._getframe(stack_depth).f_back
197
197
198 if local_ns is None:
198 if local_ns is None:
199 local_ns = call_frame.f_locals
199 local_ns = call_frame.f_locals
200 if global_ns is None:
200 if global_ns is None:
201 global_ns = call_frame.f_globals
201 global_ns = call_frame.f_globals
202
202
203 # Update namespaces and fire up interpreter
203 # Update namespaces and fire up interpreter
204
204
205 # The global one is easy, we can just throw it in
205 # The global one is easy, we can just throw it in
206 self.user_global_ns = global_ns
206 self.user_global_ns = global_ns
207
207
208 # but the user/local one is tricky: ipython needs it to store internal
208 # but the user/local one is tricky: ipython needs it to store internal
209 # data, but we also need the locals. We'll copy locals in the user
209 # data, but we also need the locals. We'll copy locals in the user
210 # one, but will track what got copied so we can delete them at exit.
210 # one, but will track what got copied so we can delete them at exit.
211 # This is so that a later embedded call doesn't see locals from a
211 # This is so that a later embedded call doesn't see locals from a
212 # previous call (which most likely existed in a separate scope).
212 # previous call (which most likely existed in a separate scope).
213 local_varnames = local_ns.keys()
213 local_varnames = local_ns.keys()
214 self.user_ns.update(local_ns)
214 self.user_ns.update(local_ns)
215 #self.user_ns['local_ns'] = local_ns # dbg
215 #self.user_ns['local_ns'] = local_ns # dbg
216
216
217 # Patch for global embedding to make sure that things don't overwrite
217 # Patch for global embedding to make sure that things don't overwrite
218 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
218 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
219 # FIXME. Test this a bit more carefully (the if.. is new)
219 # FIXME. Test this a bit more carefully (the if.. is new)
220 if local_ns is None and global_ns is None:
220 if local_ns is None and global_ns is None:
221 self.user_global_ns.update(__main__.__dict__)
221 self.user_global_ns.update(__main__.__dict__)
222
222
223 # make sure the tab-completer has the correct frame information, so it
223 # make sure the tab-completer has the correct frame information, so it
224 # actually completes using the frame's locals/globals
224 # actually completes using the frame's locals/globals
225 self.set_completer_frame()
225 self.set_completer_frame()
226
226
227 with nested(self.builtin_trap, self.display_trap):
227 with nested(self.builtin_trap, self.display_trap):
228 self.interact(display_banner=display_banner)
228 self.interact(display_banner=display_banner)
229
229
230 # now, purge out the user namespace from anything we might have added
230 # now, purge out the user namespace from anything we might have added
231 # from the caller's local namespace
231 # from the caller's local namespace
232 delvar = self.user_ns.pop
232 delvar = self.user_ns.pop
233 for var in local_varnames:
233 for var in local_varnames:
234 delvar(var,None)
234 delvar(var,None)
235
235
236
236
237 _embedded_shell = None
237 _embedded_shell = None
238
238
239
239
240 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
240 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
241 display_banner=True, exit_msg=''):
241 display_banner=True, exit_msg=''):
242 """Call this to embed IPython at the current point in your program.
242 """Call this to embed IPython at the current point in your program.
243
243
244 The first invocation of this will create an :class:`InteractiveShellEmbed`
244 The first invocation of this will create an :class:`InteractiveShellEmbed`
245 instance and then call it. Consecutive calls just call the already
245 instance and then call it. Consecutive calls just call the already
246 created instance.
246 created instance.
247
247
248 Here is a simple example::
248 Here is a simple example::
249
249
250 from IPython import embed
250 from IPython import embed
251 a = 10
251 a = 10
252 b = 20
252 b = 20
253 embed('First time')
253 embed('First time')
254 c = 30
254 c = 30
255 d = 40
255 d = 40
256 embed
256 embed
257
257
258 Full customization can be done by passing a :class:`Struct` in as the
258 Full customization can be done by passing a :class:`Struct` in as the
259 config argument.
259 config argument.
260 """
260 """
261 if config is None:
261 if config is None:
262 config = load_default_config()
262 config = load_default_config()
263 config.InteractiveShellEmbed = config.InteractiveShell
263 config.InteractiveShellEmbed = config.InteractiveShell
264 global _embedded_shell
264 global _embedded_shell
265 if _embedded_shell is None:
265 if _embedded_shell is None:
266 _embedded_shell = InteractiveShellEmbed(
266 _embedded_shell = InteractiveShellEmbed(
267 config=config, usage=usage,
267 config=config, usage=usage,
268 banner1=banner1, banner2=banner2,
268 banner1=banner1, banner2=banner2,
269 display_banner=display_banner, exit_msg=exit_msg
269 display_banner=display_banner, exit_msg=exit_msg
270 )
270 )
271 _embedded_shell(header=header, stack_depth=2)
271 _embedded_shell(header=header, stack_depth=2)
272
272
@@ -1,544 +1,544 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6
6
7 Authors:
7 Authors:
8
8
9 * Brian Granger
9 * Brian Granger
10 * Fernando Perez
10 * Fernando Perez
11
11
12 Notes
12 Notes
13 -----
13 -----
14 """
14 """
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2009 The IPython Development Team
17 # Copyright (C) 2008-2009 The IPython Development Team
18 #
18 #
19 # Distributed under the terms of the BSD License. The full license is in
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Imports
24 # Imports
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 import logging
27 import logging
28 import os
28 import os
29 import sys
29 import sys
30 import warnings
30 import warnings
31
31
32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
32 from IPython.core.application import Application, BaseAppArgParseConfigLoader
33 from IPython.core import release
33 from IPython.core import release
34 from IPython.core.iplib import InteractiveShell
34 from IPython.core.iplib import InteractiveShell
35 from IPython.config.loader import (
35 from IPython.config.loader import (
36 NoConfigDefault,
36 NoConfigDefault,
37 Config,
37 Config,
38 PyFileConfigLoader
38 PyFileConfigLoader
39 )
39 )
40
40
41 from IPython.lib import inputhook
41 from IPython.lib import inputhook
42
42
43 from IPython.utils.genutils import filefind, get_ipython_dir
43 from IPython.utils.genutils import filefind, get_ipython_dir
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Utilities and helpers
46 # Utilities and helpers
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49
49
50 ipython_desc = """
50 ipython_desc = """
51 A Python shell with automatic history (input and output), dynamic object
51 A Python shell with automatic history (input and output), dynamic object
52 introspection, easier configuration, command completion, access to the system
52 introspection, easier configuration, command completion, access to the system
53 shell and more.
53 shell and more.
54 """
54 """
55
55
56 def pylab_warning():
56 def pylab_warning():
57 msg = """
57 msg = """
58
58
59 IPython's -pylab mode has been disabled until matplotlib supports this version
59 IPython's -pylab mode has been disabled until matplotlib supports this version
60 of IPython. This version of IPython has greatly improved GUI integration that
60 of IPython. This version of IPython has greatly improved GUI integration that
61 matplotlib will soon be able to take advantage of. This will eventually
61 matplotlib will soon be able to take advantage of. This will eventually
62 result in greater stability and a richer API for matplotlib under IPython.
62 result in greater stability and a richer API for matplotlib under IPython.
63 However during this transition, you will either need to use an older version
63 However during this transition, you will either need to use an older version
64 of IPython, or do the following to use matplotlib interactively::
64 of IPython, or do the following to use matplotlib interactively::
65
65
66 import matplotlib
66 import matplotlib
67 matplotlib.interactive(True)
67 matplotlib.interactive(True)
68 matplotlib.use('wxagg') # adjust for your backend
68 matplotlib.use('wxagg') # adjust for your backend
69 %gui -a wx # adjust for your GUI
69 %gui -a wx # adjust for your GUI
70 from matplotlib import pyplot as plt
70 from matplotlib import pyplot as plt
71
71
72 See the %gui magic for information on the new interface.
72 See the %gui magic for information on the new interface.
73 """
73 """
74 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
74 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
75
75
76
76
77 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
78 # Main classes and functions
78 # Main classes and functions
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80
80
81 cl_args = (
81 cl_args = (
82 (('-autocall',), dict(
82 (('--autocall',), dict(
83 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
83 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
84 help='Set the autocall value (0,1,2).',
84 help='Set the autocall value (0,1,2).',
85 metavar='InteractiveShell.autocall')
85 metavar='InteractiveShell.autocall')
86 ),
86 ),
87 (('-autoindent',), dict(
87 (('--autoindent',), dict(
88 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
88 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
89 help='Turn on autoindenting.')
89 help='Turn on autoindenting.')
90 ),
90 ),
91 (('-noautoindent',), dict(
91 (('--no-autoindent',), dict(
92 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
92 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
93 help='Turn off autoindenting.')
93 help='Turn off autoindenting.')
94 ),
94 ),
95 (('-automagic',), dict(
95 (('--automagic',), dict(
96 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
96 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
97 help='Turn on the auto calling of magic commands.')
97 help='Turn on the auto calling of magic commands.')
98 ),
98 ),
99 (('-noautomagic',), dict(
99 (('--no-automagic',), dict(
100 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
100 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
101 help='Turn off the auto calling of magic commands.')
101 help='Turn off the auto calling of magic commands.')
102 ),
102 ),
103 (('-autoedit_syntax',), dict(
103 (('--autoedit-syntax',), dict(
104 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
104 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
105 help='Turn on auto editing of files with syntax errors.')
105 help='Turn on auto editing of files with syntax errors.')
106 ),
106 ),
107 (('-noautoedit_syntax',), dict(
107 (('--no-autoedit-syntax',), dict(
108 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
108 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
109 help='Turn off auto editing of files with syntax errors.')
109 help='Turn off auto editing of files with syntax errors.')
110 ),
110 ),
111 (('-banner',), dict(
111 (('--banner',), dict(
112 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
112 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
113 help='Display a banner upon starting IPython.')
113 help='Display a banner upon starting IPython.')
114 ),
114 ),
115 (('-nobanner',), dict(
115 (('--no-banner',), dict(
116 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
116 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
117 help="Don't display a banner upon starting IPython.")
117 help="Don't display a banner upon starting IPython.")
118 ),
118 ),
119 (('-cache_size',), dict(
119 (('--cache-size',), dict(
120 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
120 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
121 help="Set the size of the output cache.",
121 help="Set the size of the output cache.",
122 metavar='InteractiveShell.cache_size')
122 metavar='InteractiveShell.cache_size')
123 ),
123 ),
124 (('-classic',), dict(
124 (('--classic',), dict(
125 action='store_true', dest='Global.classic', default=NoConfigDefault,
125 action='store_true', dest='Global.classic', default=NoConfigDefault,
126 help="Gives IPython a similar feel to the classic Python prompt.")
126 help="Gives IPython a similar feel to the classic Python prompt.")
127 ),
127 ),
128 (('-colors',), dict(
128 (('--colors',), dict(
129 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
129 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
130 help="Set the color scheme (NoColor, Linux, and LightBG).",
130 help="Set the color scheme (NoColor, Linux, and LightBG).",
131 metavar='InteractiveShell.colors')
131 metavar='InteractiveShell.colors')
132 ),
132 ),
133 (('-color_info',), dict(
133 (('--color-info',), dict(
134 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
134 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
135 help="Enable using colors for info related things.")
135 help="Enable using colors for info related things.")
136 ),
136 ),
137 (('-nocolor_info',), dict(
137 (('--no-color-info',), dict(
138 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
138 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
139 help="Disable using colors for info related things.")
139 help="Disable using colors for info related things.")
140 ),
140 ),
141 (('-confirm_exit',), dict(
141 (('--confirm-exit',), dict(
142 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
142 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
143 help="Prompt the user when existing.")
143 help="Prompt the user when existing.")
144 ),
144 ),
145 (('-noconfirm_exit',), dict(
145 (('--no-confirm-exit',), dict(
146 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
146 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
147 help="Don't prompt the user when existing.")
147 help="Don't prompt the user when existing.")
148 ),
148 ),
149 (('-deep_reload',), dict(
149 (('--deep-reload',), dict(
150 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
150 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
151 help="Enable deep (recursive) reloading by default.")
151 help="Enable deep (recursive) reloading by default.")
152 ),
152 ),
153 (('-nodeep_reload',), dict(
153 (('--no-deep-reload',), dict(
154 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
154 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
155 help="Disable deep (recursive) reloading by default.")
155 help="Disable deep (recursive) reloading by default.")
156 ),
156 ),
157 (('-editor',), dict(
157 (('--editor',), dict(
158 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
158 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
159 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
159 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
160 metavar='InteractiveShell.editor')
160 metavar='InteractiveShell.editor')
161 ),
161 ),
162 (('-log','-l'), dict(
162 (('--log','-l'), dict(
163 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
163 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
164 help="Start logging to the default file (./ipython_log.py).")
164 help="Start logging to the default file (./ipython_log.py).")
165 ),
165 ),
166 (('-logfile','-lf'), dict(
166 (('--logfile','-lf'), dict(
167 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
167 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
168 help="Start logging to logfile.",
168 help="Start logging to logfile.",
169 metavar='InteractiveShell.logfile')
169 metavar='InteractiveShell.logfile')
170 ),
170 ),
171 (('-logappend','-la'), dict(
171 (('--log-append','-la'), dict(
172 type=str, dest='InteractiveShell.logappend', default=NoConfigDefault,
172 type=str, dest='InteractiveShell.logappend', default=NoConfigDefault,
173 help="Start logging to logappend in append mode.",
173 help="Start logging to logappend in append mode.",
174 metavar='InteractiveShell.logfile')
174 metavar='InteractiveShell.logfile')
175 ),
175 ),
176 (('-pdb',), dict(
176 (('--pdb',), dict(
177 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
177 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
178 help="Enable auto calling the pdb debugger after every exception.")
178 help="Enable auto calling the pdb debugger after every exception.")
179 ),
179 ),
180 (('-nopdb',), dict(
180 (('--nopdb',), dict(
181 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
181 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
182 help="Disable auto calling the pdb debugger after every exception.")
182 help="Disable auto calling the pdb debugger after every exception.")
183 ),
183 ),
184 (('-pprint',), dict(
184 (('--pprint',), dict(
185 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
185 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
186 help="Enable auto pretty printing of results.")
186 help="Enable auto pretty printing of results.")
187 ),
187 ),
188 (('-nopprint',), dict(
188 (('--no-pprint',), dict(
189 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
189 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
190 help="Disable auto auto pretty printing of results.")
190 help="Disable auto auto pretty printing of results.")
191 ),
191 ),
192 (('-prompt_in1','-pi1'), dict(
192 (('--prompt-in1','-pi1'), dict(
193 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
193 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
194 help="Set the main input prompt ('In [\#]: ')",
194 help="Set the main input prompt ('In [\#]: ')",
195 metavar='InteractiveShell.prompt_in1')
195 metavar='InteractiveShell.prompt_in1')
196 ),
196 ),
197 (('-prompt_in2','-pi2'), dict(
197 (('--prompt-in2','-pi2'), dict(
198 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
198 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
199 help="Set the secondary input prompt (' .\D.: ')",
199 help="Set the secondary input prompt (' .\D.: ')",
200 metavar='InteractiveShell.prompt_in2')
200 metavar='InteractiveShell.prompt_in2')
201 ),
201 ),
202 (('-prompt_out','-po'), dict(
202 (('--prompt-out','-po'), dict(
203 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
203 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
204 help="Set the output prompt ('Out[\#]:')",
204 help="Set the output prompt ('Out[\#]:')",
205 metavar='InteractiveShell.prompt_out')
205 metavar='InteractiveShell.prompt_out')
206 ),
206 ),
207 (('-quick',), dict(
207 (('--quick',), dict(
208 action='store_true', dest='Global.quick', default=NoConfigDefault,
208 action='store_true', dest='Global.quick', default=NoConfigDefault,
209 help="Enable quick startup with no config files.")
209 help="Enable quick startup with no config files.")
210 ),
210 ),
211 (('-readline',), dict(
211 (('--readline',), dict(
212 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
212 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
213 help="Enable readline for command line usage.")
213 help="Enable readline for command line usage.")
214 ),
214 ),
215 (('-noreadline',), dict(
215 (('--no-readline',), dict(
216 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
216 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
217 help="Disable readline for command line usage.")
217 help="Disable readline for command line usage.")
218 ),
218 ),
219 (('-screen_length','-sl'), dict(
219 (('--screen-length','-sl'), dict(
220 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
220 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
221 help='Number of lines on screen, used to control printing of long strings.',
221 help='Number of lines on screen, used to control printing of long strings.',
222 metavar='InteractiveShell.screen_length')
222 metavar='InteractiveShell.screen_length')
223 ),
223 ),
224 (('-separate_in','-si'), dict(
224 (('--separate-in','-si'), dict(
225 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
225 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
226 help="Separator before input prompts. Default '\n'.",
226 help="Separator before input prompts. Default '\n'.",
227 metavar='InteractiveShell.separate_in')
227 metavar='InteractiveShell.separate_in')
228 ),
228 ),
229 (('-separate_out','-so'), dict(
229 (('--separate-out','-so'), dict(
230 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
230 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
231 help="Separator before output prompts. Default 0 (nothing).",
231 help="Separator before output prompts. Default 0 (nothing).",
232 metavar='InteractiveShell.separate_out')
232 metavar='InteractiveShell.separate_out')
233 ),
233 ),
234 (('-separate_out2','-so2'), dict(
234 (('--separate-out2','-so2'), dict(
235 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
235 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
236 help="Separator after output prompts. Default 0 (nonight).",
236 help="Separator after output prompts. Default 0 (nonight).",
237 metavar='InteractiveShell.separate_out2')
237 metavar='InteractiveShell.separate_out2')
238 ),
238 ),
239 (('-nosep',), dict(
239 (('-no-sep',), dict(
240 action='store_true', dest='Global.nosep', default=NoConfigDefault,
240 action='store_true', dest='Global.nosep', default=NoConfigDefault,
241 help="Eliminate all spacing between prompts.")
241 help="Eliminate all spacing between prompts.")
242 ),
242 ),
243 (('-term_title',), dict(
243 (('--term-title',), dict(
244 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
244 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
245 help="Enable auto setting the terminal title.")
245 help="Enable auto setting the terminal title.")
246 ),
246 ),
247 (('-noterm_title',), dict(
247 (('--no-term-title',), dict(
248 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
248 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
249 help="Disable auto setting the terminal title.")
249 help="Disable auto setting the terminal title.")
250 ),
250 ),
251 (('-xmode',), dict(
251 (('--xmode',), dict(
252 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
252 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
253 help="Exception mode ('Plain','Context','Verbose')",
253 help="Exception mode ('Plain','Context','Verbose')",
254 metavar='InteractiveShell.xmode')
254 metavar='InteractiveShell.xmode')
255 ),
255 ),
256 (('-ext',), dict(
256 (('--ext',), dict(
257 type=str, dest='Global.extra_extension', default=NoConfigDefault,
257 type=str, dest='Global.extra_extension', default=NoConfigDefault,
258 help="The dotted module name of an IPython extension to load.",
258 help="The dotted module name of an IPython extension to load.",
259 metavar='Global.extra_extension')
259 metavar='Global.extra_extension')
260 ),
260 ),
261 (('-c',), dict(
261 (('-c',), dict(
262 type=str, dest='Global.code_to_run', default=NoConfigDefault,
262 type=str, dest='Global.code_to_run', default=NoConfigDefault,
263 help="Execute the given command string.",
263 help="Execute the given command string.",
264 metavar='Global.code_to_run')
264 metavar='Global.code_to_run')
265 ),
265 ),
266 (('-i',), dict(
266 (('-i',), dict(
267 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
267 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
268 help="If running code from the command line, become interactive afterwards.")
268 help="If running code from the command line, become interactive afterwards.")
269 ),
269 ),
270 (('-wthread',), dict(
270 (('--wthread',), dict(
271 action='store_true', dest='Global.wthread', default=NoConfigDefault,
271 action='store_true', dest='Global.wthread', default=NoConfigDefault,
272 help="Enable wxPython event loop integration.")
272 help="Enable wxPython event loop integration.")
273 ),
273 ),
274 (('-q4thread','-qthread'), dict(
274 (('--q4thread','--qthread'), dict(
275 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
275 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
276 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
276 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
277 ),
277 ),
278 (('-gthread',), dict(
278 (('--gthread',), dict(
279 action='store_true', dest='Global.gthread', default=NoConfigDefault,
279 action='store_true', dest='Global.gthread', default=NoConfigDefault,
280 help="Enable GTK event loop integration.")
280 help="Enable GTK event loop integration.")
281 ),
281 ),
282 # # These are only here to get the proper deprecation warnings
282 # # These are only here to get the proper deprecation warnings
283 (('-pylab',), dict(
283 (('--pylab',), dict(
284 action='store_true', dest='Global.pylab', default=NoConfigDefault,
284 action='store_true', dest='Global.pylab', default=NoConfigDefault,
285 help="Disabled. Pylab has been disabled until matplotlib "
285 help="Disabled. Pylab has been disabled until matplotlib "
286 "supports this version of IPython.")
286 "supports this version of IPython.")
287 )
287 )
288 )
288 )
289
289
290
290
291 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
291 class IPythonAppCLConfigLoader(BaseAppArgParseConfigLoader):
292
292
293 arguments = cl_args
293 arguments = cl_args
294
294
295
295
296 default_config_file_name = 'ipython_config.py'
296 default_config_file_name = 'ipython_config.py'
297
297
298
298
299 class IPythonApp(Application):
299 class IPythonApp(Application):
300 name = 'ipython'
300 name = 'ipython'
301 description = 'IPython: an enhanced interactive Python shell.'
301 description = 'IPython: an enhanced interactive Python shell.'
302 config_file_name = default_config_file_name
302 config_file_name = default_config_file_name
303
303
304 def create_default_config(self):
304 def create_default_config(self):
305 super(IPythonApp, self).create_default_config()
305 super(IPythonApp, self).create_default_config()
306 self.default_config.Global.display_banner = True
306 self.default_config.Global.display_banner = True
307
307
308 # If the -c flag is given or a file is given to run at the cmd line
308 # If the -c flag is given or a file is given to run at the cmd line
309 # like "ipython foo.py", normally we exit without starting the main
309 # like "ipython foo.py", normally we exit without starting the main
310 # loop. The force_interact config variable allows a user to override
310 # loop. The force_interact config variable allows a user to override
311 # this and interact. It is also set by the -i cmd line flag, just
311 # this and interact. It is also set by the -i cmd line flag, just
312 # like Python.
312 # like Python.
313 self.default_config.Global.force_interact = False
313 self.default_config.Global.force_interact = False
314
314
315 # By default always interact by starting the IPython mainloop.
315 # By default always interact by starting the IPython mainloop.
316 self.default_config.Global.interact = True
316 self.default_config.Global.interact = True
317
317
318 # No GUI integration by default
318 # No GUI integration by default
319 self.default_config.Global.wthread = False
319 self.default_config.Global.wthread = False
320 self.default_config.Global.q4thread = False
320 self.default_config.Global.q4thread = False
321 self.default_config.Global.gthread = False
321 self.default_config.Global.gthread = False
322
322
323 def create_command_line_config(self):
323 def create_command_line_config(self):
324 """Create and return a command line config loader."""
324 """Create and return a command line config loader."""
325 return IPythonAppCLConfigLoader(
325 return IPythonAppCLConfigLoader(
326 description=self.description,
326 description=self.description,
327 version=release.version
327 version=release.version
328 )
328 )
329
329
330 def post_load_command_line_config(self):
330 def post_load_command_line_config(self):
331 """Do actions after loading cl config."""
331 """Do actions after loading cl config."""
332 clc = self.command_line_config
332 clc = self.command_line_config
333
333
334 # Display the deprecation warnings about threaded shells
334 # Display the deprecation warnings about threaded shells
335 if hasattr(clc.Global, 'pylab'):
335 if hasattr(clc.Global, 'pylab'):
336 pylab_warning()
336 pylab_warning()
337 del clc.Global['pylab']
337 del clc.Global['pylab']
338
338
339 def load_file_config(self):
339 def load_file_config(self):
340 if hasattr(self.command_line_config.Global, 'quick'):
340 if hasattr(self.command_line_config.Global, 'quick'):
341 if self.command_line_config.Global.quick:
341 if self.command_line_config.Global.quick:
342 self.file_config = Config()
342 self.file_config = Config()
343 return
343 return
344 super(IPythonApp, self).load_file_config()
344 super(IPythonApp, self).load_file_config()
345
345
346 def post_load_file_config(self):
346 def post_load_file_config(self):
347 if hasattr(self.command_line_config.Global, 'extra_extension'):
347 if hasattr(self.command_line_config.Global, 'extra_extension'):
348 if not hasattr(self.file_config.Global, 'extensions'):
348 if not hasattr(self.file_config.Global, 'extensions'):
349 self.file_config.Global.extensions = []
349 self.file_config.Global.extensions = []
350 self.file_config.Global.extensions.append(
350 self.file_config.Global.extensions.append(
351 self.command_line_config.Global.extra_extension)
351 self.command_line_config.Global.extra_extension)
352 del self.command_line_config.Global.extra_extension
352 del self.command_line_config.Global.extra_extension
353
353
354 def pre_construct(self):
354 def pre_construct(self):
355 config = self.master_config
355 config = self.master_config
356
356
357 if hasattr(config.Global, 'classic'):
357 if hasattr(config.Global, 'classic'):
358 if config.Global.classic:
358 if config.Global.classic:
359 config.InteractiveShell.cache_size = 0
359 config.InteractiveShell.cache_size = 0
360 config.InteractiveShell.pprint = 0
360 config.InteractiveShell.pprint = 0
361 config.InteractiveShell.prompt_in1 = '>>> '
361 config.InteractiveShell.prompt_in1 = '>>> '
362 config.InteractiveShell.prompt_in2 = '... '
362 config.InteractiveShell.prompt_in2 = '... '
363 config.InteractiveShell.prompt_out = ''
363 config.InteractiveShell.prompt_out = ''
364 config.InteractiveShell.separate_in = \
364 config.InteractiveShell.separate_in = \
365 config.InteractiveShell.separate_out = \
365 config.InteractiveShell.separate_out = \
366 config.InteractiveShell.separate_out2 = ''
366 config.InteractiveShell.separate_out2 = ''
367 config.InteractiveShell.colors = 'NoColor'
367 config.InteractiveShell.colors = 'NoColor'
368 config.InteractiveShell.xmode = 'Plain'
368 config.InteractiveShell.xmode = 'Plain'
369
369
370 if hasattr(config.Global, 'nosep'):
370 if hasattr(config.Global, 'nosep'):
371 if config.Global.nosep:
371 if config.Global.nosep:
372 config.InteractiveShell.separate_in = \
372 config.InteractiveShell.separate_in = \
373 config.InteractiveShell.separate_out = \
373 config.InteractiveShell.separate_out = \
374 config.InteractiveShell.separate_out2 = ''
374 config.InteractiveShell.separate_out2 = ''
375
375
376 # if there is code of files to run from the cmd line, don't interact
376 # if there is code of files to run from the cmd line, don't interact
377 # unless the -i flag (Global.force_interact) is true.
377 # unless the -i flag (Global.force_interact) is true.
378 code_to_run = config.Global.get('code_to_run','')
378 code_to_run = config.Global.get('code_to_run','')
379 file_to_run = False
379 file_to_run = False
380 if len(self.extra_args)>=1:
380 if len(self.extra_args)>=1:
381 if self.extra_args[0]:
381 if self.extra_args[0]:
382 file_to_run = True
382 file_to_run = True
383 if file_to_run or code_to_run:
383 if file_to_run or code_to_run:
384 if not config.Global.force_interact:
384 if not config.Global.force_interact:
385 config.Global.interact = False
385 config.Global.interact = False
386
386
387 def construct(self):
387 def construct(self):
388 # I am a little hesitant to put these into InteractiveShell itself.
388 # I am a little hesitant to put these into InteractiveShell itself.
389 # But that might be the place for them
389 # But that might be the place for them
390 sys.path.insert(0, '')
390 sys.path.insert(0, '')
391
391
392 # Create an InteractiveShell instance
392 # Create an InteractiveShell instance
393 self.shell = InteractiveShell(
393 self.shell = InteractiveShell(
394 parent=None,
394 parent=None,
395 config=self.master_config
395 config=self.master_config
396 )
396 )
397
397
398 def post_construct(self):
398 def post_construct(self):
399 """Do actions after construct, but before starting the app."""
399 """Do actions after construct, but before starting the app."""
400 config = self.master_config
400 config = self.master_config
401
401
402 # shell.display_banner should always be False for the terminal
402 # shell.display_banner should always be False for the terminal
403 # based app, because we call shell.show_banner() by hand below
403 # based app, because we call shell.show_banner() by hand below
404 # so the banner shows *before* all extension loading stuff.
404 # so the banner shows *before* all extension loading stuff.
405 self.shell.display_banner = False
405 self.shell.display_banner = False
406
406
407 if config.Global.display_banner and \
407 if config.Global.display_banner and \
408 config.Global.interact:
408 config.Global.interact:
409 self.shell.show_banner()
409 self.shell.show_banner()
410
410
411 # Make sure there is a space below the banner.
411 # Make sure there is a space below the banner.
412 if self.log_level <= logging.INFO: print
412 if self.log_level <= logging.INFO: print
413
413
414 # Now a variety of things that happen after the banner is printed.
414 # Now a variety of things that happen after the banner is printed.
415 self._enable_gui()
415 self._enable_gui()
416 self._load_extensions()
416 self._load_extensions()
417 self._run_exec_lines()
417 self._run_exec_lines()
418 self._run_exec_files()
418 self._run_exec_files()
419 self._run_cmd_line_code()
419 self._run_cmd_line_code()
420
420
421 def _enable_gui(self):
421 def _enable_gui(self):
422 """Enable GUI event loop integration."""
422 """Enable GUI event loop integration."""
423 config = self.master_config
423 config = self.master_config
424 try:
424 try:
425 # Enable GUI integration
425 # Enable GUI integration
426 if config.Global.wthread:
426 if config.Global.wthread:
427 self.log.info("Enabling wx GUI event loop integration")
427 self.log.info("Enabling wx GUI event loop integration")
428 inputhook.enable_wx(app=True)
428 inputhook.enable_wx(app=True)
429 elif config.Global.q4thread:
429 elif config.Global.q4thread:
430 self.log.info("Enabling Qt4 GUI event loop integration")
430 self.log.info("Enabling Qt4 GUI event loop integration")
431 inputhook.enable_qt4(app=True)
431 inputhook.enable_qt4(app=True)
432 elif config.Global.gthread:
432 elif config.Global.gthread:
433 self.log.info("Enabling GTK GUI event loop integration")
433 self.log.info("Enabling GTK GUI event loop integration")
434 inputhook.enable_gtk(app=True)
434 inputhook.enable_gtk(app=True)
435 except:
435 except:
436 self.log.warn("Error in enabling GUI event loop integration:")
436 self.log.warn("Error in enabling GUI event loop integration:")
437 self.shell.showtraceback()
437 self.shell.showtraceback()
438
438
439 def _load_extensions(self):
439 def _load_extensions(self):
440 """Load all IPython extensions in Global.extensions.
440 """Load all IPython extensions in Global.extensions.
441
441
442 This uses the :meth:`InteractiveShell.load_extensions` to load all
442 This uses the :meth:`InteractiveShell.load_extensions` to load all
443 the extensions listed in ``self.master_config.Global.extensions``.
443 the extensions listed in ``self.master_config.Global.extensions``.
444 """
444 """
445 try:
445 try:
446 if hasattr(self.master_config.Global, 'extensions'):
446 if hasattr(self.master_config.Global, 'extensions'):
447 self.log.debug("Loading IPython extensions...")
447 self.log.debug("Loading IPython extensions...")
448 extensions = self.master_config.Global.extensions
448 extensions = self.master_config.Global.extensions
449 for ext in extensions:
449 for ext in extensions:
450 try:
450 try:
451 self.log.info("Loading IPython extension: %s" % ext)
451 self.log.info("Loading IPython extension: %s" % ext)
452 self.shell.load_extension(ext)
452 self.shell.load_extension(ext)
453 except:
453 except:
454 self.log.warn("Error in loading extension: %s" % ext)
454 self.log.warn("Error in loading extension: %s" % ext)
455 self.shell.showtraceback()
455 self.shell.showtraceback()
456 except:
456 except:
457 self.log.warn("Unknown error in loading extensions:")
457 self.log.warn("Unknown error in loading extensions:")
458 self.shell.showtraceback()
458 self.shell.showtraceback()
459
459
460 def _run_exec_lines(self):
460 def _run_exec_lines(self):
461 """Run lines of code in Global.exec_lines in the user's namespace."""
461 """Run lines of code in Global.exec_lines in the user's namespace."""
462 try:
462 try:
463 if hasattr(self.master_config.Global, 'exec_lines'):
463 if hasattr(self.master_config.Global, 'exec_lines'):
464 self.log.debug("Running code from Global.exec_lines...")
464 self.log.debug("Running code from Global.exec_lines...")
465 exec_lines = self.master_config.Global.exec_lines
465 exec_lines = self.master_config.Global.exec_lines
466 for line in exec_lines:
466 for line in exec_lines:
467 try:
467 try:
468 self.log.info("Running code in user namespace: %s" % line)
468 self.log.info("Running code in user namespace: %s" % line)
469 self.shell.runlines(line)
469 self.shell.runlines(line)
470 except:
470 except:
471 self.log.warn("Error in executing line in user namespace: %s" % line)
471 self.log.warn("Error in executing line in user namespace: %s" % line)
472 self.shell.showtraceback()
472 self.shell.showtraceback()
473 except:
473 except:
474 self.log.warn("Unknown error in handling Global.exec_lines:")
474 self.log.warn("Unknown error in handling Global.exec_lines:")
475 self.shell.showtraceback()
475 self.shell.showtraceback()
476
476
477 def _exec_file(self, fname):
477 def _exec_file(self, fname):
478 full_filename = filefind(fname, ['.', self.ipythondir])
478 full_filename = filefind(fname, ['.', self.ipython_dir])
479 if os.path.isfile(full_filename):
479 if os.path.isfile(full_filename):
480 if full_filename.endswith('.py'):
480 if full_filename.endswith('.py'):
481 self.log.info("Running file in user namespace: %s" % full_filename)
481 self.log.info("Running file in user namespace: %s" % full_filename)
482 self.shell.safe_execfile(full_filename, self.shell.user_ns)
482 self.shell.safe_execfile(full_filename, self.shell.user_ns)
483 elif full_filename.endswith('.ipy'):
483 elif full_filename.endswith('.ipy'):
484 self.log.info("Running file in user namespace: %s" % full_filename)
484 self.log.info("Running file in user namespace: %s" % full_filename)
485 self.shell.safe_execfile_ipy(full_filename)
485 self.shell.safe_execfile_ipy(full_filename)
486 else:
486 else:
487 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
487 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
488
488
489 def _run_exec_files(self):
489 def _run_exec_files(self):
490 try:
490 try:
491 if hasattr(self.master_config.Global, 'exec_files'):
491 if hasattr(self.master_config.Global, 'exec_files'):
492 self.log.debug("Running files in Global.exec_files...")
492 self.log.debug("Running files in Global.exec_files...")
493 exec_files = self.master_config.Global.exec_files
493 exec_files = self.master_config.Global.exec_files
494 for fname in exec_files:
494 for fname in exec_files:
495 self._exec_file(fname)
495 self._exec_file(fname)
496 except:
496 except:
497 self.log.warn("Unknown error in handling Global.exec_files:")
497 self.log.warn("Unknown error in handling Global.exec_files:")
498 self.shell.showtraceback()
498 self.shell.showtraceback()
499
499
500 def _run_cmd_line_code(self):
500 def _run_cmd_line_code(self):
501 if hasattr(self.master_config.Global, 'code_to_run'):
501 if hasattr(self.master_config.Global, 'code_to_run'):
502 line = self.master_config.Global.code_to_run
502 line = self.master_config.Global.code_to_run
503 try:
503 try:
504 self.log.info("Running code given at command line (-c): %s" % line)
504 self.log.info("Running code given at command line (-c): %s" % line)
505 self.shell.runlines(line)
505 self.shell.runlines(line)
506 except:
506 except:
507 self.log.warn("Error in executing line in user namespace: %s" % line)
507 self.log.warn("Error in executing line in user namespace: %s" % line)
508 self.shell.showtraceback()
508 self.shell.showtraceback()
509 return
509 return
510 # Like Python itself, ignore the second if the first of these is present
510 # Like Python itself, ignore the second if the first of these is present
511 try:
511 try:
512 fname = self.extra_args[0]
512 fname = self.extra_args[0]
513 except:
513 except:
514 pass
514 pass
515 else:
515 else:
516 try:
516 try:
517 self._exec_file(fname)
517 self._exec_file(fname)
518 except:
518 except:
519 self.log.warn("Error in executing file in user namespace: %s" % fname)
519 self.log.warn("Error in executing file in user namespace: %s" % fname)
520 self.shell.showtraceback()
520 self.shell.showtraceback()
521
521
522 def start_app(self):
522 def start_app(self):
523 if self.master_config.Global.interact:
523 if self.master_config.Global.interact:
524 self.log.debug("Starting IPython's mainloop...")
524 self.log.debug("Starting IPython's mainloop...")
525 self.shell.mainloop()
525 self.shell.mainloop()
526
526
527
527
528 def load_default_config(ipythondir=None):
528 def load_default_config(ipython_dir=None):
529 """Load the default config file from the default ipythondir.
529 """Load the default config file from the default ipython_dir.
530
530
531 This is useful for embedded shells.
531 This is useful for embedded shells.
532 """
532 """
533 if ipythondir is None:
533 if ipython_dir is None:
534 ipythondir = get_ipython_dir()
534 ipython_dir = get_ipython_dir()
535 cl = PyFileConfigLoader(default_config_file_name, ipythondir)
535 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
536 config = cl.load_config()
536 config = cl.load_config()
537 return config
537 return config
538
538
539
539
540 def launch_new_instance():
540 def launch_new_instance():
541 """Create and run a full blown IPython instance"""
541 """Create and run a full blown IPython instance"""
542 app = IPythonApp()
542 app = IPythonApp()
543 app.start()
543 app.start()
544
544
@@ -1,2488 +1,2488 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from __future__ import with_statement
19 from __future__ import with_statement
20
20
21 import __builtin__
21 import __builtin__
22 import StringIO
22 import StringIO
23 import bdb
23 import bdb
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.core import ultratb
34 from IPython.core import ultratb
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import shadowns
36 from IPython.core import shadowns
37 from IPython.core import history as ipcorehist
37 from IPython.core import history as ipcorehist
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.logger import Logger
43 from IPython.core.logger import Logger
44 from IPython.core.magic import Magic
44 from IPython.core.magic import Magic
45 from IPython.core.prompts import CachedOutput
45 from IPython.core.prompts import CachedOutput
46 from IPython.core.prefilter import PrefilterManager
46 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.component import Component
47 from IPython.core.component import Component
48 from IPython.core.usage import interactive_usage, default_banner
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
49 from IPython.core.error import TryNext, UsageError
50
50
51 from IPython.utils import pickleshare
51 from IPython.utils import pickleshare
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
54 from IPython.utils.ipstruct import Struct
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
57 from IPython.utils.genutils import get_ipython_dir
57 from IPython.utils.genutils import get_ipython_dir
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 from IPython.utils.syspathcontext import prepended_to_syspath
61
61
62 # from IPython.utils import growl
62 # from IPython.utils import growl
63 # growl.start("IPython")
63 # growl.start("IPython")
64
64
65 from IPython.utils.traitlets import (
65 from IPython.utils.traitlets import (
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 )
67 )
68
68
69 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
70 # Globals
70 # Globals
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72
72
73
73
74 # store the builtin raw_input globally, and use this always, in case user code
74 # store the builtin raw_input globally, and use this always, in case user code
75 # overwrites it (like wx.py.PyShell does)
75 # overwrites it (like wx.py.PyShell does)
76 raw_input_original = raw_input
76 raw_input_original = raw_input
77
77
78 # compiled regexps for autoindent management
78 # compiled regexps for autoindent management
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80
80
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Utilities
83 # Utilities
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86
86
87 ini_spaces_re = re.compile(r'^(\s+)')
87 ini_spaces_re = re.compile(r'^(\s+)')
88
88
89
89
90 def num_ini_spaces(strng):
90 def num_ini_spaces(strng):
91 """Return the number of initial spaces in a string"""
91 """Return the number of initial spaces in a string"""
92
92
93 ini_spaces = ini_spaces_re.match(strng)
93 ini_spaces = ini_spaces_re.match(strng)
94 if ini_spaces:
94 if ini_spaces:
95 return ini_spaces.end()
95 return ini_spaces.end()
96 else:
96 else:
97 return 0
97 return 0
98
98
99
99
100 def softspace(file, newvalue):
100 def softspace(file, newvalue):
101 """Copied from code.py, to remove the dependency"""
101 """Copied from code.py, to remove the dependency"""
102
102
103 oldvalue = 0
103 oldvalue = 0
104 try:
104 try:
105 oldvalue = file.softspace
105 oldvalue = file.softspace
106 except AttributeError:
106 except AttributeError:
107 pass
107 pass
108 try:
108 try:
109 file.softspace = newvalue
109 file.softspace = newvalue
110 except (AttributeError, TypeError):
110 except (AttributeError, TypeError):
111 # "attribute-less object" or "read-only attributes"
111 # "attribute-less object" or "read-only attributes"
112 pass
112 pass
113 return oldvalue
113 return oldvalue
114
114
115
115
116 class SpaceInInput(exceptions.Exception): pass
116 class SpaceInInput(exceptions.Exception): pass
117
117
118 class Bunch: pass
118 class Bunch: pass
119
119
120 class InputList(list):
120 class InputList(list):
121 """Class to store user input.
121 """Class to store user input.
122
122
123 It's basically a list, but slices return a string instead of a list, thus
123 It's basically a list, but slices return a string instead of a list, thus
124 allowing things like (assuming 'In' is an instance):
124 allowing things like (assuming 'In' is an instance):
125
125
126 exec In[4:7]
126 exec In[4:7]
127
127
128 or
128 or
129
129
130 exec In[5:9] + In[14] + In[21:25]"""
130 exec In[5:9] + In[14] + In[21:25]"""
131
131
132 def __getslice__(self,i,j):
132 def __getslice__(self,i,j):
133 return ''.join(list.__getslice__(self,i,j))
133 return ''.join(list.__getslice__(self,i,j))
134
134
135
135
136 class SyntaxTB(ultratb.ListTB):
136 class SyntaxTB(ultratb.ListTB):
137 """Extension which holds some state: the last exception value"""
137 """Extension which holds some state: the last exception value"""
138
138
139 def __init__(self,color_scheme = 'NoColor'):
139 def __init__(self,color_scheme = 'NoColor'):
140 ultratb.ListTB.__init__(self,color_scheme)
140 ultratb.ListTB.__init__(self,color_scheme)
141 self.last_syntax_error = None
141 self.last_syntax_error = None
142
142
143 def __call__(self, etype, value, elist):
143 def __call__(self, etype, value, elist):
144 self.last_syntax_error = value
144 self.last_syntax_error = value
145 ultratb.ListTB.__call__(self,etype,value,elist)
145 ultratb.ListTB.__call__(self,etype,value,elist)
146
146
147 def clear_err_state(self):
147 def clear_err_state(self):
148 """Return the current error state and clear it"""
148 """Return the current error state and clear it"""
149 e = self.last_syntax_error
149 e = self.last_syntax_error
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151 return e
151 return e
152
152
153
153
154 def get_default_editor():
154 def get_default_editor():
155 try:
155 try:
156 ed = os.environ['EDITOR']
156 ed = os.environ['EDITOR']
157 except KeyError:
157 except KeyError:
158 if os.name == 'posix':
158 if os.name == 'posix':
159 ed = 'vi' # the only one guaranteed to be there!
159 ed = 'vi' # the only one guaranteed to be there!
160 else:
160 else:
161 ed = 'notepad' # same in Windows!
161 ed = 'notepad' # same in Windows!
162 return ed
162 return ed
163
163
164
164
165 def get_default_colors():
165 def get_default_colors():
166 if sys.platform=='darwin':
166 if sys.platform=='darwin':
167 return "LightBG"
167 return "LightBG"
168 elif os.name=='nt':
168 elif os.name=='nt':
169 return 'Linux'
169 return 'Linux'
170 else:
170 else:
171 return 'Linux'
171 return 'Linux'
172
172
173
173
174 class SeparateStr(Str):
174 class SeparateStr(Str):
175 """A Str subclass to validate separate_in, separate_out, etc.
175 """A Str subclass to validate separate_in, separate_out, etc.
176
176
177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
178 """
178 """
179
179
180 def validate(self, obj, value):
180 def validate(self, obj, value):
181 if value == '0': value = ''
181 if value == '0': value = ''
182 value = value.replace('\\n','\n')
182 value = value.replace('\\n','\n')
183 return super(SeparateStr, self).validate(obj, value)
183 return super(SeparateStr, self).validate(obj, value)
184
184
185
185
186 #-----------------------------------------------------------------------------
186 #-----------------------------------------------------------------------------
187 # Main IPython class
187 # Main IPython class
188 #-----------------------------------------------------------------------------
188 #-----------------------------------------------------------------------------
189
189
190
190
191 class InteractiveShell(Component, Magic):
191 class InteractiveShell(Component, Magic):
192 """An enhanced, interactive shell for Python."""
192 """An enhanced, interactive shell for Python."""
193
193
194 autocall = Enum((0,1,2), default_value=1, config=True)
194 autocall = Enum((0,1,2), default_value=1, config=True)
195 autoedit_syntax = CBool(False, config=True)
195 autoedit_syntax = CBool(False, config=True)
196 autoindent = CBool(True, config=True)
196 autoindent = CBool(True, config=True)
197 automagic = CBool(True, config=True)
197 automagic = CBool(True, config=True)
198 banner = Str('')
198 banner = Str('')
199 banner1 = Str(default_banner, config=True)
199 banner1 = Str(default_banner, config=True)
200 banner2 = Str('', config=True)
200 banner2 = Str('', config=True)
201 cache_size = Int(1000, config=True)
201 cache_size = Int(1000, config=True)
202 color_info = CBool(True, config=True)
202 color_info = CBool(True, config=True)
203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
204 default_value=get_default_colors(), config=True)
204 default_value=get_default_colors(), config=True)
205 confirm_exit = CBool(True, config=True)
205 confirm_exit = CBool(True, config=True)
206 debug = CBool(False, config=True)
206 debug = CBool(False, config=True)
207 deep_reload = CBool(False, config=True)
207 deep_reload = CBool(False, config=True)
208 # This display_banner only controls whether or not self.show_banner()
208 # This display_banner only controls whether or not self.show_banner()
209 # is called when mainloop/interact are called. The default is False
209 # is called when mainloop/interact are called. The default is False
210 # because for the terminal based application, the banner behavior
210 # because for the terminal based application, the banner behavior
211 # is controlled by Global.display_banner, which IPythonApp looks at
211 # is controlled by Global.display_banner, which IPythonApp looks at
212 # to determine if *it* should call show_banner() by hand or not.
212 # to determine if *it* should call show_banner() by hand or not.
213 display_banner = CBool(False) # This isn't configurable!
213 display_banner = CBool(False) # This isn't configurable!
214 embedded = CBool(False)
214 embedded = CBool(False)
215 embedded_active = CBool(False)
215 embedded_active = CBool(False)
216 editor = Str(get_default_editor(), config=True)
216 editor = Str(get_default_editor(), config=True)
217 filename = Str("<ipython console>")
217 filename = Str("<ipython console>")
218 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
218 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
219 logstart = CBool(False, config=True)
219 logstart = CBool(False, config=True)
220 logfile = Str('', config=True)
220 logfile = Str('', config=True)
221 logappend = Str('', config=True)
221 logappend = Str('', config=True)
222 object_info_string_level = Enum((0,1,2), default_value=0,
222 object_info_string_level = Enum((0,1,2), default_value=0,
223 config=True)
223 config=True)
224 pager = Str('less', config=True)
224 pager = Str('less', config=True)
225 pdb = CBool(False, config=True)
225 pdb = CBool(False, config=True)
226 pprint = CBool(True, config=True)
226 pprint = CBool(True, config=True)
227 profile = Str('', config=True)
227 profile = Str('', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
231 prompts_pad_left = CBool(True, config=True)
231 prompts_pad_left = CBool(True, config=True)
232 quiet = CBool(False, config=True)
232 quiet = CBool(False, config=True)
233
233
234 readline_use = CBool(True, config=True)
234 readline_use = CBool(True, config=True)
235 readline_merge_completions = CBool(True, config=True)
235 readline_merge_completions = CBool(True, config=True)
236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
237 readline_remove_delims = Str('-/~', config=True)
237 readline_remove_delims = Str('-/~', config=True)
238 readline_parse_and_bind = List([
238 readline_parse_and_bind = List([
239 'tab: complete',
239 'tab: complete',
240 '"\C-l": possible-completions',
240 '"\C-l": possible-completions',
241 'set show-all-if-ambiguous on',
241 'set show-all-if-ambiguous on',
242 '"\C-o": tab-insert',
242 '"\C-o": tab-insert',
243 '"\M-i": " "',
243 '"\M-i": " "',
244 '"\M-o": "\d\d\d\d"',
244 '"\M-o": "\d\d\d\d"',
245 '"\M-I": "\d\d\d\d"',
245 '"\M-I": "\d\d\d\d"',
246 '"\C-r": reverse-search-history',
246 '"\C-r": reverse-search-history',
247 '"\C-s": forward-search-history',
247 '"\C-s": forward-search-history',
248 '"\C-p": history-search-backward',
248 '"\C-p": history-search-backward',
249 '"\C-n": history-search-forward',
249 '"\C-n": history-search-forward',
250 '"\e[A": history-search-backward',
250 '"\e[A": history-search-backward',
251 '"\e[B": history-search-forward',
251 '"\e[B": history-search-forward',
252 '"\C-k": kill-line',
252 '"\C-k": kill-line',
253 '"\C-u": unix-line-discard',
253 '"\C-u": unix-line-discard',
254 ], allow_none=False, config=True)
254 ], allow_none=False, config=True)
255
255
256 screen_length = Int(0, config=True)
256 screen_length = Int(0, config=True)
257
257
258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
259 separate_in = SeparateStr('\n', config=True)
259 separate_in = SeparateStr('\n', config=True)
260 separate_out = SeparateStr('', config=True)
260 separate_out = SeparateStr('', config=True)
261 separate_out2 = SeparateStr('', config=True)
261 separate_out2 = SeparateStr('', config=True)
262
262
263 system_header = Str('IPython system call: ', config=True)
263 system_header = Str('IPython system call: ', config=True)
264 system_verbose = CBool(False, config=True)
264 system_verbose = CBool(False, config=True)
265 term_title = CBool(False, config=True)
265 term_title = CBool(False, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 default_value='Context', config=True)
268 default_value='Context', config=True)
269
269
270 autoexec = List(allow_none=False)
270 autoexec = List(allow_none=False)
271
271
272 # class attribute to indicate whether the class supports threads or not.
272 # class attribute to indicate whether the class supports threads or not.
273 # Subclasses with thread support should override this as needed.
273 # Subclasses with thread support should override this as needed.
274 isthreaded = False
274 isthreaded = False
275
275
276 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
276 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
277 user_ns=None, user_global_ns=None,
277 user_ns=None, user_global_ns=None,
278 banner1=None, banner2=None, display_banner=None,
278 banner1=None, banner2=None, display_banner=None,
279 custom_exceptions=((),None)):
279 custom_exceptions=((),None)):
280
280
281 # This is where traitlets with a config_key argument are updated
281 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
282 # from the values on config.
283 super(InteractiveShell, self).__init__(parent, config=config)
283 super(InteractiveShell, self).__init__(parent, config=config)
284
284
285 # These are relatively independent and stateless
285 # These are relatively independent and stateless
286 self.init_ipythondir(ipythondir)
286 self.init_ipython_dir(ipython_dir)
287 self.init_instance_attrs()
287 self.init_instance_attrs()
288 self.init_term_title()
288 self.init_term_title()
289 self.init_usage(usage)
289 self.init_usage(usage)
290 self.init_banner(banner1, banner2, display_banner)
290 self.init_banner(banner1, banner2, display_banner)
291
291
292 # Create namespaces (user_ns, user_global_ns, etc.)
292 # Create namespaces (user_ns, user_global_ns, etc.)
293 self.init_create_namespaces(user_ns, user_global_ns)
293 self.init_create_namespaces(user_ns, user_global_ns)
294 # This has to be done after init_create_namespaces because it uses
294 # This has to be done after init_create_namespaces because it uses
295 # something in self.user_ns, but before init_sys_modules, which
295 # something in self.user_ns, but before init_sys_modules, which
296 # is the first thing to modify sys.
296 # is the first thing to modify sys.
297 self.save_sys_module_state()
297 self.save_sys_module_state()
298 self.init_sys_modules()
298 self.init_sys_modules()
299
299
300 self.init_history()
300 self.init_history()
301 self.init_encoding()
301 self.init_encoding()
302 self.init_prefilter()
302 self.init_prefilter()
303
303
304 Magic.__init__(self, self)
304 Magic.__init__(self, self)
305
305
306 self.init_syntax_highlighting()
306 self.init_syntax_highlighting()
307 self.init_hooks()
307 self.init_hooks()
308 self.init_pushd_popd_magic()
308 self.init_pushd_popd_magic()
309 self.init_traceback_handlers(custom_exceptions)
309 self.init_traceback_handlers(custom_exceptions)
310 self.init_user_ns()
310 self.init_user_ns()
311 self.init_logger()
311 self.init_logger()
312 self.init_alias()
312 self.init_alias()
313 self.init_builtins()
313 self.init_builtins()
314
314
315 # pre_config_initialization
315 # pre_config_initialization
316 self.init_shadow_hist()
316 self.init_shadow_hist()
317
317
318 # The next section should contain averything that was in ipmaker.
318 # The next section should contain averything that was in ipmaker.
319 self.init_logstart()
319 self.init_logstart()
320
320
321 # The following was in post_config_initialization
321 # The following was in post_config_initialization
322 self.init_inspector()
322 self.init_inspector()
323 self.init_readline()
323 self.init_readline()
324 self.init_prompts()
324 self.init_prompts()
325 self.init_displayhook()
325 self.init_displayhook()
326 self.init_reload_doctest()
326 self.init_reload_doctest()
327 self.init_magics()
327 self.init_magics()
328 self.init_pdb()
328 self.init_pdb()
329 self.hooks.late_startup_hook()
329 self.hooks.late_startup_hook()
330
330
331 def get_ipython(self):
331 def get_ipython(self):
332 return self
332 return self
333
333
334 #-------------------------------------------------------------------------
334 #-------------------------------------------------------------------------
335 # Traitlet changed handlers
335 # Traitlet changed handlers
336 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
337
337
338 def _banner1_changed(self):
338 def _banner1_changed(self):
339 self.compute_banner()
339 self.compute_banner()
340
340
341 def _banner2_changed(self):
341 def _banner2_changed(self):
342 self.compute_banner()
342 self.compute_banner()
343
343
344 def _ipythondir_changed(self, name, new):
344 def _ipython_dir_changed(self, name, new):
345 if not os.path.isdir(new):
345 if not os.path.isdir(new):
346 os.makedirs(new, mode = 0777)
346 os.makedirs(new, mode = 0777)
347 if not os.path.isdir(self.ipython_extension_dir):
347 if not os.path.isdir(self.ipython_extension_dir):
348 os.makedirs(self.ipython_extension_dir, mode = 0777)
348 os.makedirs(self.ipython_extension_dir, mode = 0777)
349
349
350 @property
350 @property
351 def ipython_extension_dir(self):
351 def ipython_extension_dir(self):
352 return os.path.join(self.ipythondir, 'extensions')
352 return os.path.join(self.ipython_dir, 'extensions')
353
353
354 @property
354 @property
355 def usable_screen_length(self):
355 def usable_screen_length(self):
356 if self.screen_length == 0:
356 if self.screen_length == 0:
357 return 0
357 return 0
358 else:
358 else:
359 num_lines_bot = self.separate_in.count('\n')+1
359 num_lines_bot = self.separate_in.count('\n')+1
360 return self.screen_length - num_lines_bot
360 return self.screen_length - num_lines_bot
361
361
362 def _term_title_changed(self, name, new_value):
362 def _term_title_changed(self, name, new_value):
363 self.init_term_title()
363 self.init_term_title()
364
364
365 def set_autoindent(self,value=None):
365 def set_autoindent(self,value=None):
366 """Set the autoindent flag, checking for readline support.
366 """Set the autoindent flag, checking for readline support.
367
367
368 If called with no arguments, it acts as a toggle."""
368 If called with no arguments, it acts as a toggle."""
369
369
370 if not self.has_readline:
370 if not self.has_readline:
371 if os.name == 'posix':
371 if os.name == 'posix':
372 warn("The auto-indent feature requires the readline library")
372 warn("The auto-indent feature requires the readline library")
373 self.autoindent = 0
373 self.autoindent = 0
374 return
374 return
375 if value is None:
375 if value is None:
376 self.autoindent = not self.autoindent
376 self.autoindent = not self.autoindent
377 else:
377 else:
378 self.autoindent = value
378 self.autoindent = value
379
379
380 #-------------------------------------------------------------------------
380 #-------------------------------------------------------------------------
381 # init_* methods called by __init__
381 # init_* methods called by __init__
382 #-------------------------------------------------------------------------
382 #-------------------------------------------------------------------------
383
383
384 def init_ipythondir(self, ipythondir):
384 def init_ipython_dir(self, ipython_dir):
385 if ipythondir is not None:
385 if ipython_dir is not None:
386 self.ipythondir = ipythondir
386 self.ipython_dir = ipython_dir
387 self.config.Global.ipythondir = self.ipythondir
387 self.config.Global.ipython_dir = self.ipython_dir
388 return
388 return
389
389
390 if hasattr(self.config.Global, 'ipythondir'):
390 if hasattr(self.config.Global, 'ipython_dir'):
391 self.ipythondir = self.config.Global.ipythondir
391 self.ipython_dir = self.config.Global.ipython_dir
392 else:
392 else:
393 self.ipythondir = get_ipython_dir()
393 self.ipython_dir = get_ipython_dir()
394
394
395 # All children can just read this
395 # All children can just read this
396 self.config.Global.ipythondir = self.ipythondir
396 self.config.Global.ipython_dir = self.ipython_dir
397
397
398 def init_instance_attrs(self):
398 def init_instance_attrs(self):
399 self.jobs = BackgroundJobManager()
399 self.jobs = BackgroundJobManager()
400 self.more = False
400 self.more = False
401
401
402 # command compiler
402 # command compiler
403 self.compile = codeop.CommandCompiler()
403 self.compile = codeop.CommandCompiler()
404
404
405 # User input buffer
405 # User input buffer
406 self.buffer = []
406 self.buffer = []
407
407
408 # Make an empty namespace, which extension writers can rely on both
408 # Make an empty namespace, which extension writers can rely on both
409 # existing and NEVER being used by ipython itself. This gives them a
409 # existing and NEVER being used by ipython itself. This gives them a
410 # convenient location for storing additional information and state
410 # convenient location for storing additional information and state
411 # their extensions may require, without fear of collisions with other
411 # their extensions may require, without fear of collisions with other
412 # ipython names that may develop later.
412 # ipython names that may develop later.
413 self.meta = Struct()
413 self.meta = Struct()
414
414
415 # Object variable to store code object waiting execution. This is
415 # Object variable to store code object waiting execution. This is
416 # used mainly by the multithreaded shells, but it can come in handy in
416 # used mainly by the multithreaded shells, but it can come in handy in
417 # other situations. No need to use a Queue here, since it's a single
417 # other situations. No need to use a Queue here, since it's a single
418 # item which gets cleared once run.
418 # item which gets cleared once run.
419 self.code_to_run = None
419 self.code_to_run = None
420
420
421 # Flag to mark unconditional exit
421 # Flag to mark unconditional exit
422 self.exit_now = False
422 self.exit_now = False
423
423
424 # Temporary files used for various purposes. Deleted at exit.
424 # Temporary files used for various purposes. Deleted at exit.
425 self.tempfiles = []
425 self.tempfiles = []
426
426
427 # Keep track of readline usage (later set by init_readline)
427 # Keep track of readline usage (later set by init_readline)
428 self.has_readline = False
428 self.has_readline = False
429
429
430 # keep track of where we started running (mainly for crash post-mortem)
430 # keep track of where we started running (mainly for crash post-mortem)
431 # This is not being used anywhere currently.
431 # This is not being used anywhere currently.
432 self.starting_dir = os.getcwd()
432 self.starting_dir = os.getcwd()
433
433
434 # Indentation management
434 # Indentation management
435 self.indent_current_nsp = 0
435 self.indent_current_nsp = 0
436
436
437 def init_term_title(self):
437 def init_term_title(self):
438 # Enable or disable the terminal title.
438 # Enable or disable the terminal title.
439 if self.term_title:
439 if self.term_title:
440 toggle_set_term_title(True)
440 toggle_set_term_title(True)
441 set_term_title('IPython: ' + abbrev_cwd())
441 set_term_title('IPython: ' + abbrev_cwd())
442 else:
442 else:
443 toggle_set_term_title(False)
443 toggle_set_term_title(False)
444
444
445 def init_usage(self, usage=None):
445 def init_usage(self, usage=None):
446 if usage is None:
446 if usage is None:
447 self.usage = interactive_usage
447 self.usage = interactive_usage
448 else:
448 else:
449 self.usage = usage
449 self.usage = usage
450
450
451 def init_encoding(self):
451 def init_encoding(self):
452 # Get system encoding at startup time. Certain terminals (like Emacs
452 # Get system encoding at startup time. Certain terminals (like Emacs
453 # under Win32 have it set to None, and we need to have a known valid
453 # under Win32 have it set to None, and we need to have a known valid
454 # encoding to use in the raw_input() method
454 # encoding to use in the raw_input() method
455 try:
455 try:
456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
457 except AttributeError:
457 except AttributeError:
458 self.stdin_encoding = 'ascii'
458 self.stdin_encoding = 'ascii'
459
459
460 def init_syntax_highlighting(self):
460 def init_syntax_highlighting(self):
461 # Python source parser/formatter for syntax highlighting
461 # Python source parser/formatter for syntax highlighting
462 pyformat = PyColorize.Parser().format
462 pyformat = PyColorize.Parser().format
463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
464
464
465 def init_pushd_popd_magic(self):
465 def init_pushd_popd_magic(self):
466 # for pushd/popd management
466 # for pushd/popd management
467 try:
467 try:
468 self.home_dir = get_home_dir()
468 self.home_dir = get_home_dir()
469 except HomeDirError, msg:
469 except HomeDirError, msg:
470 fatal(msg)
470 fatal(msg)
471
471
472 self.dir_stack = []
472 self.dir_stack = []
473
473
474 def init_logger(self):
474 def init_logger(self):
475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
476 # local shortcut, this is used a LOT
476 # local shortcut, this is used a LOT
477 self.log = self.logger.log
477 self.log = self.logger.log
478
478
479 def init_logstart(self):
479 def init_logstart(self):
480 if self.logappend:
480 if self.logappend:
481 self.magic_logstart(self.logappend + ' append')
481 self.magic_logstart(self.logappend + ' append')
482 elif self.logfile:
482 elif self.logfile:
483 self.magic_logstart(self.logfile)
483 self.magic_logstart(self.logfile)
484 elif self.logstart:
484 elif self.logstart:
485 self.magic_logstart()
485 self.magic_logstart()
486
486
487 def init_builtins(self):
487 def init_builtins(self):
488 self.builtin_trap = BuiltinTrap(self)
488 self.builtin_trap = BuiltinTrap(self)
489
489
490 def init_inspector(self):
490 def init_inspector(self):
491 # Object inspector
491 # Object inspector
492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
493 PyColorize.ANSICodeColors,
493 PyColorize.ANSICodeColors,
494 'NoColor',
494 'NoColor',
495 self.object_info_string_level)
495 self.object_info_string_level)
496
496
497 def init_prompts(self):
497 def init_prompts(self):
498 # Initialize cache, set in/out prompts and printing system
498 # Initialize cache, set in/out prompts and printing system
499 self.outputcache = CachedOutput(self,
499 self.outputcache = CachedOutput(self,
500 self.cache_size,
500 self.cache_size,
501 self.pprint,
501 self.pprint,
502 input_sep = self.separate_in,
502 input_sep = self.separate_in,
503 output_sep = self.separate_out,
503 output_sep = self.separate_out,
504 output_sep2 = self.separate_out2,
504 output_sep2 = self.separate_out2,
505 ps1 = self.prompt_in1,
505 ps1 = self.prompt_in1,
506 ps2 = self.prompt_in2,
506 ps2 = self.prompt_in2,
507 ps_out = self.prompt_out,
507 ps_out = self.prompt_out,
508 pad_left = self.prompts_pad_left)
508 pad_left = self.prompts_pad_left)
509
509
510 # user may have over-ridden the default print hook:
510 # user may have over-ridden the default print hook:
511 try:
511 try:
512 self.outputcache.__class__.display = self.hooks.display
512 self.outputcache.__class__.display = self.hooks.display
513 except AttributeError:
513 except AttributeError:
514 pass
514 pass
515
515
516 def init_displayhook(self):
516 def init_displayhook(self):
517 self.display_trap = DisplayTrap(self, self.outputcache)
517 self.display_trap = DisplayTrap(self, self.outputcache)
518
518
519 def init_reload_doctest(self):
519 def init_reload_doctest(self):
520 # Do a proper resetting of doctest, including the necessary displayhook
520 # Do a proper resetting of doctest, including the necessary displayhook
521 # monkeypatching
521 # monkeypatching
522 try:
522 try:
523 doctest_reload()
523 doctest_reload()
524 except ImportError:
524 except ImportError:
525 warn("doctest module does not exist.")
525 warn("doctest module does not exist.")
526
526
527 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
528 # Things related to the banner
528 # Things related to the banner
529 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
530
530
531 def init_banner(self, banner1, banner2, display_banner):
531 def init_banner(self, banner1, banner2, display_banner):
532 if banner1 is not None:
532 if banner1 is not None:
533 self.banner1 = banner1
533 self.banner1 = banner1
534 if banner2 is not None:
534 if banner2 is not None:
535 self.banner2 = banner2
535 self.banner2 = banner2
536 if display_banner is not None:
536 if display_banner is not None:
537 self.display_banner = display_banner
537 self.display_banner = display_banner
538 self.compute_banner()
538 self.compute_banner()
539
539
540 def show_banner(self, banner=None):
540 def show_banner(self, banner=None):
541 if banner is None:
541 if banner is None:
542 banner = self.banner
542 banner = self.banner
543 self.write(banner)
543 self.write(banner)
544
544
545 def compute_banner(self):
545 def compute_banner(self):
546 self.banner = self.banner1 + '\n'
546 self.banner = self.banner1 + '\n'
547 if self.profile:
547 if self.profile:
548 self.banner += '\nIPython profile: %s\n' % self.profile
548 self.banner += '\nIPython profile: %s\n' % self.profile
549 if self.banner2:
549 if self.banner2:
550 self.banner += '\n' + self.banner2 + '\n'
550 self.banner += '\n' + self.banner2 + '\n'
551
551
552 #-------------------------------------------------------------------------
552 #-------------------------------------------------------------------------
553 # Things related to injections into the sys module
553 # Things related to injections into the sys module
554 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
555
555
556 def save_sys_module_state(self):
556 def save_sys_module_state(self):
557 """Save the state of hooks in the sys module.
557 """Save the state of hooks in the sys module.
558
558
559 This has to be called after self.user_ns is created.
559 This has to be called after self.user_ns is created.
560 """
560 """
561 self._orig_sys_module_state = {}
561 self._orig_sys_module_state = {}
562 self._orig_sys_module_state['stdin'] = sys.stdin
562 self._orig_sys_module_state['stdin'] = sys.stdin
563 self._orig_sys_module_state['stdout'] = sys.stdout
563 self._orig_sys_module_state['stdout'] = sys.stdout
564 self._orig_sys_module_state['stderr'] = sys.stderr
564 self._orig_sys_module_state['stderr'] = sys.stderr
565 self._orig_sys_module_state['excepthook'] = sys.excepthook
565 self._orig_sys_module_state['excepthook'] = sys.excepthook
566 try:
566 try:
567 self._orig_sys_modules_main_name = self.user_ns['__name__']
567 self._orig_sys_modules_main_name = self.user_ns['__name__']
568 except KeyError:
568 except KeyError:
569 pass
569 pass
570
570
571 def restore_sys_module_state(self):
571 def restore_sys_module_state(self):
572 """Restore the state of the sys module."""
572 """Restore the state of the sys module."""
573 try:
573 try:
574 for k, v in self._orig_sys_module_state.items():
574 for k, v in self._orig_sys_module_state.items():
575 setattr(sys, k, v)
575 setattr(sys, k, v)
576 except AttributeError:
576 except AttributeError:
577 pass
577 pass
578 try:
578 try:
579 delattr(sys, 'ipcompleter')
579 delattr(sys, 'ipcompleter')
580 except AttributeError:
580 except AttributeError:
581 pass
581 pass
582 # Reset what what done in self.init_sys_modules
582 # Reset what what done in self.init_sys_modules
583 try:
583 try:
584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
585 except (AttributeError, KeyError):
585 except (AttributeError, KeyError):
586 pass
586 pass
587
587
588 #-------------------------------------------------------------------------
588 #-------------------------------------------------------------------------
589 # Things related to hooks
589 # Things related to hooks
590 #-------------------------------------------------------------------------
590 #-------------------------------------------------------------------------
591
591
592 def init_hooks(self):
592 def init_hooks(self):
593 # hooks holds pointers used for user-side customizations
593 # hooks holds pointers used for user-side customizations
594 self.hooks = Struct()
594 self.hooks = Struct()
595
595
596 self.strdispatchers = {}
596 self.strdispatchers = {}
597
597
598 # Set all default hooks, defined in the IPython.hooks module.
598 # Set all default hooks, defined in the IPython.hooks module.
599 import IPython.core.hooks
599 import IPython.core.hooks
600 hooks = IPython.core.hooks
600 hooks = IPython.core.hooks
601 for hook_name in hooks.__all__:
601 for hook_name in hooks.__all__:
602 # default hooks have priority 100, i.e. low; user hooks should have
602 # default hooks have priority 100, i.e. low; user hooks should have
603 # 0-100 priority
603 # 0-100 priority
604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
605
605
606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
607 """set_hook(name,hook) -> sets an internal IPython hook.
607 """set_hook(name,hook) -> sets an internal IPython hook.
608
608
609 IPython exposes some of its internal API as user-modifiable hooks. By
609 IPython exposes some of its internal API as user-modifiable hooks. By
610 adding your function to one of these hooks, you can modify IPython's
610 adding your function to one of these hooks, you can modify IPython's
611 behavior to call at runtime your own routines."""
611 behavior to call at runtime your own routines."""
612
612
613 # At some point in the future, this should validate the hook before it
613 # At some point in the future, this should validate the hook before it
614 # accepts it. Probably at least check that the hook takes the number
614 # accepts it. Probably at least check that the hook takes the number
615 # of args it's supposed to.
615 # of args it's supposed to.
616
616
617 f = new.instancemethod(hook,self,self.__class__)
617 f = new.instancemethod(hook,self,self.__class__)
618
618
619 # check if the hook is for strdispatcher first
619 # check if the hook is for strdispatcher first
620 if str_key is not None:
620 if str_key is not None:
621 sdp = self.strdispatchers.get(name, StrDispatch())
621 sdp = self.strdispatchers.get(name, StrDispatch())
622 sdp.add_s(str_key, f, priority )
622 sdp.add_s(str_key, f, priority )
623 self.strdispatchers[name] = sdp
623 self.strdispatchers[name] = sdp
624 return
624 return
625 if re_key is not None:
625 if re_key is not None:
626 sdp = self.strdispatchers.get(name, StrDispatch())
626 sdp = self.strdispatchers.get(name, StrDispatch())
627 sdp.add_re(re.compile(re_key), f, priority )
627 sdp.add_re(re.compile(re_key), f, priority )
628 self.strdispatchers[name] = sdp
628 self.strdispatchers[name] = sdp
629 return
629 return
630
630
631 dp = getattr(self.hooks, name, None)
631 dp = getattr(self.hooks, name, None)
632 if name not in IPython.core.hooks.__all__:
632 if name not in IPython.core.hooks.__all__:
633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
634 if not dp:
634 if not dp:
635 dp = IPython.core.hooks.CommandChainDispatcher()
635 dp = IPython.core.hooks.CommandChainDispatcher()
636
636
637 try:
637 try:
638 dp.add(f,priority)
638 dp.add(f,priority)
639 except AttributeError:
639 except AttributeError:
640 # it was not commandchain, plain old func - replace
640 # it was not commandchain, plain old func - replace
641 dp = f
641 dp = f
642
642
643 setattr(self.hooks,name, dp)
643 setattr(self.hooks,name, dp)
644
644
645 #-------------------------------------------------------------------------
645 #-------------------------------------------------------------------------
646 # Things related to the "main" module
646 # Things related to the "main" module
647 #-------------------------------------------------------------------------
647 #-------------------------------------------------------------------------
648
648
649 def new_main_mod(self,ns=None):
649 def new_main_mod(self,ns=None):
650 """Return a new 'main' module object for user code execution.
650 """Return a new 'main' module object for user code execution.
651 """
651 """
652 main_mod = self._user_main_module
652 main_mod = self._user_main_module
653 init_fakemod_dict(main_mod,ns)
653 init_fakemod_dict(main_mod,ns)
654 return main_mod
654 return main_mod
655
655
656 def cache_main_mod(self,ns,fname):
656 def cache_main_mod(self,ns,fname):
657 """Cache a main module's namespace.
657 """Cache a main module's namespace.
658
658
659 When scripts are executed via %run, we must keep a reference to the
659 When scripts are executed via %run, we must keep a reference to the
660 namespace of their __main__ module (a FakeModule instance) around so
660 namespace of their __main__ module (a FakeModule instance) around so
661 that Python doesn't clear it, rendering objects defined therein
661 that Python doesn't clear it, rendering objects defined therein
662 useless.
662 useless.
663
663
664 This method keeps said reference in a private dict, keyed by the
664 This method keeps said reference in a private dict, keyed by the
665 absolute path of the module object (which corresponds to the script
665 absolute path of the module object (which corresponds to the script
666 path). This way, for multiple executions of the same script we only
666 path). This way, for multiple executions of the same script we only
667 keep one copy of the namespace (the last one), thus preventing memory
667 keep one copy of the namespace (the last one), thus preventing memory
668 leaks from old references while allowing the objects from the last
668 leaks from old references while allowing the objects from the last
669 execution to be accessible.
669 execution to be accessible.
670
670
671 Note: we can not allow the actual FakeModule instances to be deleted,
671 Note: we can not allow the actual FakeModule instances to be deleted,
672 because of how Python tears down modules (it hard-sets all their
672 because of how Python tears down modules (it hard-sets all their
673 references to None without regard for reference counts). This method
673 references to None without regard for reference counts). This method
674 must therefore make a *copy* of the given namespace, to allow the
674 must therefore make a *copy* of the given namespace, to allow the
675 original module's __dict__ to be cleared and reused.
675 original module's __dict__ to be cleared and reused.
676
676
677
677
678 Parameters
678 Parameters
679 ----------
679 ----------
680 ns : a namespace (a dict, typically)
680 ns : a namespace (a dict, typically)
681
681
682 fname : str
682 fname : str
683 Filename associated with the namespace.
683 Filename associated with the namespace.
684
684
685 Examples
685 Examples
686 --------
686 --------
687
687
688 In [10]: import IPython
688 In [10]: import IPython
689
689
690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
691
691
692 In [12]: IPython.__file__ in _ip._main_ns_cache
692 In [12]: IPython.__file__ in _ip._main_ns_cache
693 Out[12]: True
693 Out[12]: True
694 """
694 """
695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
696
696
697 def clear_main_mod_cache(self):
697 def clear_main_mod_cache(self):
698 """Clear the cache of main modules.
698 """Clear the cache of main modules.
699
699
700 Mainly for use by utilities like %reset.
700 Mainly for use by utilities like %reset.
701
701
702 Examples
702 Examples
703 --------
703 --------
704
704
705 In [15]: import IPython
705 In [15]: import IPython
706
706
707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
708
708
709 In [17]: len(_ip._main_ns_cache) > 0
709 In [17]: len(_ip._main_ns_cache) > 0
710 Out[17]: True
710 Out[17]: True
711
711
712 In [18]: _ip.clear_main_mod_cache()
712 In [18]: _ip.clear_main_mod_cache()
713
713
714 In [19]: len(_ip._main_ns_cache) == 0
714 In [19]: len(_ip._main_ns_cache) == 0
715 Out[19]: True
715 Out[19]: True
716 """
716 """
717 self._main_ns_cache.clear()
717 self._main_ns_cache.clear()
718
718
719 #-------------------------------------------------------------------------
719 #-------------------------------------------------------------------------
720 # Things related to debugging
720 # Things related to debugging
721 #-------------------------------------------------------------------------
721 #-------------------------------------------------------------------------
722
722
723 def init_pdb(self):
723 def init_pdb(self):
724 # Set calling of pdb on exceptions
724 # Set calling of pdb on exceptions
725 # self.call_pdb is a property
725 # self.call_pdb is a property
726 self.call_pdb = self.pdb
726 self.call_pdb = self.pdb
727
727
728 def _get_call_pdb(self):
728 def _get_call_pdb(self):
729 return self._call_pdb
729 return self._call_pdb
730
730
731 def _set_call_pdb(self,val):
731 def _set_call_pdb(self,val):
732
732
733 if val not in (0,1,False,True):
733 if val not in (0,1,False,True):
734 raise ValueError,'new call_pdb value must be boolean'
734 raise ValueError,'new call_pdb value must be boolean'
735
735
736 # store value in instance
736 # store value in instance
737 self._call_pdb = val
737 self._call_pdb = val
738
738
739 # notify the actual exception handlers
739 # notify the actual exception handlers
740 self.InteractiveTB.call_pdb = val
740 self.InteractiveTB.call_pdb = val
741 if self.isthreaded:
741 if self.isthreaded:
742 try:
742 try:
743 self.sys_excepthook.call_pdb = val
743 self.sys_excepthook.call_pdb = val
744 except:
744 except:
745 warn('Failed to activate pdb for threaded exception handler')
745 warn('Failed to activate pdb for threaded exception handler')
746
746
747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
748 'Control auto-activation of pdb at exceptions')
748 'Control auto-activation of pdb at exceptions')
749
749
750 def debugger(self,force=False):
750 def debugger(self,force=False):
751 """Call the pydb/pdb debugger.
751 """Call the pydb/pdb debugger.
752
752
753 Keywords:
753 Keywords:
754
754
755 - force(False): by default, this routine checks the instance call_pdb
755 - force(False): by default, this routine checks the instance call_pdb
756 flag and does not actually invoke the debugger if the flag is false.
756 flag and does not actually invoke the debugger if the flag is false.
757 The 'force' option forces the debugger to activate even if the flag
757 The 'force' option forces the debugger to activate even if the flag
758 is false.
758 is false.
759 """
759 """
760
760
761 if not (force or self.call_pdb):
761 if not (force or self.call_pdb):
762 return
762 return
763
763
764 if not hasattr(sys,'last_traceback'):
764 if not hasattr(sys,'last_traceback'):
765 error('No traceback has been produced, nothing to debug.')
765 error('No traceback has been produced, nothing to debug.')
766 return
766 return
767
767
768 # use pydb if available
768 # use pydb if available
769 if debugger.has_pydb:
769 if debugger.has_pydb:
770 from pydb import pm
770 from pydb import pm
771 else:
771 else:
772 # fallback to our internal debugger
772 # fallback to our internal debugger
773 pm = lambda : self.InteractiveTB.debugger(force=True)
773 pm = lambda : self.InteractiveTB.debugger(force=True)
774 self.history_saving_wrapper(pm)()
774 self.history_saving_wrapper(pm)()
775
775
776 #-------------------------------------------------------------------------
776 #-------------------------------------------------------------------------
777 # Things related to IPython's various namespaces
777 # Things related to IPython's various namespaces
778 #-------------------------------------------------------------------------
778 #-------------------------------------------------------------------------
779
779
780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
781 # Create the namespace where the user will operate. user_ns is
781 # Create the namespace where the user will operate. user_ns is
782 # normally the only one used, and it is passed to the exec calls as
782 # normally the only one used, and it is passed to the exec calls as
783 # the locals argument. But we do carry a user_global_ns namespace
783 # the locals argument. But we do carry a user_global_ns namespace
784 # given as the exec 'globals' argument, This is useful in embedding
784 # given as the exec 'globals' argument, This is useful in embedding
785 # situations where the ipython shell opens in a context where the
785 # situations where the ipython shell opens in a context where the
786 # distinction between locals and globals is meaningful. For
786 # distinction between locals and globals is meaningful. For
787 # non-embedded contexts, it is just the same object as the user_ns dict.
787 # non-embedded contexts, it is just the same object as the user_ns dict.
788
788
789 # FIXME. For some strange reason, __builtins__ is showing up at user
789 # FIXME. For some strange reason, __builtins__ is showing up at user
790 # level as a dict instead of a module. This is a manual fix, but I
790 # level as a dict instead of a module. This is a manual fix, but I
791 # should really track down where the problem is coming from. Alex
791 # should really track down where the problem is coming from. Alex
792 # Schmolck reported this problem first.
792 # Schmolck reported this problem first.
793
793
794 # A useful post by Alex Martelli on this topic:
794 # A useful post by Alex Martelli on this topic:
795 # Re: inconsistent value from __builtins__
795 # Re: inconsistent value from __builtins__
796 # Von: Alex Martelli <aleaxit@yahoo.com>
796 # Von: Alex Martelli <aleaxit@yahoo.com>
797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
798 # Gruppen: comp.lang.python
798 # Gruppen: comp.lang.python
799
799
800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
802 # > <type 'dict'>
802 # > <type 'dict'>
803 # > >>> print type(__builtins__)
803 # > >>> print type(__builtins__)
804 # > <type 'module'>
804 # > <type 'module'>
805 # > Is this difference in return value intentional?
805 # > Is this difference in return value intentional?
806
806
807 # Well, it's documented that '__builtins__' can be either a dictionary
807 # Well, it's documented that '__builtins__' can be either a dictionary
808 # or a module, and it's been that way for a long time. Whether it's
808 # or a module, and it's been that way for a long time. Whether it's
809 # intentional (or sensible), I don't know. In any case, the idea is
809 # intentional (or sensible), I don't know. In any case, the idea is
810 # that if you need to access the built-in namespace directly, you
810 # that if you need to access the built-in namespace directly, you
811 # should start with "import __builtin__" (note, no 's') which will
811 # should start with "import __builtin__" (note, no 's') which will
812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
813
813
814 # These routines return properly built dicts as needed by the rest of
814 # These routines return properly built dicts as needed by the rest of
815 # the code, and can also be used by extension writers to generate
815 # the code, and can also be used by extension writers to generate
816 # properly initialized namespaces.
816 # properly initialized namespaces.
817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
818 user_global_ns)
818 user_global_ns)
819
819
820 # Assign namespaces
820 # Assign namespaces
821 # This is the namespace where all normal user variables live
821 # This is the namespace where all normal user variables live
822 self.user_ns = user_ns
822 self.user_ns = user_ns
823 self.user_global_ns = user_global_ns
823 self.user_global_ns = user_global_ns
824
824
825 # An auxiliary namespace that checks what parts of the user_ns were
825 # An auxiliary namespace that checks what parts of the user_ns were
826 # loaded at startup, so we can list later only variables defined in
826 # loaded at startup, so we can list later only variables defined in
827 # actual interactive use. Since it is always a subset of user_ns, it
827 # actual interactive use. Since it is always a subset of user_ns, it
828 # doesn't need to be seaparately tracked in the ns_table
828 # doesn't need to be seaparately tracked in the ns_table
829 self.user_config_ns = {}
829 self.user_config_ns = {}
830
830
831 # A namespace to keep track of internal data structures to prevent
831 # A namespace to keep track of internal data structures to prevent
832 # them from cluttering user-visible stuff. Will be updated later
832 # them from cluttering user-visible stuff. Will be updated later
833 self.internal_ns = {}
833 self.internal_ns = {}
834
834
835 # Now that FakeModule produces a real module, we've run into a nasty
835 # Now that FakeModule produces a real module, we've run into a nasty
836 # problem: after script execution (via %run), the module where the user
836 # problem: after script execution (via %run), the module where the user
837 # code ran is deleted. Now that this object is a true module (needed
837 # code ran is deleted. Now that this object is a true module (needed
838 # so docetst and other tools work correctly), the Python module
838 # so docetst and other tools work correctly), the Python module
839 # teardown mechanism runs over it, and sets to None every variable
839 # teardown mechanism runs over it, and sets to None every variable
840 # present in that module. Top-level references to objects from the
840 # present in that module. Top-level references to objects from the
841 # script survive, because the user_ns is updated with them. However,
841 # script survive, because the user_ns is updated with them. However,
842 # calling functions defined in the script that use other things from
842 # calling functions defined in the script that use other things from
843 # the script will fail, because the function's closure had references
843 # the script will fail, because the function's closure had references
844 # to the original objects, which are now all None. So we must protect
844 # to the original objects, which are now all None. So we must protect
845 # these modules from deletion by keeping a cache.
845 # these modules from deletion by keeping a cache.
846 #
846 #
847 # To avoid keeping stale modules around (we only need the one from the
847 # To avoid keeping stale modules around (we only need the one from the
848 # last run), we use a dict keyed with the full path to the script, so
848 # last run), we use a dict keyed with the full path to the script, so
849 # only the last version of the module is held in the cache. Note,
849 # only the last version of the module is held in the cache. Note,
850 # however, that we must cache the module *namespace contents* (their
850 # however, that we must cache the module *namespace contents* (their
851 # __dict__). Because if we try to cache the actual modules, old ones
851 # __dict__). Because if we try to cache the actual modules, old ones
852 # (uncached) could be destroyed while still holding references (such as
852 # (uncached) could be destroyed while still holding references (such as
853 # those held by GUI objects that tend to be long-lived)>
853 # those held by GUI objects that tend to be long-lived)>
854 #
854 #
855 # The %reset command will flush this cache. See the cache_main_mod()
855 # The %reset command will flush this cache. See the cache_main_mod()
856 # and clear_main_mod_cache() methods for details on use.
856 # and clear_main_mod_cache() methods for details on use.
857
857
858 # This is the cache used for 'main' namespaces
858 # This is the cache used for 'main' namespaces
859 self._main_ns_cache = {}
859 self._main_ns_cache = {}
860 # And this is the single instance of FakeModule whose __dict__ we keep
860 # And this is the single instance of FakeModule whose __dict__ we keep
861 # copying and clearing for reuse on each %run
861 # copying and clearing for reuse on each %run
862 self._user_main_module = FakeModule()
862 self._user_main_module = FakeModule()
863
863
864 # A table holding all the namespaces IPython deals with, so that
864 # A table holding all the namespaces IPython deals with, so that
865 # introspection facilities can search easily.
865 # introspection facilities can search easily.
866 self.ns_table = {'user':user_ns,
866 self.ns_table = {'user':user_ns,
867 'user_global':user_global_ns,
867 'user_global':user_global_ns,
868 'internal':self.internal_ns,
868 'internal':self.internal_ns,
869 'builtin':__builtin__.__dict__
869 'builtin':__builtin__.__dict__
870 }
870 }
871
871
872 # Similarly, track all namespaces where references can be held and that
872 # Similarly, track all namespaces where references can be held and that
873 # we can safely clear (so it can NOT include builtin). This one can be
873 # we can safely clear (so it can NOT include builtin). This one can be
874 # a simple list.
874 # a simple list.
875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
876 self.internal_ns, self._main_ns_cache ]
876 self.internal_ns, self._main_ns_cache ]
877
877
878 def init_sys_modules(self):
878 def init_sys_modules(self):
879 # We need to insert into sys.modules something that looks like a
879 # We need to insert into sys.modules something that looks like a
880 # module but which accesses the IPython namespace, for shelve and
880 # module but which accesses the IPython namespace, for shelve and
881 # pickle to work interactively. Normally they rely on getting
881 # pickle to work interactively. Normally they rely on getting
882 # everything out of __main__, but for embedding purposes each IPython
882 # everything out of __main__, but for embedding purposes each IPython
883 # instance has its own private namespace, so we can't go shoving
883 # instance has its own private namespace, so we can't go shoving
884 # everything into __main__.
884 # everything into __main__.
885
885
886 # note, however, that we should only do this for non-embedded
886 # note, however, that we should only do this for non-embedded
887 # ipythons, which really mimic the __main__.__dict__ with their own
887 # ipythons, which really mimic the __main__.__dict__ with their own
888 # namespace. Embedded instances, on the other hand, should not do
888 # namespace. Embedded instances, on the other hand, should not do
889 # this because they need to manage the user local/global namespaces
889 # this because they need to manage the user local/global namespaces
890 # only, but they live within a 'normal' __main__ (meaning, they
890 # only, but they live within a 'normal' __main__ (meaning, they
891 # shouldn't overtake the execution environment of the script they're
891 # shouldn't overtake the execution environment of the script they're
892 # embedded in).
892 # embedded in).
893
893
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895
895
896 try:
896 try:
897 main_name = self.user_ns['__name__']
897 main_name = self.user_ns['__name__']
898 except KeyError:
898 except KeyError:
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 else:
900 else:
901 sys.modules[main_name] = FakeModule(self.user_ns)
901 sys.modules[main_name] = FakeModule(self.user_ns)
902
902
903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
904 """Return a valid local and global user interactive namespaces.
904 """Return a valid local and global user interactive namespaces.
905
905
906 This builds a dict with the minimal information needed to operate as a
906 This builds a dict with the minimal information needed to operate as a
907 valid IPython user namespace, which you can pass to the various
907 valid IPython user namespace, which you can pass to the various
908 embedding classes in ipython. The default implementation returns the
908 embedding classes in ipython. The default implementation returns the
909 same dict for both the locals and the globals to allow functions to
909 same dict for both the locals and the globals to allow functions to
910 refer to variables in the namespace. Customized implementations can
910 refer to variables in the namespace. Customized implementations can
911 return different dicts. The locals dictionary can actually be anything
911 return different dicts. The locals dictionary can actually be anything
912 following the basic mapping protocol of a dict, but the globals dict
912 following the basic mapping protocol of a dict, but the globals dict
913 must be a true dict, not even a subclass. It is recommended that any
913 must be a true dict, not even a subclass. It is recommended that any
914 custom object for the locals namespace synchronize with the globals
914 custom object for the locals namespace synchronize with the globals
915 dict somehow.
915 dict somehow.
916
916
917 Raises TypeError if the provided globals namespace is not a true dict.
917 Raises TypeError if the provided globals namespace is not a true dict.
918
918
919 :Parameters:
919 :Parameters:
920 user_ns : dict-like, optional
920 user_ns : dict-like, optional
921 The current user namespace. The items in this namespace should
921 The current user namespace. The items in this namespace should
922 be included in the output. If None, an appropriate blank
922 be included in the output. If None, an appropriate blank
923 namespace should be created.
923 namespace should be created.
924 user_global_ns : dict, optional
924 user_global_ns : dict, optional
925 The current user global namespace. The items in this namespace
925 The current user global namespace. The items in this namespace
926 should be included in the output. If None, an appropriate
926 should be included in the output. If None, an appropriate
927 blank namespace should be created.
927 blank namespace should be created.
928
928
929 :Returns:
929 :Returns:
930 A tuple pair of dictionary-like object to be used as the local namespace
930 A tuple pair of dictionary-like object to be used as the local namespace
931 of the interpreter and a dict to be used as the global namespace.
931 of the interpreter and a dict to be used as the global namespace.
932 """
932 """
933
933
934 if user_ns is None:
934 if user_ns is None:
935 # Set __name__ to __main__ to better match the behavior of the
935 # Set __name__ to __main__ to better match the behavior of the
936 # normal interpreter.
936 # normal interpreter.
937 user_ns = {'__name__' :'__main__',
937 user_ns = {'__name__' :'__main__',
938 '__builtins__' : __builtin__,
938 '__builtins__' : __builtin__,
939 }
939 }
940 else:
940 else:
941 user_ns.setdefault('__name__','__main__')
941 user_ns.setdefault('__name__','__main__')
942 user_ns.setdefault('__builtins__',__builtin__)
942 user_ns.setdefault('__builtins__',__builtin__)
943
943
944 if user_global_ns is None:
944 if user_global_ns is None:
945 user_global_ns = user_ns
945 user_global_ns = user_ns
946 if type(user_global_ns) is not dict:
946 if type(user_global_ns) is not dict:
947 raise TypeError("user_global_ns must be a true dict; got %r"
947 raise TypeError("user_global_ns must be a true dict; got %r"
948 % type(user_global_ns))
948 % type(user_global_ns))
949
949
950 return user_ns, user_global_ns
950 return user_ns, user_global_ns
951
951
952 def init_user_ns(self):
952 def init_user_ns(self):
953 """Initialize all user-visible namespaces to their minimum defaults.
953 """Initialize all user-visible namespaces to their minimum defaults.
954
954
955 Certain history lists are also initialized here, as they effectively
955 Certain history lists are also initialized here, as they effectively
956 act as user namespaces.
956 act as user namespaces.
957
957
958 Notes
958 Notes
959 -----
959 -----
960 All data structures here are only filled in, they are NOT reset by this
960 All data structures here are only filled in, they are NOT reset by this
961 method. If they were not empty before, data will simply be added to
961 method. If they were not empty before, data will simply be added to
962 therm.
962 therm.
963 """
963 """
964 # Store myself as the public api!!!
964 # Store myself as the public api!!!
965 self.user_ns['get_ipython'] = self.get_ipython
965 self.user_ns['get_ipython'] = self.get_ipython
966
966
967 # make global variables for user access to the histories
967 # make global variables for user access to the histories
968 self.user_ns['_ih'] = self.input_hist
968 self.user_ns['_ih'] = self.input_hist
969 self.user_ns['_oh'] = self.output_hist
969 self.user_ns['_oh'] = self.output_hist
970 self.user_ns['_dh'] = self.dir_hist
970 self.user_ns['_dh'] = self.dir_hist
971
971
972 # user aliases to input and output histories
972 # user aliases to input and output histories
973 self.user_ns['In'] = self.input_hist
973 self.user_ns['In'] = self.input_hist
974 self.user_ns['Out'] = self.output_hist
974 self.user_ns['Out'] = self.output_hist
975
975
976 self.user_ns['_sh'] = shadowns
976 self.user_ns['_sh'] = shadowns
977
977
978 # Put 'help' in the user namespace
978 # Put 'help' in the user namespace
979 try:
979 try:
980 from site import _Helper
980 from site import _Helper
981 self.user_ns['help'] = _Helper()
981 self.user_ns['help'] = _Helper()
982 except ImportError:
982 except ImportError:
983 warn('help() not available - check site.py')
983 warn('help() not available - check site.py')
984
984
985 def reset(self):
985 def reset(self):
986 """Clear all internal namespaces.
986 """Clear all internal namespaces.
987
987
988 Note that this is much more aggressive than %reset, since it clears
988 Note that this is much more aggressive than %reset, since it clears
989 fully all namespaces, as well as all input/output lists.
989 fully all namespaces, as well as all input/output lists.
990 """
990 """
991 for ns in self.ns_refs_table:
991 for ns in self.ns_refs_table:
992 ns.clear()
992 ns.clear()
993
993
994 self.alias_manager.clear_aliases()
994 self.alias_manager.clear_aliases()
995
995
996 # Clear input and output histories
996 # Clear input and output histories
997 self.input_hist[:] = []
997 self.input_hist[:] = []
998 self.input_hist_raw[:] = []
998 self.input_hist_raw[:] = []
999 self.output_hist.clear()
999 self.output_hist.clear()
1000
1000
1001 # Restore the user namespaces to minimal usability
1001 # Restore the user namespaces to minimal usability
1002 self.init_user_ns()
1002 self.init_user_ns()
1003
1003
1004 # Restore the default and user aliases
1004 # Restore the default and user aliases
1005 self.alias_manager.init_aliases()
1005 self.alias_manager.init_aliases()
1006
1006
1007 def push(self, variables, interactive=True):
1007 def push(self, variables, interactive=True):
1008 """Inject a group of variables into the IPython user namespace.
1008 """Inject a group of variables into the IPython user namespace.
1009
1009
1010 Parameters
1010 Parameters
1011 ----------
1011 ----------
1012 variables : dict, str or list/tuple of str
1012 variables : dict, str or list/tuple of str
1013 The variables to inject into the user's namespace. If a dict,
1013 The variables to inject into the user's namespace. If a dict,
1014 a simple update is done. If a str, the string is assumed to
1014 a simple update is done. If a str, the string is assumed to
1015 have variable names separated by spaces. A list/tuple of str
1015 have variable names separated by spaces. A list/tuple of str
1016 can also be used to give the variable names. If just the variable
1016 can also be used to give the variable names. If just the variable
1017 names are give (list/tuple/str) then the variable values looked
1017 names are give (list/tuple/str) then the variable values looked
1018 up in the callers frame.
1018 up in the callers frame.
1019 interactive : bool
1019 interactive : bool
1020 If True (default), the variables will be listed with the ``who``
1020 If True (default), the variables will be listed with the ``who``
1021 magic.
1021 magic.
1022 """
1022 """
1023 vdict = None
1023 vdict = None
1024
1024
1025 # We need a dict of name/value pairs to do namespace updates.
1025 # We need a dict of name/value pairs to do namespace updates.
1026 if isinstance(variables, dict):
1026 if isinstance(variables, dict):
1027 vdict = variables
1027 vdict = variables
1028 elif isinstance(variables, (basestring, list, tuple)):
1028 elif isinstance(variables, (basestring, list, tuple)):
1029 if isinstance(variables, basestring):
1029 if isinstance(variables, basestring):
1030 vlist = variables.split()
1030 vlist = variables.split()
1031 else:
1031 else:
1032 vlist = variables
1032 vlist = variables
1033 vdict = {}
1033 vdict = {}
1034 cf = sys._getframe(1)
1034 cf = sys._getframe(1)
1035 for name in vlist:
1035 for name in vlist:
1036 try:
1036 try:
1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1038 except:
1038 except:
1039 print ('Could not get variable %s from %s' %
1039 print ('Could not get variable %s from %s' %
1040 (name,cf.f_code.co_name))
1040 (name,cf.f_code.co_name))
1041 else:
1041 else:
1042 raise ValueError('variables must be a dict/str/list/tuple')
1042 raise ValueError('variables must be a dict/str/list/tuple')
1043
1043
1044 # Propagate variables to user namespace
1044 # Propagate variables to user namespace
1045 self.user_ns.update(vdict)
1045 self.user_ns.update(vdict)
1046
1046
1047 # And configure interactive visibility
1047 # And configure interactive visibility
1048 config_ns = self.user_config_ns
1048 config_ns = self.user_config_ns
1049 if interactive:
1049 if interactive:
1050 for name, val in vdict.iteritems():
1050 for name, val in vdict.iteritems():
1051 config_ns.pop(name, None)
1051 config_ns.pop(name, None)
1052 else:
1052 else:
1053 for name,val in vdict.iteritems():
1053 for name,val in vdict.iteritems():
1054 config_ns[name] = val
1054 config_ns[name] = val
1055
1055
1056 #-------------------------------------------------------------------------
1056 #-------------------------------------------------------------------------
1057 # Things related to history management
1057 # Things related to history management
1058 #-------------------------------------------------------------------------
1058 #-------------------------------------------------------------------------
1059
1059
1060 def init_history(self):
1060 def init_history(self):
1061 # List of input with multi-line handling.
1061 # List of input with multi-line handling.
1062 self.input_hist = InputList()
1062 self.input_hist = InputList()
1063 # This one will hold the 'raw' input history, without any
1063 # This one will hold the 'raw' input history, without any
1064 # pre-processing. This will allow users to retrieve the input just as
1064 # pre-processing. This will allow users to retrieve the input just as
1065 # it was exactly typed in by the user, with %hist -r.
1065 # it was exactly typed in by the user, with %hist -r.
1066 self.input_hist_raw = InputList()
1066 self.input_hist_raw = InputList()
1067
1067
1068 # list of visited directories
1068 # list of visited directories
1069 try:
1069 try:
1070 self.dir_hist = [os.getcwd()]
1070 self.dir_hist = [os.getcwd()]
1071 except OSError:
1071 except OSError:
1072 self.dir_hist = []
1072 self.dir_hist = []
1073
1073
1074 # dict of output history
1074 # dict of output history
1075 self.output_hist = {}
1075 self.output_hist = {}
1076
1076
1077 # Now the history file
1077 # Now the history file
1078 if self.profile:
1078 if self.profile:
1079 histfname = 'history-%s' % self.profile
1079 histfname = 'history-%s' % self.profile
1080 else:
1080 else:
1081 histfname = 'history'
1081 histfname = 'history'
1082 self.histfile = os.path.join(self.ipythondir, histfname)
1082 self.histfile = os.path.join(self.ipython_dir, histfname)
1083
1083
1084 # Fill the history zero entry, user counter starts at 1
1084 # Fill the history zero entry, user counter starts at 1
1085 self.input_hist.append('\n')
1085 self.input_hist.append('\n')
1086 self.input_hist_raw.append('\n')
1086 self.input_hist_raw.append('\n')
1087
1087
1088 def init_shadow_hist(self):
1088 def init_shadow_hist(self):
1089 try:
1089 try:
1090 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1090 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1091 except exceptions.UnicodeDecodeError:
1091 except exceptions.UnicodeDecodeError:
1092 print "Your ipythondir can't be decoded to unicode!"
1092 print "Your ipython_dir can't be decoded to unicode!"
1093 print "Please set HOME environment variable to something that"
1093 print "Please set HOME environment variable to something that"
1094 print r"only has ASCII characters, e.g. c:\home"
1094 print r"only has ASCII characters, e.g. c:\home"
1095 print "Now it is", self.ipythondir
1095 print "Now it is", self.ipython_dir
1096 sys.exit()
1096 sys.exit()
1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1098
1098
1099 def savehist(self):
1099 def savehist(self):
1100 """Save input history to a file (via readline library)."""
1100 """Save input history to a file (via readline library)."""
1101
1101
1102 if not self.has_readline:
1102 if not self.has_readline:
1103 return
1103 return
1104
1104
1105 try:
1105 try:
1106 self.readline.write_history_file(self.histfile)
1106 self.readline.write_history_file(self.histfile)
1107 except:
1107 except:
1108 print 'Unable to save IPython command history to file: ' + \
1108 print 'Unable to save IPython command history to file: ' + \
1109 `self.histfile`
1109 `self.histfile`
1110
1110
1111 def reloadhist(self):
1111 def reloadhist(self):
1112 """Reload the input history from disk file."""
1112 """Reload the input history from disk file."""
1113
1113
1114 if self.has_readline:
1114 if self.has_readline:
1115 try:
1115 try:
1116 self.readline.clear_history()
1116 self.readline.clear_history()
1117 self.readline.read_history_file(self.shell.histfile)
1117 self.readline.read_history_file(self.shell.histfile)
1118 except AttributeError:
1118 except AttributeError:
1119 pass
1119 pass
1120
1120
1121 def history_saving_wrapper(self, func):
1121 def history_saving_wrapper(self, func):
1122 """ Wrap func for readline history saving
1122 """ Wrap func for readline history saving
1123
1123
1124 Convert func into callable that saves & restores
1124 Convert func into callable that saves & restores
1125 history around the call """
1125 history around the call """
1126
1126
1127 if not self.has_readline:
1127 if not self.has_readline:
1128 return func
1128 return func
1129
1129
1130 def wrapper():
1130 def wrapper():
1131 self.savehist()
1131 self.savehist()
1132 try:
1132 try:
1133 func()
1133 func()
1134 finally:
1134 finally:
1135 readline.read_history_file(self.histfile)
1135 readline.read_history_file(self.histfile)
1136 return wrapper
1136 return wrapper
1137
1137
1138 #-------------------------------------------------------------------------
1138 #-------------------------------------------------------------------------
1139 # Things related to exception handling and tracebacks (not debugging)
1139 # Things related to exception handling and tracebacks (not debugging)
1140 #-------------------------------------------------------------------------
1140 #-------------------------------------------------------------------------
1141
1141
1142 def init_traceback_handlers(self, custom_exceptions):
1142 def init_traceback_handlers(self, custom_exceptions):
1143 # Syntax error handler.
1143 # Syntax error handler.
1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1145
1145
1146 # The interactive one is initialized with an offset, meaning we always
1146 # The interactive one is initialized with an offset, meaning we always
1147 # want to remove the topmost item in the traceback, which is our own
1147 # want to remove the topmost item in the traceback, which is our own
1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1150 color_scheme='NoColor',
1150 color_scheme='NoColor',
1151 tb_offset = 1)
1151 tb_offset = 1)
1152
1152
1153 # IPython itself shouldn't crash. This will produce a detailed
1153 # IPython itself shouldn't crash. This will produce a detailed
1154 # post-mortem if it does. But we only install the crash handler for
1154 # post-mortem if it does. But we only install the crash handler for
1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1156 # and lose the crash handler. This is because exceptions in the main
1156 # and lose the crash handler. This is because exceptions in the main
1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1158 # and there's no point in printing crash dumps for every user exception.
1158 # and there's no point in printing crash dumps for every user exception.
1159 if self.isthreaded:
1159 if self.isthreaded:
1160 ipCrashHandler = ultratb.FormattedTB()
1160 ipCrashHandler = ultratb.FormattedTB()
1161 else:
1161 else:
1162 from IPython.core import crashhandler
1162 from IPython.core import crashhandler
1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1164 self.set_crash_handler(ipCrashHandler)
1164 self.set_crash_handler(ipCrashHandler)
1165
1165
1166 # and add any custom exception handlers the user may have specified
1166 # and add any custom exception handlers the user may have specified
1167 self.set_custom_exc(*custom_exceptions)
1167 self.set_custom_exc(*custom_exceptions)
1168
1168
1169 def set_crash_handler(self, crashHandler):
1169 def set_crash_handler(self, crashHandler):
1170 """Set the IPython crash handler.
1170 """Set the IPython crash handler.
1171
1171
1172 This must be a callable with a signature suitable for use as
1172 This must be a callable with a signature suitable for use as
1173 sys.excepthook."""
1173 sys.excepthook."""
1174
1174
1175 # Install the given crash handler as the Python exception hook
1175 # Install the given crash handler as the Python exception hook
1176 sys.excepthook = crashHandler
1176 sys.excepthook = crashHandler
1177
1177
1178 # The instance will store a pointer to this, so that runtime code
1178 # The instance will store a pointer to this, so that runtime code
1179 # (such as magics) can access it. This is because during the
1179 # (such as magics) can access it. This is because during the
1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1181 # frameworks).
1181 # frameworks).
1182 self.sys_excepthook = sys.excepthook
1182 self.sys_excepthook = sys.excepthook
1183
1183
1184 def set_custom_exc(self,exc_tuple,handler):
1184 def set_custom_exc(self,exc_tuple,handler):
1185 """set_custom_exc(exc_tuple,handler)
1185 """set_custom_exc(exc_tuple,handler)
1186
1186
1187 Set a custom exception handler, which will be called if any of the
1187 Set a custom exception handler, which will be called if any of the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 runcode() method.
1189 runcode() method.
1190
1190
1191 Inputs:
1191 Inputs:
1192
1192
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 handler for. It is very important that you use a tuple, and NOT A
1194 handler for. It is very important that you use a tuple, and NOT A
1195 LIST here, because of the way Python's except statement works. If
1195 LIST here, because of the way Python's except statement works. If
1196 you only want to trap a single exception, use a singleton tuple:
1196 you only want to trap a single exception, use a singleton tuple:
1197
1197
1198 exc_tuple == (MyCustomException,)
1198 exc_tuple == (MyCustomException,)
1199
1199
1200 - handler: this must be defined as a function with the following
1200 - handler: this must be defined as a function with the following
1201 basic interface: def my_handler(self,etype,value,tb).
1201 basic interface: def my_handler(self,etype,value,tb).
1202
1202
1203 This will be made into an instance method (via new.instancemethod)
1203 This will be made into an instance method (via new.instancemethod)
1204 of IPython itself, and it will be called if any of the exceptions
1204 of IPython itself, and it will be called if any of the exceptions
1205 listed in the exc_tuple are caught. If the handler is None, an
1205 listed in the exc_tuple are caught. If the handler is None, an
1206 internal basic one is used, which just prints basic info.
1206 internal basic one is used, which just prints basic info.
1207
1207
1208 WARNING: by putting in your own exception handler into IPython's main
1208 WARNING: by putting in your own exception handler into IPython's main
1209 execution loop, you run a very good chance of nasty crashes. This
1209 execution loop, you run a very good chance of nasty crashes. This
1210 facility should only be used if you really know what you are doing."""
1210 facility should only be used if you really know what you are doing."""
1211
1211
1212 assert type(exc_tuple)==type(()) , \
1212 assert type(exc_tuple)==type(()) , \
1213 "The custom exceptions must be given AS A TUPLE."
1213 "The custom exceptions must be given AS A TUPLE."
1214
1214
1215 def dummy_handler(self,etype,value,tb):
1215 def dummy_handler(self,etype,value,tb):
1216 print '*** Simple custom exception handler ***'
1216 print '*** Simple custom exception handler ***'
1217 print 'Exception type :',etype
1217 print 'Exception type :',etype
1218 print 'Exception value:',value
1218 print 'Exception value:',value
1219 print 'Traceback :',tb
1219 print 'Traceback :',tb
1220 print 'Source code :','\n'.join(self.buffer)
1220 print 'Source code :','\n'.join(self.buffer)
1221
1221
1222 if handler is None: handler = dummy_handler
1222 if handler is None: handler = dummy_handler
1223
1223
1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1225 self.custom_exceptions = exc_tuple
1225 self.custom_exceptions = exc_tuple
1226
1226
1227 def excepthook(self, etype, value, tb):
1227 def excepthook(self, etype, value, tb):
1228 """One more defense for GUI apps that call sys.excepthook.
1228 """One more defense for GUI apps that call sys.excepthook.
1229
1229
1230 GUI frameworks like wxPython trap exceptions and call
1230 GUI frameworks like wxPython trap exceptions and call
1231 sys.excepthook themselves. I guess this is a feature that
1231 sys.excepthook themselves. I guess this is a feature that
1232 enables them to keep running after exceptions that would
1232 enables them to keep running after exceptions that would
1233 otherwise kill their mainloop. This is a bother for IPython
1233 otherwise kill their mainloop. This is a bother for IPython
1234 which excepts to catch all of the program exceptions with a try:
1234 which excepts to catch all of the program exceptions with a try:
1235 except: statement.
1235 except: statement.
1236
1236
1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1238 any app directly invokes sys.excepthook, it will look to the user like
1238 any app directly invokes sys.excepthook, it will look to the user like
1239 IPython crashed. In order to work around this, we can disable the
1239 IPython crashed. In order to work around this, we can disable the
1240 CrashHandler and replace it with this excepthook instead, which prints a
1240 CrashHandler and replace it with this excepthook instead, which prints a
1241 regular traceback using our InteractiveTB. In this fashion, apps which
1241 regular traceback using our InteractiveTB. In this fashion, apps which
1242 call sys.excepthook will generate a regular-looking exception from
1242 call sys.excepthook will generate a regular-looking exception from
1243 IPython, and the CrashHandler will only be triggered by real IPython
1243 IPython, and the CrashHandler will only be triggered by real IPython
1244 crashes.
1244 crashes.
1245
1245
1246 This hook should be used sparingly, only in places which are not likely
1246 This hook should be used sparingly, only in places which are not likely
1247 to be true IPython errors.
1247 to be true IPython errors.
1248 """
1248 """
1249 self.showtraceback((etype,value,tb),tb_offset=0)
1249 self.showtraceback((etype,value,tb),tb_offset=0)
1250
1250
1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1252 """Display the exception that just occurred.
1252 """Display the exception that just occurred.
1253
1253
1254 If nothing is known about the exception, this is the method which
1254 If nothing is known about the exception, this is the method which
1255 should be used throughout the code for presenting user tracebacks,
1255 should be used throughout the code for presenting user tracebacks,
1256 rather than directly invoking the InteractiveTB object.
1256 rather than directly invoking the InteractiveTB object.
1257
1257
1258 A specific showsyntaxerror() also exists, but this method can take
1258 A specific showsyntaxerror() also exists, but this method can take
1259 care of calling it if needed, so unless you are explicitly catching a
1259 care of calling it if needed, so unless you are explicitly catching a
1260 SyntaxError exception, don't try to analyze the stack manually and
1260 SyntaxError exception, don't try to analyze the stack manually and
1261 simply call this method."""
1261 simply call this method."""
1262
1262
1263
1263
1264 # Though this won't be called by syntax errors in the input line,
1264 # Though this won't be called by syntax errors in the input line,
1265 # there may be SyntaxError cases whith imported code.
1265 # there may be SyntaxError cases whith imported code.
1266
1266
1267 try:
1267 try:
1268 if exc_tuple is None:
1268 if exc_tuple is None:
1269 etype, value, tb = sys.exc_info()
1269 etype, value, tb = sys.exc_info()
1270 else:
1270 else:
1271 etype, value, tb = exc_tuple
1271 etype, value, tb = exc_tuple
1272
1272
1273 if etype is SyntaxError:
1273 if etype is SyntaxError:
1274 self.showsyntaxerror(filename)
1274 self.showsyntaxerror(filename)
1275 elif etype is UsageError:
1275 elif etype is UsageError:
1276 print "UsageError:", value
1276 print "UsageError:", value
1277 else:
1277 else:
1278 # WARNING: these variables are somewhat deprecated and not
1278 # WARNING: these variables are somewhat deprecated and not
1279 # necessarily safe to use in a threaded environment, but tools
1279 # necessarily safe to use in a threaded environment, but tools
1280 # like pdb depend on their existence, so let's set them. If we
1280 # like pdb depend on their existence, so let's set them. If we
1281 # find problems in the field, we'll need to revisit their use.
1281 # find problems in the field, we'll need to revisit their use.
1282 sys.last_type = etype
1282 sys.last_type = etype
1283 sys.last_value = value
1283 sys.last_value = value
1284 sys.last_traceback = tb
1284 sys.last_traceback = tb
1285
1285
1286 if etype in self.custom_exceptions:
1286 if etype in self.custom_exceptions:
1287 self.CustomTB(etype,value,tb)
1287 self.CustomTB(etype,value,tb)
1288 else:
1288 else:
1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1290 if self.InteractiveTB.call_pdb and self.has_readline:
1290 if self.InteractiveTB.call_pdb and self.has_readline:
1291 # pdb mucks up readline, fix it back
1291 # pdb mucks up readline, fix it back
1292 self.set_completer()
1292 self.set_completer()
1293 except KeyboardInterrupt:
1293 except KeyboardInterrupt:
1294 self.write("\nKeyboardInterrupt\n")
1294 self.write("\nKeyboardInterrupt\n")
1295
1295
1296 def showsyntaxerror(self, filename=None):
1296 def showsyntaxerror(self, filename=None):
1297 """Display the syntax error that just occurred.
1297 """Display the syntax error that just occurred.
1298
1298
1299 This doesn't display a stack trace because there isn't one.
1299 This doesn't display a stack trace because there isn't one.
1300
1300
1301 If a filename is given, it is stuffed in the exception instead
1301 If a filename is given, it is stuffed in the exception instead
1302 of what was there before (because Python's parser always uses
1302 of what was there before (because Python's parser always uses
1303 "<string>" when reading from a string).
1303 "<string>" when reading from a string).
1304 """
1304 """
1305 etype, value, last_traceback = sys.exc_info()
1305 etype, value, last_traceback = sys.exc_info()
1306
1306
1307 # See note about these variables in showtraceback() below
1307 # See note about these variables in showtraceback() below
1308 sys.last_type = etype
1308 sys.last_type = etype
1309 sys.last_value = value
1309 sys.last_value = value
1310 sys.last_traceback = last_traceback
1310 sys.last_traceback = last_traceback
1311
1311
1312 if filename and etype is SyntaxError:
1312 if filename and etype is SyntaxError:
1313 # Work hard to stuff the correct filename in the exception
1313 # Work hard to stuff the correct filename in the exception
1314 try:
1314 try:
1315 msg, (dummy_filename, lineno, offset, line) = value
1315 msg, (dummy_filename, lineno, offset, line) = value
1316 except:
1316 except:
1317 # Not the format we expect; leave it alone
1317 # Not the format we expect; leave it alone
1318 pass
1318 pass
1319 else:
1319 else:
1320 # Stuff in the right filename
1320 # Stuff in the right filename
1321 try:
1321 try:
1322 # Assume SyntaxError is a class exception
1322 # Assume SyntaxError is a class exception
1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1324 except:
1324 except:
1325 # If that failed, assume SyntaxError is a string
1325 # If that failed, assume SyntaxError is a string
1326 value = msg, (filename, lineno, offset, line)
1326 value = msg, (filename, lineno, offset, line)
1327 self.SyntaxTB(etype,value,[])
1327 self.SyntaxTB(etype,value,[])
1328
1328
1329 def edit_syntax_error(self):
1329 def edit_syntax_error(self):
1330 """The bottom half of the syntax error handler called in the main loop.
1330 """The bottom half of the syntax error handler called in the main loop.
1331
1331
1332 Loop until syntax error is fixed or user cancels.
1332 Loop until syntax error is fixed or user cancels.
1333 """
1333 """
1334
1334
1335 while self.SyntaxTB.last_syntax_error:
1335 while self.SyntaxTB.last_syntax_error:
1336 # copy and clear last_syntax_error
1336 # copy and clear last_syntax_error
1337 err = self.SyntaxTB.clear_err_state()
1337 err = self.SyntaxTB.clear_err_state()
1338 if not self._should_recompile(err):
1338 if not self._should_recompile(err):
1339 return
1339 return
1340 try:
1340 try:
1341 # may set last_syntax_error again if a SyntaxError is raised
1341 # may set last_syntax_error again if a SyntaxError is raised
1342 self.safe_execfile(err.filename,self.user_ns)
1342 self.safe_execfile(err.filename,self.user_ns)
1343 except:
1343 except:
1344 self.showtraceback()
1344 self.showtraceback()
1345 else:
1345 else:
1346 try:
1346 try:
1347 f = file(err.filename)
1347 f = file(err.filename)
1348 try:
1348 try:
1349 # This should be inside a display_trap block and I
1349 # This should be inside a display_trap block and I
1350 # think it is.
1350 # think it is.
1351 sys.displayhook(f.read())
1351 sys.displayhook(f.read())
1352 finally:
1352 finally:
1353 f.close()
1353 f.close()
1354 except:
1354 except:
1355 self.showtraceback()
1355 self.showtraceback()
1356
1356
1357 def _should_recompile(self,e):
1357 def _should_recompile(self,e):
1358 """Utility routine for edit_syntax_error"""
1358 """Utility routine for edit_syntax_error"""
1359
1359
1360 if e.filename in ('<ipython console>','<input>','<string>',
1360 if e.filename in ('<ipython console>','<input>','<string>',
1361 '<console>','<BackgroundJob compilation>',
1361 '<console>','<BackgroundJob compilation>',
1362 None):
1362 None):
1363
1363
1364 return False
1364 return False
1365 try:
1365 try:
1366 if (self.autoedit_syntax and
1366 if (self.autoedit_syntax and
1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1368 '[Y/n] ','y')):
1368 '[Y/n] ','y')):
1369 return False
1369 return False
1370 except EOFError:
1370 except EOFError:
1371 return False
1371 return False
1372
1372
1373 def int0(x):
1373 def int0(x):
1374 try:
1374 try:
1375 return int(x)
1375 return int(x)
1376 except TypeError:
1376 except TypeError:
1377 return 0
1377 return 0
1378 # always pass integer line and offset values to editor hook
1378 # always pass integer line and offset values to editor hook
1379 try:
1379 try:
1380 self.hooks.fix_error_editor(e.filename,
1380 self.hooks.fix_error_editor(e.filename,
1381 int0(e.lineno),int0(e.offset),e.msg)
1381 int0(e.lineno),int0(e.offset),e.msg)
1382 except TryNext:
1382 except TryNext:
1383 warn('Could not open editor')
1383 warn('Could not open editor')
1384 return False
1384 return False
1385 return True
1385 return True
1386
1386
1387 #-------------------------------------------------------------------------
1387 #-------------------------------------------------------------------------
1388 # Things related to tab completion
1388 # Things related to tab completion
1389 #-------------------------------------------------------------------------
1389 #-------------------------------------------------------------------------
1390
1390
1391 def complete(self, text):
1391 def complete(self, text):
1392 """Return a sorted list of all possible completions on text.
1392 """Return a sorted list of all possible completions on text.
1393
1393
1394 Inputs:
1394 Inputs:
1395
1395
1396 - text: a string of text to be completed on.
1396 - text: a string of text to be completed on.
1397
1397
1398 This is a wrapper around the completion mechanism, similar to what
1398 This is a wrapper around the completion mechanism, similar to what
1399 readline does at the command line when the TAB key is hit. By
1399 readline does at the command line when the TAB key is hit. By
1400 exposing it as a method, it can be used by other non-readline
1400 exposing it as a method, it can be used by other non-readline
1401 environments (such as GUIs) for text completion.
1401 environments (such as GUIs) for text completion.
1402
1402
1403 Simple usage example:
1403 Simple usage example:
1404
1404
1405 In [7]: x = 'hello'
1405 In [7]: x = 'hello'
1406
1406
1407 In [8]: x
1407 In [8]: x
1408 Out[8]: 'hello'
1408 Out[8]: 'hello'
1409
1409
1410 In [9]: print x
1410 In [9]: print x
1411 hello
1411 hello
1412
1412
1413 In [10]: _ip.complete('x.l')
1413 In [10]: _ip.complete('x.l')
1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1415 """
1415 """
1416
1416
1417 # Inject names into __builtin__ so we can complete on the added names.
1417 # Inject names into __builtin__ so we can complete on the added names.
1418 with self.builtin_trap:
1418 with self.builtin_trap:
1419 complete = self.Completer.complete
1419 complete = self.Completer.complete
1420 state = 0
1420 state = 0
1421 # use a dict so we get unique keys, since ipyhton's multiple
1421 # use a dict so we get unique keys, since ipyhton's multiple
1422 # completers can return duplicates. When we make 2.4 a requirement,
1422 # completers can return duplicates. When we make 2.4 a requirement,
1423 # start using sets instead, which are faster.
1423 # start using sets instead, which are faster.
1424 comps = {}
1424 comps = {}
1425 while True:
1425 while True:
1426 newcomp = complete(text,state,line_buffer=text)
1426 newcomp = complete(text,state,line_buffer=text)
1427 if newcomp is None:
1427 if newcomp is None:
1428 break
1428 break
1429 comps[newcomp] = 1
1429 comps[newcomp] = 1
1430 state += 1
1430 state += 1
1431 outcomps = comps.keys()
1431 outcomps = comps.keys()
1432 outcomps.sort()
1432 outcomps.sort()
1433 #print "T:",text,"OC:",outcomps # dbg
1433 #print "T:",text,"OC:",outcomps # dbg
1434 #print "vars:",self.user_ns.keys()
1434 #print "vars:",self.user_ns.keys()
1435 return outcomps
1435 return outcomps
1436
1436
1437 def set_custom_completer(self,completer,pos=0):
1437 def set_custom_completer(self,completer,pos=0):
1438 """Adds a new custom completer function.
1438 """Adds a new custom completer function.
1439
1439
1440 The position argument (defaults to 0) is the index in the completers
1440 The position argument (defaults to 0) is the index in the completers
1441 list where you want the completer to be inserted."""
1441 list where you want the completer to be inserted."""
1442
1442
1443 newcomp = new.instancemethod(completer,self.Completer,
1443 newcomp = new.instancemethod(completer,self.Completer,
1444 self.Completer.__class__)
1444 self.Completer.__class__)
1445 self.Completer.matchers.insert(pos,newcomp)
1445 self.Completer.matchers.insert(pos,newcomp)
1446
1446
1447 def set_completer(self):
1447 def set_completer(self):
1448 """Reset readline's completer to be our own."""
1448 """Reset readline's completer to be our own."""
1449 self.readline.set_completer(self.Completer.complete)
1449 self.readline.set_completer(self.Completer.complete)
1450
1450
1451 def set_completer_frame(self, frame=None):
1451 def set_completer_frame(self, frame=None):
1452 """Set the frame of the completer."""
1452 """Set the frame of the completer."""
1453 if frame:
1453 if frame:
1454 self.Completer.namespace = frame.f_locals
1454 self.Completer.namespace = frame.f_locals
1455 self.Completer.global_namespace = frame.f_globals
1455 self.Completer.global_namespace = frame.f_globals
1456 else:
1456 else:
1457 self.Completer.namespace = self.user_ns
1457 self.Completer.namespace = self.user_ns
1458 self.Completer.global_namespace = self.user_global_ns
1458 self.Completer.global_namespace = self.user_global_ns
1459
1459
1460 #-------------------------------------------------------------------------
1460 #-------------------------------------------------------------------------
1461 # Things related to readline
1461 # Things related to readline
1462 #-------------------------------------------------------------------------
1462 #-------------------------------------------------------------------------
1463
1463
1464 def init_readline(self):
1464 def init_readline(self):
1465 """Command history completion/saving/reloading."""
1465 """Command history completion/saving/reloading."""
1466
1466
1467 self.rl_next_input = None
1467 self.rl_next_input = None
1468 self.rl_do_indent = False
1468 self.rl_do_indent = False
1469
1469
1470 if not self.readline_use:
1470 if not self.readline_use:
1471 return
1471 return
1472
1472
1473 import IPython.utils.rlineimpl as readline
1473 import IPython.utils.rlineimpl as readline
1474
1474
1475 if not readline.have_readline:
1475 if not readline.have_readline:
1476 self.has_readline = 0
1476 self.has_readline = 0
1477 self.readline = None
1477 self.readline = None
1478 # no point in bugging windows users with this every time:
1478 # no point in bugging windows users with this every time:
1479 warn('Readline services not available on this platform.')
1479 warn('Readline services not available on this platform.')
1480 else:
1480 else:
1481 sys.modules['readline'] = readline
1481 sys.modules['readline'] = readline
1482 import atexit
1482 import atexit
1483 from IPython.core.completer import IPCompleter
1483 from IPython.core.completer import IPCompleter
1484 self.Completer = IPCompleter(self,
1484 self.Completer = IPCompleter(self,
1485 self.user_ns,
1485 self.user_ns,
1486 self.user_global_ns,
1486 self.user_global_ns,
1487 self.readline_omit__names,
1487 self.readline_omit__names,
1488 self.alias_manager.alias_table)
1488 self.alias_manager.alias_table)
1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1490 self.strdispatchers['complete_command'] = sdisp
1490 self.strdispatchers['complete_command'] = sdisp
1491 self.Completer.custom_completers = sdisp
1491 self.Completer.custom_completers = sdisp
1492 # Platform-specific configuration
1492 # Platform-specific configuration
1493 if os.name == 'nt':
1493 if os.name == 'nt':
1494 self.readline_startup_hook = readline.set_pre_input_hook
1494 self.readline_startup_hook = readline.set_pre_input_hook
1495 else:
1495 else:
1496 self.readline_startup_hook = readline.set_startup_hook
1496 self.readline_startup_hook = readline.set_startup_hook
1497
1497
1498 # Load user's initrc file (readline config)
1498 # Load user's initrc file (readline config)
1499 # Or if libedit is used, load editrc.
1499 # Or if libedit is used, load editrc.
1500 inputrc_name = os.environ.get('INPUTRC')
1500 inputrc_name = os.environ.get('INPUTRC')
1501 if inputrc_name is None:
1501 if inputrc_name is None:
1502 home_dir = get_home_dir()
1502 home_dir = get_home_dir()
1503 if home_dir is not None:
1503 if home_dir is not None:
1504 inputrc_name = '.inputrc'
1504 inputrc_name = '.inputrc'
1505 if readline.uses_libedit:
1505 if readline.uses_libedit:
1506 inputrc_name = '.editrc'
1506 inputrc_name = '.editrc'
1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1508 if os.path.isfile(inputrc_name):
1508 if os.path.isfile(inputrc_name):
1509 try:
1509 try:
1510 readline.read_init_file(inputrc_name)
1510 readline.read_init_file(inputrc_name)
1511 except:
1511 except:
1512 warn('Problems reading readline initialization file <%s>'
1512 warn('Problems reading readline initialization file <%s>'
1513 % inputrc_name)
1513 % inputrc_name)
1514
1514
1515 self.has_readline = 1
1515 self.has_readline = 1
1516 self.readline = readline
1516 self.readline = readline
1517 # save this in sys so embedded copies can restore it properly
1517 # save this in sys so embedded copies can restore it properly
1518 sys.ipcompleter = self.Completer.complete
1518 sys.ipcompleter = self.Completer.complete
1519 self.set_completer()
1519 self.set_completer()
1520
1520
1521 # Configure readline according to user's prefs
1521 # Configure readline according to user's prefs
1522 # This is only done if GNU readline is being used. If libedit
1522 # This is only done if GNU readline is being used. If libedit
1523 # is being used (as on Leopard) the readline config is
1523 # is being used (as on Leopard) the readline config is
1524 # not run as the syntax for libedit is different.
1524 # not run as the syntax for libedit is different.
1525 if not readline.uses_libedit:
1525 if not readline.uses_libedit:
1526 for rlcommand in self.readline_parse_and_bind:
1526 for rlcommand in self.readline_parse_and_bind:
1527 #print "loading rl:",rlcommand # dbg
1527 #print "loading rl:",rlcommand # dbg
1528 readline.parse_and_bind(rlcommand)
1528 readline.parse_and_bind(rlcommand)
1529
1529
1530 # Remove some chars from the delimiters list. If we encounter
1530 # Remove some chars from the delimiters list. If we encounter
1531 # unicode chars, discard them.
1531 # unicode chars, discard them.
1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1533 delims = delims.translate(string._idmap,
1533 delims = delims.translate(string._idmap,
1534 self.readline_remove_delims)
1534 self.readline_remove_delims)
1535 readline.set_completer_delims(delims)
1535 readline.set_completer_delims(delims)
1536 # otherwise we end up with a monster history after a while:
1536 # otherwise we end up with a monster history after a while:
1537 readline.set_history_length(1000)
1537 readline.set_history_length(1000)
1538 try:
1538 try:
1539 #print '*** Reading readline history' # dbg
1539 #print '*** Reading readline history' # dbg
1540 readline.read_history_file(self.histfile)
1540 readline.read_history_file(self.histfile)
1541 except IOError:
1541 except IOError:
1542 pass # It doesn't exist yet.
1542 pass # It doesn't exist yet.
1543
1543
1544 atexit.register(self.atexit_operations)
1544 atexit.register(self.atexit_operations)
1545 del atexit
1545 del atexit
1546
1546
1547 # Configure auto-indent for all platforms
1547 # Configure auto-indent for all platforms
1548 self.set_autoindent(self.autoindent)
1548 self.set_autoindent(self.autoindent)
1549
1549
1550 def set_next_input(self, s):
1550 def set_next_input(self, s):
1551 """ Sets the 'default' input string for the next command line.
1551 """ Sets the 'default' input string for the next command line.
1552
1552
1553 Requires readline.
1553 Requires readline.
1554
1554
1555 Example:
1555 Example:
1556
1556
1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1558 [D:\ipython]|2> Hello Word_ # cursor is here
1558 [D:\ipython]|2> Hello Word_ # cursor is here
1559 """
1559 """
1560
1560
1561 self.rl_next_input = s
1561 self.rl_next_input = s
1562
1562
1563 def pre_readline(self):
1563 def pre_readline(self):
1564 """readline hook to be used at the start of each line.
1564 """readline hook to be used at the start of each line.
1565
1565
1566 Currently it handles auto-indent only."""
1566 Currently it handles auto-indent only."""
1567
1567
1568 #debugx('self.indent_current_nsp','pre_readline:')
1568 #debugx('self.indent_current_nsp','pre_readline:')
1569
1569
1570 if self.rl_do_indent:
1570 if self.rl_do_indent:
1571 self.readline.insert_text(self._indent_current_str())
1571 self.readline.insert_text(self._indent_current_str())
1572 if self.rl_next_input is not None:
1572 if self.rl_next_input is not None:
1573 self.readline.insert_text(self.rl_next_input)
1573 self.readline.insert_text(self.rl_next_input)
1574 self.rl_next_input = None
1574 self.rl_next_input = None
1575
1575
1576 def _indent_current_str(self):
1576 def _indent_current_str(self):
1577 """return the current level of indentation as a string"""
1577 """return the current level of indentation as a string"""
1578 return self.indent_current_nsp * ' '
1578 return self.indent_current_nsp * ' '
1579
1579
1580 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1581 # Things related to magics
1581 # Things related to magics
1582 #-------------------------------------------------------------------------
1582 #-------------------------------------------------------------------------
1583
1583
1584 def init_magics(self):
1584 def init_magics(self):
1585 # Set user colors (don't do it in the constructor above so that it
1585 # Set user colors (don't do it in the constructor above so that it
1586 # doesn't crash if colors option is invalid)
1586 # doesn't crash if colors option is invalid)
1587 self.magic_colors(self.colors)
1587 self.magic_colors(self.colors)
1588
1588
1589 def magic(self,arg_s):
1589 def magic(self,arg_s):
1590 """Call a magic function by name.
1590 """Call a magic function by name.
1591
1591
1592 Input: a string containing the name of the magic function to call and any
1592 Input: a string containing the name of the magic function to call and any
1593 additional arguments to be passed to the magic.
1593 additional arguments to be passed to the magic.
1594
1594
1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1596 prompt:
1596 prompt:
1597
1597
1598 In[1]: %name -opt foo bar
1598 In[1]: %name -opt foo bar
1599
1599
1600 To call a magic without arguments, simply use magic('name').
1600 To call a magic without arguments, simply use magic('name').
1601
1601
1602 This provides a proper Python function to call IPython's magics in any
1602 This provides a proper Python function to call IPython's magics in any
1603 valid Python code you can type at the interpreter, including loops and
1603 valid Python code you can type at the interpreter, including loops and
1604 compound statements.
1604 compound statements.
1605 """
1605 """
1606
1606
1607 args = arg_s.split(' ',1)
1607 args = arg_s.split(' ',1)
1608 magic_name = args[0]
1608 magic_name = args[0]
1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1610
1610
1611 try:
1611 try:
1612 magic_args = args[1]
1612 magic_args = args[1]
1613 except IndexError:
1613 except IndexError:
1614 magic_args = ''
1614 magic_args = ''
1615 fn = getattr(self,'magic_'+magic_name,None)
1615 fn = getattr(self,'magic_'+magic_name,None)
1616 if fn is None:
1616 if fn is None:
1617 error("Magic function `%s` not found." % magic_name)
1617 error("Magic function `%s` not found." % magic_name)
1618 else:
1618 else:
1619 magic_args = self.var_expand(magic_args,1)
1619 magic_args = self.var_expand(magic_args,1)
1620 with nested(self.builtin_trap,):
1620 with nested(self.builtin_trap,):
1621 result = fn(magic_args)
1621 result = fn(magic_args)
1622 return result
1622 return result
1623
1623
1624 def define_magic(self, magicname, func):
1624 def define_magic(self, magicname, func):
1625 """Expose own function as magic function for ipython
1625 """Expose own function as magic function for ipython
1626
1626
1627 def foo_impl(self,parameter_s=''):
1627 def foo_impl(self,parameter_s=''):
1628 'My very own magic!. (Use docstrings, IPython reads them).'
1628 'My very own magic!. (Use docstrings, IPython reads them).'
1629 print 'Magic function. Passed parameter is between < >:'
1629 print 'Magic function. Passed parameter is between < >:'
1630 print '<%s>' % parameter_s
1630 print '<%s>' % parameter_s
1631 print 'The self object is:',self
1631 print 'The self object is:',self
1632
1632
1633 self.define_magic('foo',foo_impl)
1633 self.define_magic('foo',foo_impl)
1634 """
1634 """
1635
1635
1636 import new
1636 import new
1637 im = new.instancemethod(func,self, self.__class__)
1637 im = new.instancemethod(func,self, self.__class__)
1638 old = getattr(self, "magic_" + magicname, None)
1638 old = getattr(self, "magic_" + magicname, None)
1639 setattr(self, "magic_" + magicname, im)
1639 setattr(self, "magic_" + magicname, im)
1640 return old
1640 return old
1641
1641
1642 #-------------------------------------------------------------------------
1642 #-------------------------------------------------------------------------
1643 # Things related to macros
1643 # Things related to macros
1644 #-------------------------------------------------------------------------
1644 #-------------------------------------------------------------------------
1645
1645
1646 def define_macro(self, name, themacro):
1646 def define_macro(self, name, themacro):
1647 """Define a new macro
1647 """Define a new macro
1648
1648
1649 Parameters
1649 Parameters
1650 ----------
1650 ----------
1651 name : str
1651 name : str
1652 The name of the macro.
1652 The name of the macro.
1653 themacro : str or Macro
1653 themacro : str or Macro
1654 The action to do upon invoking the macro. If a string, a new
1654 The action to do upon invoking the macro. If a string, a new
1655 Macro object is created by passing the string to it.
1655 Macro object is created by passing the string to it.
1656 """
1656 """
1657
1657
1658 from IPython.core import macro
1658 from IPython.core import macro
1659
1659
1660 if isinstance(themacro, basestring):
1660 if isinstance(themacro, basestring):
1661 themacro = macro.Macro(themacro)
1661 themacro = macro.Macro(themacro)
1662 if not isinstance(themacro, macro.Macro):
1662 if not isinstance(themacro, macro.Macro):
1663 raise ValueError('A macro must be a string or a Macro instance.')
1663 raise ValueError('A macro must be a string or a Macro instance.')
1664 self.user_ns[name] = themacro
1664 self.user_ns[name] = themacro
1665
1665
1666 #-------------------------------------------------------------------------
1666 #-------------------------------------------------------------------------
1667 # Things related to the running of system commands
1667 # Things related to the running of system commands
1668 #-------------------------------------------------------------------------
1668 #-------------------------------------------------------------------------
1669
1669
1670 def system(self, cmd):
1670 def system(self, cmd):
1671 """Make a system call, using IPython."""
1671 """Make a system call, using IPython."""
1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1673
1673
1674 #-------------------------------------------------------------------------
1674 #-------------------------------------------------------------------------
1675 # Things related to aliases
1675 # Things related to aliases
1676 #-------------------------------------------------------------------------
1676 #-------------------------------------------------------------------------
1677
1677
1678 def init_alias(self):
1678 def init_alias(self):
1679 self.alias_manager = AliasManager(self, config=self.config)
1679 self.alias_manager = AliasManager(self, config=self.config)
1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1681
1681
1682 #-------------------------------------------------------------------------
1682 #-------------------------------------------------------------------------
1683 # Things related to the running of code
1683 # Things related to the running of code
1684 #-------------------------------------------------------------------------
1684 #-------------------------------------------------------------------------
1685
1685
1686 def ex(self, cmd):
1686 def ex(self, cmd):
1687 """Execute a normal python statement in user namespace."""
1687 """Execute a normal python statement in user namespace."""
1688 with nested(self.builtin_trap,):
1688 with nested(self.builtin_trap,):
1689 exec cmd in self.user_global_ns, self.user_ns
1689 exec cmd in self.user_global_ns, self.user_ns
1690
1690
1691 def ev(self, expr):
1691 def ev(self, expr):
1692 """Evaluate python expression expr in user namespace.
1692 """Evaluate python expression expr in user namespace.
1693
1693
1694 Returns the result of evaluation
1694 Returns the result of evaluation
1695 """
1695 """
1696 with nested(self.builtin_trap,):
1696 with nested(self.builtin_trap,):
1697 return eval(expr, self.user_global_ns, self.user_ns)
1697 return eval(expr, self.user_global_ns, self.user_ns)
1698
1698
1699 def mainloop(self, display_banner=None):
1699 def mainloop(self, display_banner=None):
1700 """Start the mainloop.
1700 """Start the mainloop.
1701
1701
1702 If an optional banner argument is given, it will override the
1702 If an optional banner argument is given, it will override the
1703 internally created default banner.
1703 internally created default banner.
1704 """
1704 """
1705
1705
1706 with nested(self.builtin_trap, self.display_trap):
1706 with nested(self.builtin_trap, self.display_trap):
1707
1707
1708 # if you run stuff with -c <cmd>, raw hist is not updated
1708 # if you run stuff with -c <cmd>, raw hist is not updated
1709 # ensure that it's in sync
1709 # ensure that it's in sync
1710 if len(self.input_hist) != len (self.input_hist_raw):
1710 if len(self.input_hist) != len (self.input_hist_raw):
1711 self.input_hist_raw = InputList(self.input_hist)
1711 self.input_hist_raw = InputList(self.input_hist)
1712
1712
1713 while 1:
1713 while 1:
1714 try:
1714 try:
1715 self.interact(display_banner=display_banner)
1715 self.interact(display_banner=display_banner)
1716 #self.interact_with_readline()
1716 #self.interact_with_readline()
1717 # XXX for testing of a readline-decoupled repl loop, call
1717 # XXX for testing of a readline-decoupled repl loop, call
1718 # interact_with_readline above
1718 # interact_with_readline above
1719 break
1719 break
1720 except KeyboardInterrupt:
1720 except KeyboardInterrupt:
1721 # this should not be necessary, but KeyboardInterrupt
1721 # this should not be necessary, but KeyboardInterrupt
1722 # handling seems rather unpredictable...
1722 # handling seems rather unpredictable...
1723 self.write("\nKeyboardInterrupt in interact()\n")
1723 self.write("\nKeyboardInterrupt in interact()\n")
1724
1724
1725 def interact_prompt(self):
1725 def interact_prompt(self):
1726 """ Print the prompt (in read-eval-print loop)
1726 """ Print the prompt (in read-eval-print loop)
1727
1727
1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1729 used in standard IPython flow.
1729 used in standard IPython flow.
1730 """
1730 """
1731 if self.more:
1731 if self.more:
1732 try:
1732 try:
1733 prompt = self.hooks.generate_prompt(True)
1733 prompt = self.hooks.generate_prompt(True)
1734 except:
1734 except:
1735 self.showtraceback()
1735 self.showtraceback()
1736 if self.autoindent:
1736 if self.autoindent:
1737 self.rl_do_indent = True
1737 self.rl_do_indent = True
1738
1738
1739 else:
1739 else:
1740 try:
1740 try:
1741 prompt = self.hooks.generate_prompt(False)
1741 prompt = self.hooks.generate_prompt(False)
1742 except:
1742 except:
1743 self.showtraceback()
1743 self.showtraceback()
1744 self.write(prompt)
1744 self.write(prompt)
1745
1745
1746 def interact_handle_input(self,line):
1746 def interact_handle_input(self,line):
1747 """ Handle the input line (in read-eval-print loop)
1747 """ Handle the input line (in read-eval-print loop)
1748
1748
1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1750 used in standard IPython flow.
1750 used in standard IPython flow.
1751 """
1751 """
1752 if line.lstrip() == line:
1752 if line.lstrip() == line:
1753 self.shadowhist.add(line.strip())
1753 self.shadowhist.add(line.strip())
1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1755
1755
1756 if line.strip():
1756 if line.strip():
1757 if self.more:
1757 if self.more:
1758 self.input_hist_raw[-1] += '%s\n' % line
1758 self.input_hist_raw[-1] += '%s\n' % line
1759 else:
1759 else:
1760 self.input_hist_raw.append('%s\n' % line)
1760 self.input_hist_raw.append('%s\n' % line)
1761
1761
1762
1762
1763 self.more = self.push_line(lineout)
1763 self.more = self.push_line(lineout)
1764 if (self.SyntaxTB.last_syntax_error and
1764 if (self.SyntaxTB.last_syntax_error and
1765 self.autoedit_syntax):
1765 self.autoedit_syntax):
1766 self.edit_syntax_error()
1766 self.edit_syntax_error()
1767
1767
1768 def interact_with_readline(self):
1768 def interact_with_readline(self):
1769 """ Demo of using interact_handle_input, interact_prompt
1769 """ Demo of using interact_handle_input, interact_prompt
1770
1770
1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1772 it should work like this.
1772 it should work like this.
1773 """
1773 """
1774 self.readline_startup_hook(self.pre_readline)
1774 self.readline_startup_hook(self.pre_readline)
1775 while not self.exit_now:
1775 while not self.exit_now:
1776 self.interact_prompt()
1776 self.interact_prompt()
1777 if self.more:
1777 if self.more:
1778 self.rl_do_indent = True
1778 self.rl_do_indent = True
1779 else:
1779 else:
1780 self.rl_do_indent = False
1780 self.rl_do_indent = False
1781 line = raw_input_original().decode(self.stdin_encoding)
1781 line = raw_input_original().decode(self.stdin_encoding)
1782 self.interact_handle_input(line)
1782 self.interact_handle_input(line)
1783
1783
1784 def interact(self, display_banner=None):
1784 def interact(self, display_banner=None):
1785 """Closely emulate the interactive Python console."""
1785 """Closely emulate the interactive Python console."""
1786
1786
1787 # batch run -> do not interact
1787 # batch run -> do not interact
1788 if self.exit_now:
1788 if self.exit_now:
1789 return
1789 return
1790
1790
1791 if display_banner is None:
1791 if display_banner is None:
1792 display_banner = self.display_banner
1792 display_banner = self.display_banner
1793 if display_banner:
1793 if display_banner:
1794 self.show_banner()
1794 self.show_banner()
1795
1795
1796 more = 0
1796 more = 0
1797
1797
1798 # Mark activity in the builtins
1798 # Mark activity in the builtins
1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1800
1800
1801 if self.has_readline:
1801 if self.has_readline:
1802 self.readline_startup_hook(self.pre_readline)
1802 self.readline_startup_hook(self.pre_readline)
1803 # exit_now is set by a call to %Exit or %Quit, through the
1803 # exit_now is set by a call to %Exit or %Quit, through the
1804 # ask_exit callback.
1804 # ask_exit callback.
1805
1805
1806 while not self.exit_now:
1806 while not self.exit_now:
1807 self.hooks.pre_prompt_hook()
1807 self.hooks.pre_prompt_hook()
1808 if more:
1808 if more:
1809 try:
1809 try:
1810 prompt = self.hooks.generate_prompt(True)
1810 prompt = self.hooks.generate_prompt(True)
1811 except:
1811 except:
1812 self.showtraceback()
1812 self.showtraceback()
1813 if self.autoindent:
1813 if self.autoindent:
1814 self.rl_do_indent = True
1814 self.rl_do_indent = True
1815
1815
1816 else:
1816 else:
1817 try:
1817 try:
1818 prompt = self.hooks.generate_prompt(False)
1818 prompt = self.hooks.generate_prompt(False)
1819 except:
1819 except:
1820 self.showtraceback()
1820 self.showtraceback()
1821 try:
1821 try:
1822 line = self.raw_input(prompt, more)
1822 line = self.raw_input(prompt, more)
1823 if self.exit_now:
1823 if self.exit_now:
1824 # quick exit on sys.std[in|out] close
1824 # quick exit on sys.std[in|out] close
1825 break
1825 break
1826 if self.autoindent:
1826 if self.autoindent:
1827 self.rl_do_indent = False
1827 self.rl_do_indent = False
1828
1828
1829 except KeyboardInterrupt:
1829 except KeyboardInterrupt:
1830 #double-guard against keyboardinterrupts during kbdint handling
1830 #double-guard against keyboardinterrupts during kbdint handling
1831 try:
1831 try:
1832 self.write('\nKeyboardInterrupt\n')
1832 self.write('\nKeyboardInterrupt\n')
1833 self.resetbuffer()
1833 self.resetbuffer()
1834 # keep cache in sync with the prompt counter:
1834 # keep cache in sync with the prompt counter:
1835 self.outputcache.prompt_count -= 1
1835 self.outputcache.prompt_count -= 1
1836
1836
1837 if self.autoindent:
1837 if self.autoindent:
1838 self.indent_current_nsp = 0
1838 self.indent_current_nsp = 0
1839 more = 0
1839 more = 0
1840 except KeyboardInterrupt:
1840 except KeyboardInterrupt:
1841 pass
1841 pass
1842 except EOFError:
1842 except EOFError:
1843 if self.autoindent:
1843 if self.autoindent:
1844 self.rl_do_indent = False
1844 self.rl_do_indent = False
1845 self.readline_startup_hook(None)
1845 self.readline_startup_hook(None)
1846 self.write('\n')
1846 self.write('\n')
1847 self.exit()
1847 self.exit()
1848 except bdb.BdbQuit:
1848 except bdb.BdbQuit:
1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1850 'Because of how pdb handles the stack, it is impossible\n'
1850 'Because of how pdb handles the stack, it is impossible\n'
1851 'for IPython to properly format this particular exception.\n'
1851 'for IPython to properly format this particular exception.\n'
1852 'IPython will resume normal operation.')
1852 'IPython will resume normal operation.')
1853 except:
1853 except:
1854 # exceptions here are VERY RARE, but they can be triggered
1854 # exceptions here are VERY RARE, but they can be triggered
1855 # asynchronously by signal handlers, for example.
1855 # asynchronously by signal handlers, for example.
1856 self.showtraceback()
1856 self.showtraceback()
1857 else:
1857 else:
1858 more = self.push_line(line)
1858 more = self.push_line(line)
1859 if (self.SyntaxTB.last_syntax_error and
1859 if (self.SyntaxTB.last_syntax_error and
1860 self.autoedit_syntax):
1860 self.autoedit_syntax):
1861 self.edit_syntax_error()
1861 self.edit_syntax_error()
1862
1862
1863 # We are off again...
1863 # We are off again...
1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1865
1865
1866 def safe_execfile(self, fname, *where, **kw):
1866 def safe_execfile(self, fname, *where, **kw):
1867 """A safe version of the builtin execfile().
1867 """A safe version of the builtin execfile().
1868
1868
1869 This version will never throw an exception, but instead print
1869 This version will never throw an exception, but instead print
1870 helpful error messages to the screen. This only works on pure
1870 helpful error messages to the screen. This only works on pure
1871 Python files with the .py extension.
1871 Python files with the .py extension.
1872
1872
1873 Parameters
1873 Parameters
1874 ----------
1874 ----------
1875 fname : string
1875 fname : string
1876 The name of the file to be executed.
1876 The name of the file to be executed.
1877 where : tuple
1877 where : tuple
1878 One or two namespaces, passed to execfile() as (globals,locals).
1878 One or two namespaces, passed to execfile() as (globals,locals).
1879 If only one is given, it is passed as both.
1879 If only one is given, it is passed as both.
1880 exit_ignore : bool (False)
1880 exit_ignore : bool (False)
1881 If True, then don't print errors for non-zero exit statuses.
1881 If True, then don't print errors for non-zero exit statuses.
1882 """
1882 """
1883 kw.setdefault('exit_ignore', False)
1883 kw.setdefault('exit_ignore', False)
1884
1884
1885 fname = os.path.abspath(os.path.expanduser(fname))
1885 fname = os.path.abspath(os.path.expanduser(fname))
1886
1886
1887 # Make sure we have a .py file
1887 # Make sure we have a .py file
1888 if not fname.endswith('.py'):
1888 if not fname.endswith('.py'):
1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1890
1890
1891 # Make sure we can open the file
1891 # Make sure we can open the file
1892 try:
1892 try:
1893 with open(fname) as thefile:
1893 with open(fname) as thefile:
1894 pass
1894 pass
1895 except:
1895 except:
1896 warn('Could not open file <%s> for safe execution.' % fname)
1896 warn('Could not open file <%s> for safe execution.' % fname)
1897 return
1897 return
1898
1898
1899 # Find things also in current directory. This is needed to mimic the
1899 # Find things also in current directory. This is needed to mimic the
1900 # behavior of running a script from the system command line, where
1900 # behavior of running a script from the system command line, where
1901 # Python inserts the script's directory into sys.path
1901 # Python inserts the script's directory into sys.path
1902 dname = os.path.dirname(fname)
1902 dname = os.path.dirname(fname)
1903
1903
1904 with prepended_to_syspath(dname):
1904 with prepended_to_syspath(dname):
1905 try:
1905 try:
1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1907 # Work around a bug in Python for Windows. The bug was
1907 # Work around a bug in Python for Windows. The bug was
1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1909 # SVN Python as of March/07. For details, see:
1909 # SVN Python as of March/07. For details, see:
1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1911 try:
1911 try:
1912 globs,locs = where[0:2]
1912 globs,locs = where[0:2]
1913 except:
1913 except:
1914 try:
1914 try:
1915 globs = locs = where[0]
1915 globs = locs = where[0]
1916 except:
1916 except:
1917 globs = locs = globals()
1917 globs = locs = globals()
1918 exec file(fname) in globs,locs
1918 exec file(fname) in globs,locs
1919 else:
1919 else:
1920 execfile(fname,*where)
1920 execfile(fname,*where)
1921 except SyntaxError:
1921 except SyntaxError:
1922 self.showsyntaxerror()
1922 self.showsyntaxerror()
1923 warn('Failure executing file: <%s>' % fname)
1923 warn('Failure executing file: <%s>' % fname)
1924 except SystemExit, status:
1924 except SystemExit, status:
1925 # Code that correctly sets the exit status flag to success (0)
1925 # Code that correctly sets the exit status flag to success (0)
1926 # shouldn't be bothered with a traceback. Note that a plain
1926 # shouldn't be bothered with a traceback. Note that a plain
1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1928 # will still get a traceback. Note that the structure of the
1928 # will still get a traceback. Note that the structure of the
1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1930 # the checks must be done in a version-dependent way.
1930 # the checks must be done in a version-dependent way.
1931 show = False
1931 show = False
1932 if status.args[0]==0 and not kw['exit_ignore']:
1932 if status.args[0]==0 and not kw['exit_ignore']:
1933 show = True
1933 show = True
1934 if show:
1934 if show:
1935 self.showtraceback()
1935 self.showtraceback()
1936 warn('Failure executing file: <%s>' % fname)
1936 warn('Failure executing file: <%s>' % fname)
1937 except:
1937 except:
1938 self.showtraceback()
1938 self.showtraceback()
1939 warn('Failure executing file: <%s>' % fname)
1939 warn('Failure executing file: <%s>' % fname)
1940
1940
1941 def safe_execfile_ipy(self, fname):
1941 def safe_execfile_ipy(self, fname):
1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1943
1943
1944 Parameters
1944 Parameters
1945 ----------
1945 ----------
1946 fname : str
1946 fname : str
1947 The name of the file to execute. The filename must have a
1947 The name of the file to execute. The filename must have a
1948 .ipy extension.
1948 .ipy extension.
1949 """
1949 """
1950 fname = os.path.abspath(os.path.expanduser(fname))
1950 fname = os.path.abspath(os.path.expanduser(fname))
1951
1951
1952 # Make sure we have a .py file
1952 # Make sure we have a .py file
1953 if not fname.endswith('.ipy'):
1953 if not fname.endswith('.ipy'):
1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1955
1955
1956 # Make sure we can open the file
1956 # Make sure we can open the file
1957 try:
1957 try:
1958 with open(fname) as thefile:
1958 with open(fname) as thefile:
1959 pass
1959 pass
1960 except:
1960 except:
1961 warn('Could not open file <%s> for safe execution.' % fname)
1961 warn('Could not open file <%s> for safe execution.' % fname)
1962 return
1962 return
1963
1963
1964 # Find things also in current directory. This is needed to mimic the
1964 # Find things also in current directory. This is needed to mimic the
1965 # behavior of running a script from the system command line, where
1965 # behavior of running a script from the system command line, where
1966 # Python inserts the script's directory into sys.path
1966 # Python inserts the script's directory into sys.path
1967 dname = os.path.dirname(fname)
1967 dname = os.path.dirname(fname)
1968
1968
1969 with prepended_to_syspath(dname):
1969 with prepended_to_syspath(dname):
1970 try:
1970 try:
1971 with open(fname) as thefile:
1971 with open(fname) as thefile:
1972 script = thefile.read()
1972 script = thefile.read()
1973 # self.runlines currently captures all exceptions
1973 # self.runlines currently captures all exceptions
1974 # raise in user code. It would be nice if there were
1974 # raise in user code. It would be nice if there were
1975 # versions of runlines, execfile that did raise, so
1975 # versions of runlines, execfile that did raise, so
1976 # we could catch the errors.
1976 # we could catch the errors.
1977 self.runlines(script, clean=True)
1977 self.runlines(script, clean=True)
1978 except:
1978 except:
1979 self.showtraceback()
1979 self.showtraceback()
1980 warn('Unknown failure executing file: <%s>' % fname)
1980 warn('Unknown failure executing file: <%s>' % fname)
1981
1981
1982 def _is_secondary_block_start(self, s):
1982 def _is_secondary_block_start(self, s):
1983 if not s.endswith(':'):
1983 if not s.endswith(':'):
1984 return False
1984 return False
1985 if (s.startswith('elif') or
1985 if (s.startswith('elif') or
1986 s.startswith('else') or
1986 s.startswith('else') or
1987 s.startswith('except') or
1987 s.startswith('except') or
1988 s.startswith('finally')):
1988 s.startswith('finally')):
1989 return True
1989 return True
1990
1990
1991 def cleanup_ipy_script(self, script):
1991 def cleanup_ipy_script(self, script):
1992 """Make a script safe for self.runlines()
1992 """Make a script safe for self.runlines()
1993
1993
1994 Currently, IPython is lines based, with blocks being detected by
1994 Currently, IPython is lines based, with blocks being detected by
1995 empty lines. This is a problem for block based scripts that may
1995 empty lines. This is a problem for block based scripts that may
1996 not have empty lines after blocks. This script adds those empty
1996 not have empty lines after blocks. This script adds those empty
1997 lines to make scripts safe for running in the current line based
1997 lines to make scripts safe for running in the current line based
1998 IPython.
1998 IPython.
1999 """
1999 """
2000 res = []
2000 res = []
2001 lines = script.splitlines()
2001 lines = script.splitlines()
2002 level = 0
2002 level = 0
2003
2003
2004 for l in lines:
2004 for l in lines:
2005 lstripped = l.lstrip()
2005 lstripped = l.lstrip()
2006 stripped = l.strip()
2006 stripped = l.strip()
2007 if not stripped:
2007 if not stripped:
2008 continue
2008 continue
2009 newlevel = len(l) - len(lstripped)
2009 newlevel = len(l) - len(lstripped)
2010 if level > 0 and newlevel == 0 and \
2010 if level > 0 and newlevel == 0 and \
2011 not self._is_secondary_block_start(stripped):
2011 not self._is_secondary_block_start(stripped):
2012 # add empty line
2012 # add empty line
2013 res.append('')
2013 res.append('')
2014 res.append(l)
2014 res.append(l)
2015 level = newlevel
2015 level = newlevel
2016
2016
2017 return '\n'.join(res) + '\n'
2017 return '\n'.join(res) + '\n'
2018
2018
2019 def runlines(self, lines, clean=False):
2019 def runlines(self, lines, clean=False):
2020 """Run a string of one or more lines of source.
2020 """Run a string of one or more lines of source.
2021
2021
2022 This method is capable of running a string containing multiple source
2022 This method is capable of running a string containing multiple source
2023 lines, as if they had been entered at the IPython prompt. Since it
2023 lines, as if they had been entered at the IPython prompt. Since it
2024 exposes IPython's processing machinery, the given strings can contain
2024 exposes IPython's processing machinery, the given strings can contain
2025 magic calls (%magic), special shell access (!cmd), etc.
2025 magic calls (%magic), special shell access (!cmd), etc.
2026 """
2026 """
2027
2027
2028 if isinstance(lines, (list, tuple)):
2028 if isinstance(lines, (list, tuple)):
2029 lines = '\n'.join(lines)
2029 lines = '\n'.join(lines)
2030
2030
2031 if clean:
2031 if clean:
2032 lines = self.cleanup_ipy_script(lines)
2032 lines = self.cleanup_ipy_script(lines)
2033
2033
2034 # We must start with a clean buffer, in case this is run from an
2034 # We must start with a clean buffer, in case this is run from an
2035 # interactive IPython session (via a magic, for example).
2035 # interactive IPython session (via a magic, for example).
2036 self.resetbuffer()
2036 self.resetbuffer()
2037 lines = lines.splitlines()
2037 lines = lines.splitlines()
2038 more = 0
2038 more = 0
2039
2039
2040 with nested(self.builtin_trap, self.display_trap):
2040 with nested(self.builtin_trap, self.display_trap):
2041 for line in lines:
2041 for line in lines:
2042 # skip blank lines so we don't mess up the prompt counter, but do
2042 # skip blank lines so we don't mess up the prompt counter, but do
2043 # NOT skip even a blank line if we are in a code block (more is
2043 # NOT skip even a blank line if we are in a code block (more is
2044 # true)
2044 # true)
2045
2045
2046 if line or more:
2046 if line or more:
2047 # push to raw history, so hist line numbers stay in sync
2047 # push to raw history, so hist line numbers stay in sync
2048 self.input_hist_raw.append("# " + line + "\n")
2048 self.input_hist_raw.append("# " + line + "\n")
2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2050 more = self.push_line(prefiltered)
2050 more = self.push_line(prefiltered)
2051 # IPython's runsource returns None if there was an error
2051 # IPython's runsource returns None if there was an error
2052 # compiling the code. This allows us to stop processing right
2052 # compiling the code. This allows us to stop processing right
2053 # away, so the user gets the error message at the right place.
2053 # away, so the user gets the error message at the right place.
2054 if more is None:
2054 if more is None:
2055 break
2055 break
2056 else:
2056 else:
2057 self.input_hist_raw.append("\n")
2057 self.input_hist_raw.append("\n")
2058 # final newline in case the input didn't have it, so that the code
2058 # final newline in case the input didn't have it, so that the code
2059 # actually does get executed
2059 # actually does get executed
2060 if more:
2060 if more:
2061 self.push_line('\n')
2061 self.push_line('\n')
2062
2062
2063 def runsource(self, source, filename='<input>', symbol='single'):
2063 def runsource(self, source, filename='<input>', symbol='single'):
2064 """Compile and run some source in the interpreter.
2064 """Compile and run some source in the interpreter.
2065
2065
2066 Arguments are as for compile_command().
2066 Arguments are as for compile_command().
2067
2067
2068 One several things can happen:
2068 One several things can happen:
2069
2069
2070 1) The input is incorrect; compile_command() raised an
2070 1) The input is incorrect; compile_command() raised an
2071 exception (SyntaxError or OverflowError). A syntax traceback
2071 exception (SyntaxError or OverflowError). A syntax traceback
2072 will be printed by calling the showsyntaxerror() method.
2072 will be printed by calling the showsyntaxerror() method.
2073
2073
2074 2) The input is incomplete, and more input is required;
2074 2) The input is incomplete, and more input is required;
2075 compile_command() returned None. Nothing happens.
2075 compile_command() returned None. Nothing happens.
2076
2076
2077 3) The input is complete; compile_command() returned a code
2077 3) The input is complete; compile_command() returned a code
2078 object. The code is executed by calling self.runcode() (which
2078 object. The code is executed by calling self.runcode() (which
2079 also handles run-time exceptions, except for SystemExit).
2079 also handles run-time exceptions, except for SystemExit).
2080
2080
2081 The return value is:
2081 The return value is:
2082
2082
2083 - True in case 2
2083 - True in case 2
2084
2084
2085 - False in the other cases, unless an exception is raised, where
2085 - False in the other cases, unless an exception is raised, where
2086 None is returned instead. This can be used by external callers to
2086 None is returned instead. This can be used by external callers to
2087 know whether to continue feeding input or not.
2087 know whether to continue feeding input or not.
2088
2088
2089 The return value can be used to decide whether to use sys.ps1 or
2089 The return value can be used to decide whether to use sys.ps1 or
2090 sys.ps2 to prompt the next line."""
2090 sys.ps2 to prompt the next line."""
2091
2091
2092 # if the source code has leading blanks, add 'if 1:\n' to it
2092 # if the source code has leading blanks, add 'if 1:\n' to it
2093 # this allows execution of indented pasted code. It is tempting
2093 # this allows execution of indented pasted code. It is tempting
2094 # to add '\n' at the end of source to run commands like ' a=1'
2094 # to add '\n' at the end of source to run commands like ' a=1'
2095 # directly, but this fails for more complicated scenarios
2095 # directly, but this fails for more complicated scenarios
2096 source=source.encode(self.stdin_encoding)
2096 source=source.encode(self.stdin_encoding)
2097 if source[:1] in [' ', '\t']:
2097 if source[:1] in [' ', '\t']:
2098 source = 'if 1:\n%s' % source
2098 source = 'if 1:\n%s' % source
2099
2099
2100 try:
2100 try:
2101 code = self.compile(source,filename,symbol)
2101 code = self.compile(source,filename,symbol)
2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2103 # Case 1
2103 # Case 1
2104 self.showsyntaxerror(filename)
2104 self.showsyntaxerror(filename)
2105 return None
2105 return None
2106
2106
2107 if code is None:
2107 if code is None:
2108 # Case 2
2108 # Case 2
2109 return True
2109 return True
2110
2110
2111 # Case 3
2111 # Case 3
2112 # We store the code object so that threaded shells and
2112 # We store the code object so that threaded shells and
2113 # custom exception handlers can access all this info if needed.
2113 # custom exception handlers can access all this info if needed.
2114 # The source corresponding to this can be obtained from the
2114 # The source corresponding to this can be obtained from the
2115 # buffer attribute as '\n'.join(self.buffer).
2115 # buffer attribute as '\n'.join(self.buffer).
2116 self.code_to_run = code
2116 self.code_to_run = code
2117 # now actually execute the code object
2117 # now actually execute the code object
2118 if self.runcode(code) == 0:
2118 if self.runcode(code) == 0:
2119 return False
2119 return False
2120 else:
2120 else:
2121 return None
2121 return None
2122
2122
2123 def runcode(self,code_obj):
2123 def runcode(self,code_obj):
2124 """Execute a code object.
2124 """Execute a code object.
2125
2125
2126 When an exception occurs, self.showtraceback() is called to display a
2126 When an exception occurs, self.showtraceback() is called to display a
2127 traceback.
2127 traceback.
2128
2128
2129 Return value: a flag indicating whether the code to be run completed
2129 Return value: a flag indicating whether the code to be run completed
2130 successfully:
2130 successfully:
2131
2131
2132 - 0: successful execution.
2132 - 0: successful execution.
2133 - 1: an error occurred.
2133 - 1: an error occurred.
2134 """
2134 """
2135
2135
2136 # Set our own excepthook in case the user code tries to call it
2136 # Set our own excepthook in case the user code tries to call it
2137 # directly, so that the IPython crash handler doesn't get triggered
2137 # directly, so that the IPython crash handler doesn't get triggered
2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2139
2139
2140 # we save the original sys.excepthook in the instance, in case config
2140 # we save the original sys.excepthook in the instance, in case config
2141 # code (such as magics) needs access to it.
2141 # code (such as magics) needs access to it.
2142 self.sys_excepthook = old_excepthook
2142 self.sys_excepthook = old_excepthook
2143 outflag = 1 # happens in more places, so it's easier as default
2143 outflag = 1 # happens in more places, so it's easier as default
2144 try:
2144 try:
2145 try:
2145 try:
2146 self.hooks.pre_runcode_hook()
2146 self.hooks.pre_runcode_hook()
2147 exec code_obj in self.user_global_ns, self.user_ns
2147 exec code_obj in self.user_global_ns, self.user_ns
2148 finally:
2148 finally:
2149 # Reset our crash handler in place
2149 # Reset our crash handler in place
2150 sys.excepthook = old_excepthook
2150 sys.excepthook = old_excepthook
2151 except SystemExit:
2151 except SystemExit:
2152 self.resetbuffer()
2152 self.resetbuffer()
2153 self.showtraceback()
2153 self.showtraceback()
2154 warn("Type %exit or %quit to exit IPython "
2154 warn("Type %exit or %quit to exit IPython "
2155 "(%Exit or %Quit do so unconditionally).",level=1)
2155 "(%Exit or %Quit do so unconditionally).",level=1)
2156 except self.custom_exceptions:
2156 except self.custom_exceptions:
2157 etype,value,tb = sys.exc_info()
2157 etype,value,tb = sys.exc_info()
2158 self.CustomTB(etype,value,tb)
2158 self.CustomTB(etype,value,tb)
2159 except:
2159 except:
2160 self.showtraceback()
2160 self.showtraceback()
2161 else:
2161 else:
2162 outflag = 0
2162 outflag = 0
2163 if softspace(sys.stdout, 0):
2163 if softspace(sys.stdout, 0):
2164 print
2164 print
2165 # Flush out code object which has been run (and source)
2165 # Flush out code object which has been run (and source)
2166 self.code_to_run = None
2166 self.code_to_run = None
2167 return outflag
2167 return outflag
2168
2168
2169 def push_line(self, line):
2169 def push_line(self, line):
2170 """Push a line to the interpreter.
2170 """Push a line to the interpreter.
2171
2171
2172 The line should not have a trailing newline; it may have
2172 The line should not have a trailing newline; it may have
2173 internal newlines. The line is appended to a buffer and the
2173 internal newlines. The line is appended to a buffer and the
2174 interpreter's runsource() method is called with the
2174 interpreter's runsource() method is called with the
2175 concatenated contents of the buffer as source. If this
2175 concatenated contents of the buffer as source. If this
2176 indicates that the command was executed or invalid, the buffer
2176 indicates that the command was executed or invalid, the buffer
2177 is reset; otherwise, the command is incomplete, and the buffer
2177 is reset; otherwise, the command is incomplete, and the buffer
2178 is left as it was after the line was appended. The return
2178 is left as it was after the line was appended. The return
2179 value is 1 if more input is required, 0 if the line was dealt
2179 value is 1 if more input is required, 0 if the line was dealt
2180 with in some way (this is the same as runsource()).
2180 with in some way (this is the same as runsource()).
2181 """
2181 """
2182
2182
2183 # autoindent management should be done here, and not in the
2183 # autoindent management should be done here, and not in the
2184 # interactive loop, since that one is only seen by keyboard input. We
2184 # interactive loop, since that one is only seen by keyboard input. We
2185 # need this done correctly even for code run via runlines (which uses
2185 # need this done correctly even for code run via runlines (which uses
2186 # push).
2186 # push).
2187
2187
2188 #print 'push line: <%s>' % line # dbg
2188 #print 'push line: <%s>' % line # dbg
2189 for subline in line.splitlines():
2189 for subline in line.splitlines():
2190 self._autoindent_update(subline)
2190 self._autoindent_update(subline)
2191 self.buffer.append(line)
2191 self.buffer.append(line)
2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2193 if not more:
2193 if not more:
2194 self.resetbuffer()
2194 self.resetbuffer()
2195 return more
2195 return more
2196
2196
2197 def _autoindent_update(self,line):
2197 def _autoindent_update(self,line):
2198 """Keep track of the indent level."""
2198 """Keep track of the indent level."""
2199
2199
2200 #debugx('line')
2200 #debugx('line')
2201 #debugx('self.indent_current_nsp')
2201 #debugx('self.indent_current_nsp')
2202 if self.autoindent:
2202 if self.autoindent:
2203 if line:
2203 if line:
2204 inisp = num_ini_spaces(line)
2204 inisp = num_ini_spaces(line)
2205 if inisp < self.indent_current_nsp:
2205 if inisp < self.indent_current_nsp:
2206 self.indent_current_nsp = inisp
2206 self.indent_current_nsp = inisp
2207
2207
2208 if line[-1] == ':':
2208 if line[-1] == ':':
2209 self.indent_current_nsp += 4
2209 self.indent_current_nsp += 4
2210 elif dedent_re.match(line):
2210 elif dedent_re.match(line):
2211 self.indent_current_nsp -= 4
2211 self.indent_current_nsp -= 4
2212 else:
2212 else:
2213 self.indent_current_nsp = 0
2213 self.indent_current_nsp = 0
2214
2214
2215 def resetbuffer(self):
2215 def resetbuffer(self):
2216 """Reset the input buffer."""
2216 """Reset the input buffer."""
2217 self.buffer[:] = []
2217 self.buffer[:] = []
2218
2218
2219 def raw_input(self,prompt='',continue_prompt=False):
2219 def raw_input(self,prompt='',continue_prompt=False):
2220 """Write a prompt and read a line.
2220 """Write a prompt and read a line.
2221
2221
2222 The returned line does not include the trailing newline.
2222 The returned line does not include the trailing newline.
2223 When the user enters the EOF key sequence, EOFError is raised.
2223 When the user enters the EOF key sequence, EOFError is raised.
2224
2224
2225 Optional inputs:
2225 Optional inputs:
2226
2226
2227 - prompt(''): a string to be printed to prompt the user.
2227 - prompt(''): a string to be printed to prompt the user.
2228
2228
2229 - continue_prompt(False): whether this line is the first one or a
2229 - continue_prompt(False): whether this line is the first one or a
2230 continuation in a sequence of inputs.
2230 continuation in a sequence of inputs.
2231 """
2231 """
2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2233
2233
2234 # Code run by the user may have modified the readline completer state.
2234 # Code run by the user may have modified the readline completer state.
2235 # We must ensure that our completer is back in place.
2235 # We must ensure that our completer is back in place.
2236
2236
2237 if self.has_readline:
2237 if self.has_readline:
2238 self.set_completer()
2238 self.set_completer()
2239
2239
2240 try:
2240 try:
2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2242 except ValueError:
2242 except ValueError:
2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2244 " or sys.stdout.close()!\nExiting IPython!")
2244 " or sys.stdout.close()!\nExiting IPython!")
2245 self.ask_exit()
2245 self.ask_exit()
2246 return ""
2246 return ""
2247
2247
2248 # Try to be reasonably smart about not re-indenting pasted input more
2248 # Try to be reasonably smart about not re-indenting pasted input more
2249 # than necessary. We do this by trimming out the auto-indent initial
2249 # than necessary. We do this by trimming out the auto-indent initial
2250 # spaces, if the user's actual input started itself with whitespace.
2250 # spaces, if the user's actual input started itself with whitespace.
2251 #debugx('self.buffer[-1]')
2251 #debugx('self.buffer[-1]')
2252
2252
2253 if self.autoindent:
2253 if self.autoindent:
2254 if num_ini_spaces(line) > self.indent_current_nsp:
2254 if num_ini_spaces(line) > self.indent_current_nsp:
2255 line = line[self.indent_current_nsp:]
2255 line = line[self.indent_current_nsp:]
2256 self.indent_current_nsp = 0
2256 self.indent_current_nsp = 0
2257
2257
2258 # store the unfiltered input before the user has any chance to modify
2258 # store the unfiltered input before the user has any chance to modify
2259 # it.
2259 # it.
2260 if line.strip():
2260 if line.strip():
2261 if continue_prompt:
2261 if continue_prompt:
2262 self.input_hist_raw[-1] += '%s\n' % line
2262 self.input_hist_raw[-1] += '%s\n' % line
2263 if self.has_readline and self.readline_use:
2263 if self.has_readline and self.readline_use:
2264 try:
2264 try:
2265 histlen = self.readline.get_current_history_length()
2265 histlen = self.readline.get_current_history_length()
2266 if histlen > 1:
2266 if histlen > 1:
2267 newhist = self.input_hist_raw[-1].rstrip()
2267 newhist = self.input_hist_raw[-1].rstrip()
2268 self.readline.remove_history_item(histlen-1)
2268 self.readline.remove_history_item(histlen-1)
2269 self.readline.replace_history_item(histlen-2,
2269 self.readline.replace_history_item(histlen-2,
2270 newhist.encode(self.stdin_encoding))
2270 newhist.encode(self.stdin_encoding))
2271 except AttributeError:
2271 except AttributeError:
2272 pass # re{move,place}_history_item are new in 2.4.
2272 pass # re{move,place}_history_item are new in 2.4.
2273 else:
2273 else:
2274 self.input_hist_raw.append('%s\n' % line)
2274 self.input_hist_raw.append('%s\n' % line)
2275 # only entries starting at first column go to shadow history
2275 # only entries starting at first column go to shadow history
2276 if line.lstrip() == line:
2276 if line.lstrip() == line:
2277 self.shadowhist.add(line.strip())
2277 self.shadowhist.add(line.strip())
2278 elif not continue_prompt:
2278 elif not continue_prompt:
2279 self.input_hist_raw.append('\n')
2279 self.input_hist_raw.append('\n')
2280 try:
2280 try:
2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2282 except:
2282 except:
2283 # blanket except, in case a user-defined prefilter crashes, so it
2283 # blanket except, in case a user-defined prefilter crashes, so it
2284 # can't take all of ipython with it.
2284 # can't take all of ipython with it.
2285 self.showtraceback()
2285 self.showtraceback()
2286 return ''
2286 return ''
2287 else:
2287 else:
2288 return lineout
2288 return lineout
2289
2289
2290 #-------------------------------------------------------------------------
2290 #-------------------------------------------------------------------------
2291 # Working with components
2291 # Working with components
2292 #-------------------------------------------------------------------------
2292 #-------------------------------------------------------------------------
2293
2293
2294 def get_component(self, name=None, klass=None):
2294 def get_component(self, name=None, klass=None):
2295 """Fetch a component by name and klass in my tree."""
2295 """Fetch a component by name and klass in my tree."""
2296 c = Component.get_instances(root=self, name=name, klass=klass)
2296 c = Component.get_instances(root=self, name=name, klass=klass)
2297 if len(c) == 0:
2297 if len(c) == 0:
2298 return None
2298 return None
2299 if len(c) == 1:
2299 if len(c) == 1:
2300 return c[0]
2300 return c[0]
2301 else:
2301 else:
2302 return c
2302 return c
2303
2303
2304 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2305 # IPython extensions
2305 # IPython extensions
2306 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2307
2307
2308 def load_extension(self, module_str):
2308 def load_extension(self, module_str):
2309 """Load an IPython extension by its module name.
2309 """Load an IPython extension by its module name.
2310
2310
2311 An IPython extension is an importable Python module that has
2311 An IPython extension is an importable Python module that has
2312 a function with the signature::
2312 a function with the signature::
2313
2313
2314 def load_ipython_extension(ipython):
2314 def load_ipython_extension(ipython):
2315 # Do things with ipython
2315 # Do things with ipython
2316
2316
2317 This function is called after your extension is imported and the
2317 This function is called after your extension is imported and the
2318 currently active :class:`InteractiveShell` instance is passed as
2318 currently active :class:`InteractiveShell` instance is passed as
2319 the only argument. You can do anything you want with IPython at
2319 the only argument. You can do anything you want with IPython at
2320 that point, including defining new magic and aliases, adding new
2320 that point, including defining new magic and aliases, adding new
2321 components, etc.
2321 components, etc.
2322
2322
2323 The :func:`load_ipython_extension` will be called again is you
2323 The :func:`load_ipython_extension` will be called again is you
2324 load or reload the extension again. It is up to the extension
2324 load or reload the extension again. It is up to the extension
2325 author to add code to manage that.
2325 author to add code to manage that.
2326
2326
2327 You can put your extension modules anywhere you want, as long as
2327 You can put your extension modules anywhere you want, as long as
2328 they can be imported by Python's standard import mechanism. However,
2328 they can be imported by Python's standard import mechanism. However,
2329 to make it easy to write extensions, you can also put your extensions
2329 to make it easy to write extensions, you can also put your extensions
2330 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2330 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2331 is added to ``sys.path`` automatically.
2331 is added to ``sys.path`` automatically.
2332 """
2332 """
2333 from IPython.utils.syspathcontext import prepended_to_syspath
2333 from IPython.utils.syspathcontext import prepended_to_syspath
2334
2334
2335 if module_str not in sys.modules:
2335 if module_str not in sys.modules:
2336 with prepended_to_syspath(self.ipython_extension_dir):
2336 with prepended_to_syspath(self.ipython_extension_dir):
2337 __import__(module_str)
2337 __import__(module_str)
2338 mod = sys.modules[module_str]
2338 mod = sys.modules[module_str]
2339 self._call_load_ipython_extension(mod)
2339 self._call_load_ipython_extension(mod)
2340
2340
2341 def unload_extension(self, module_str):
2341 def unload_extension(self, module_str):
2342 """Unload an IPython extension by its module name.
2342 """Unload an IPython extension by its module name.
2343
2343
2344 This function looks up the extension's name in ``sys.modules`` and
2344 This function looks up the extension's name in ``sys.modules`` and
2345 simply calls ``mod.unload_ipython_extension(self)``.
2345 simply calls ``mod.unload_ipython_extension(self)``.
2346 """
2346 """
2347 if module_str in sys.modules:
2347 if module_str in sys.modules:
2348 mod = sys.modules[module_str]
2348 mod = sys.modules[module_str]
2349 self._call_unload_ipython_extension(mod)
2349 self._call_unload_ipython_extension(mod)
2350
2350
2351 def reload_extension(self, module_str):
2351 def reload_extension(self, module_str):
2352 """Reload an IPython extension by calling reload.
2352 """Reload an IPython extension by calling reload.
2353
2353
2354 If the module has not been loaded before,
2354 If the module has not been loaded before,
2355 :meth:`InteractiveShell.load_extension` is called. Otherwise
2355 :meth:`InteractiveShell.load_extension` is called. Otherwise
2356 :func:`reload` is called and then the :func:`load_ipython_extension`
2356 :func:`reload` is called and then the :func:`load_ipython_extension`
2357 function of the module, if it exists is called.
2357 function of the module, if it exists is called.
2358 """
2358 """
2359 from IPython.utils.syspathcontext import prepended_to_syspath
2359 from IPython.utils.syspathcontext import prepended_to_syspath
2360
2360
2361 with prepended_to_syspath(self.ipython_extension_dir):
2361 with prepended_to_syspath(self.ipython_extension_dir):
2362 if module_str in sys.modules:
2362 if module_str in sys.modules:
2363 mod = sys.modules[module_str]
2363 mod = sys.modules[module_str]
2364 reload(mod)
2364 reload(mod)
2365 self._call_load_ipython_extension(mod)
2365 self._call_load_ipython_extension(mod)
2366 else:
2366 else:
2367 self.load_extension(module_str)
2367 self.load_extension(module_str)
2368
2368
2369 def _call_load_ipython_extension(self, mod):
2369 def _call_load_ipython_extension(self, mod):
2370 if hasattr(mod, 'load_ipython_extension'):
2370 if hasattr(mod, 'load_ipython_extension'):
2371 mod.load_ipython_extension(self)
2371 mod.load_ipython_extension(self)
2372
2372
2373 def _call_unload_ipython_extension(self, mod):
2373 def _call_unload_ipython_extension(self, mod):
2374 if hasattr(mod, 'unload_ipython_extension'):
2374 if hasattr(mod, 'unload_ipython_extension'):
2375 mod.unload_ipython_extension(self)
2375 mod.unload_ipython_extension(self)
2376
2376
2377 #-------------------------------------------------------------------------
2377 #-------------------------------------------------------------------------
2378 # Things related to the prefilter
2378 # Things related to the prefilter
2379 #-------------------------------------------------------------------------
2379 #-------------------------------------------------------------------------
2380
2380
2381 def init_prefilter(self):
2381 def init_prefilter(self):
2382 self.prefilter_manager = PrefilterManager(self, config=self.config)
2382 self.prefilter_manager = PrefilterManager(self, config=self.config)
2383
2383
2384 #-------------------------------------------------------------------------
2384 #-------------------------------------------------------------------------
2385 # Utilities
2385 # Utilities
2386 #-------------------------------------------------------------------------
2386 #-------------------------------------------------------------------------
2387
2387
2388 def getoutput(self, cmd):
2388 def getoutput(self, cmd):
2389 return getoutput(self.var_expand(cmd,depth=2),
2389 return getoutput(self.var_expand(cmd,depth=2),
2390 header=self.system_header,
2390 header=self.system_header,
2391 verbose=self.system_verbose)
2391 verbose=self.system_verbose)
2392
2392
2393 def getoutputerror(self, cmd):
2393 def getoutputerror(self, cmd):
2394 return getoutputerror(self.var_expand(cmd,depth=2),
2394 return getoutputerror(self.var_expand(cmd,depth=2),
2395 header=self.system_header,
2395 header=self.system_header,
2396 verbose=self.system_verbose)
2396 verbose=self.system_verbose)
2397
2397
2398 def var_expand(self,cmd,depth=0):
2398 def var_expand(self,cmd,depth=0):
2399 """Expand python variables in a string.
2399 """Expand python variables in a string.
2400
2400
2401 The depth argument indicates how many frames above the caller should
2401 The depth argument indicates how many frames above the caller should
2402 be walked to look for the local namespace where to expand variables.
2402 be walked to look for the local namespace where to expand variables.
2403
2403
2404 The global namespace for expansion is always the user's interactive
2404 The global namespace for expansion is always the user's interactive
2405 namespace.
2405 namespace.
2406 """
2406 """
2407
2407
2408 return str(ItplNS(cmd,
2408 return str(ItplNS(cmd,
2409 self.user_ns, # globals
2409 self.user_ns, # globals
2410 # Skip our own frame in searching for locals:
2410 # Skip our own frame in searching for locals:
2411 sys._getframe(depth+1).f_locals # locals
2411 sys._getframe(depth+1).f_locals # locals
2412 ))
2412 ))
2413
2413
2414 def mktempfile(self,data=None):
2414 def mktempfile(self,data=None):
2415 """Make a new tempfile and return its filename.
2415 """Make a new tempfile and return its filename.
2416
2416
2417 This makes a call to tempfile.mktemp, but it registers the created
2417 This makes a call to tempfile.mktemp, but it registers the created
2418 filename internally so ipython cleans it up at exit time.
2418 filename internally so ipython cleans it up at exit time.
2419
2419
2420 Optional inputs:
2420 Optional inputs:
2421
2421
2422 - data(None): if data is given, it gets written out to the temp file
2422 - data(None): if data is given, it gets written out to the temp file
2423 immediately, and the file is closed again."""
2423 immediately, and the file is closed again."""
2424
2424
2425 filename = tempfile.mktemp('.py','ipython_edit_')
2425 filename = tempfile.mktemp('.py','ipython_edit_')
2426 self.tempfiles.append(filename)
2426 self.tempfiles.append(filename)
2427
2427
2428 if data:
2428 if data:
2429 tmp_file = open(filename,'w')
2429 tmp_file = open(filename,'w')
2430 tmp_file.write(data)
2430 tmp_file.write(data)
2431 tmp_file.close()
2431 tmp_file.close()
2432 return filename
2432 return filename
2433
2433
2434 def write(self,data):
2434 def write(self,data):
2435 """Write a string to the default output"""
2435 """Write a string to the default output"""
2436 Term.cout.write(data)
2436 Term.cout.write(data)
2437
2437
2438 def write_err(self,data):
2438 def write_err(self,data):
2439 """Write a string to the default error output"""
2439 """Write a string to the default error output"""
2440 Term.cerr.write(data)
2440 Term.cerr.write(data)
2441
2441
2442 def ask_yes_no(self,prompt,default=True):
2442 def ask_yes_no(self,prompt,default=True):
2443 if self.quiet:
2443 if self.quiet:
2444 return True
2444 return True
2445 return ask_yes_no(prompt,default)
2445 return ask_yes_no(prompt,default)
2446
2446
2447 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2448 # Things related to IPython exiting
2448 # Things related to IPython exiting
2449 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2450
2450
2451 def ask_exit(self):
2451 def ask_exit(self):
2452 """ Call for exiting. Can be overiden and used as a callback. """
2452 """ Call for exiting. Can be overiden and used as a callback. """
2453 self.exit_now = True
2453 self.exit_now = True
2454
2454
2455 def exit(self):
2455 def exit(self):
2456 """Handle interactive exit.
2456 """Handle interactive exit.
2457
2457
2458 This method calls the ask_exit callback."""
2458 This method calls the ask_exit callback."""
2459 if self.confirm_exit:
2459 if self.confirm_exit:
2460 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2460 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2461 self.ask_exit()
2461 self.ask_exit()
2462 else:
2462 else:
2463 self.ask_exit()
2463 self.ask_exit()
2464
2464
2465 def atexit_operations(self):
2465 def atexit_operations(self):
2466 """This will be executed at the time of exit.
2466 """This will be executed at the time of exit.
2467
2467
2468 Saving of persistent data should be performed here.
2468 Saving of persistent data should be performed here.
2469 """
2469 """
2470 self.savehist()
2470 self.savehist()
2471
2471
2472 # Cleanup all tempfiles left around
2472 # Cleanup all tempfiles left around
2473 for tfile in self.tempfiles:
2473 for tfile in self.tempfiles:
2474 try:
2474 try:
2475 os.unlink(tfile)
2475 os.unlink(tfile)
2476 except OSError:
2476 except OSError:
2477 pass
2477 pass
2478
2478
2479 # Clear all user namespaces to release all references cleanly.
2479 # Clear all user namespaces to release all references cleanly.
2480 self.reset()
2480 self.reset()
2481
2481
2482 # Run user hooks
2482 # Run user hooks
2483 self.hooks.shutdown_hook()
2483 self.hooks.shutdown_hook()
2484
2484
2485 def cleanup(self):
2485 def cleanup(self):
2486 self.restore_sys_module_state()
2486 self.restore_sys_module_state()
2487
2487
2488
2488
@@ -1,3608 +1,3580 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #*****************************************************************************
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 #****************************************************************************
14 # Modules and globals
14 # Modules and globals
15
15
16 # Python standard modules
16 # Python standard modules
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 import inspect
19 import inspect
20 import os
20 import os
21 import pdb
21 import pdb
22 import pydoc
22 import pydoc
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import tempfile
26 import tempfile
27 import time
27 import time
28 import cPickle as pickle
28 import cPickle as pickle
29 import textwrap
29 import textwrap
30 from cStringIO import StringIO
30 from cStringIO import StringIO
31 from getopt import getopt,GetoptError
31 from getopt import getopt,GetoptError
32 from pprint import pprint, pformat
32 from pprint import pprint, pformat
33
33
34 # cProfile was added in Python2.5
34 # cProfile was added in Python2.5
35 try:
35 try:
36 import cProfile as profile
36 import cProfile as profile
37 import pstats
37 import pstats
38 except ImportError:
38 except ImportError:
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 import IPython
46 import IPython
47 from IPython.utils import wildcard
47 from IPython.utils import wildcard
48 from IPython.core import debugger, oinspect
48 from IPython.core import debugger, oinspect
49 from IPython.core.error import TryNext
49 from IPython.core.error import TryNext
50 from IPython.core.fakemodule import FakeModule
50 from IPython.core.fakemodule import FakeModule
51 from IPython.core.prefilter import ESC_MAGIC
51 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
52 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
53 from IPython.utils.PyColorize import Parser
53 from IPython.utils.PyColorize import Parser
54 from IPython.utils.ipstruct import Struct
54 from IPython.utils.ipstruct import Struct
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
57 from IPython.core.page import page
57 from IPython.core.page import page
58 from IPython.utils import platutils
58 from IPython.utils import platutils
59 import IPython.utils.generics
59 import IPython.utils.generics
60 from IPython.core.error import UsageError
60 from IPython.core.error import UsageError
61 from IPython.testing import decorators as testdec
61 from IPython.testing import decorators as testdec
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Utility functions
64 # Utility functions
65 def on_off(tag):
65 def on_off(tag):
66 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
66 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
67 return ['OFF','ON'][tag]
67 return ['OFF','ON'][tag]
68
68
69 class Bunch: pass
69 class Bunch: pass
70
70
71 def compress_dhist(dh):
71 def compress_dhist(dh):
72 head, tail = dh[:-10], dh[-10:]
72 head, tail = dh[:-10], dh[-10:]
73
73
74 newhead = []
74 newhead = []
75 done = set()
75 done = set()
76 for h in head:
76 for h in head:
77 if h in done:
77 if h in done:
78 continue
78 continue
79 newhead.append(h)
79 newhead.append(h)
80 done.add(h)
80 done.add(h)
81
81
82 return newhead + tail
82 return newhead + tail
83
83
84
84
85 #***************************************************************************
85 #***************************************************************************
86 # Main class implementing Magic functionality
86 # Main class implementing Magic functionality
87 class Magic:
87 class Magic:
88 """Magic functions for InteractiveShell.
88 """Magic functions for InteractiveShell.
89
89
90 Shell functions which can be reached as %function_name. All magic
90 Shell functions which can be reached as %function_name. All magic
91 functions should accept a string, which they can parse for their own
91 functions should accept a string, which they can parse for their own
92 needs. This can make some functions easier to type, eg `%cd ../`
92 needs. This can make some functions easier to type, eg `%cd ../`
93 vs. `%cd("../")`
93 vs. `%cd("../")`
94
94
95 ALL definitions MUST begin with the prefix magic_. The user won't need it
95 ALL definitions MUST begin with the prefix magic_. The user won't need it
96 at the command line, but it is is needed in the definition. """
96 at the command line, but it is is needed in the definition. """
97
97
98 # class globals
98 # class globals
99 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
99 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
100 'Automagic is ON, % prefix NOT needed for magic functions.']
100 'Automagic is ON, % prefix NOT needed for magic functions.']
101
101
102 #......................................................................
102 #......................................................................
103 # some utility functions
103 # some utility functions
104
104
105 def __init__(self,shell):
105 def __init__(self,shell):
106
106
107 self.options_table = {}
107 self.options_table = {}
108 if profile is None:
108 if profile is None:
109 self.magic_prun = self.profile_missing_notice
109 self.magic_prun = self.profile_missing_notice
110 self.shell = shell
110 self.shell = shell
111
111
112 # namespace for holding state we may need
112 # namespace for holding state we may need
113 self._magic_state = Bunch()
113 self._magic_state = Bunch()
114
114
115 def profile_missing_notice(self, *args, **kwargs):
115 def profile_missing_notice(self, *args, **kwargs):
116 error("""\
116 error("""\
117 The profile module could not be found. It has been removed from the standard
117 The profile module could not be found. It has been removed from the standard
118 python packages because of its non-free license. To use profiling, install the
118 python packages because of its non-free license. To use profiling, install the
119 python-profiler package from non-free.""")
119 python-profiler package from non-free.""")
120
120
121 def default_option(self,fn,optstr):
121 def default_option(self,fn,optstr):
122 """Make an entry in the options_table for fn, with value optstr"""
122 """Make an entry in the options_table for fn, with value optstr"""
123
123
124 if fn not in self.lsmagic():
124 if fn not in self.lsmagic():
125 error("%s is not a magic function" % fn)
125 error("%s is not a magic function" % fn)
126 self.options_table[fn] = optstr
126 self.options_table[fn] = optstr
127
127
128 def lsmagic(self):
128 def lsmagic(self):
129 """Return a list of currently available magic functions.
129 """Return a list of currently available magic functions.
130
130
131 Gives a list of the bare names after mangling (['ls','cd', ...], not
131 Gives a list of the bare names after mangling (['ls','cd', ...], not
132 ['magic_ls','magic_cd',...]"""
132 ['magic_ls','magic_cd',...]"""
133
133
134 # FIXME. This needs a cleanup, in the way the magics list is built.
134 # FIXME. This needs a cleanup, in the way the magics list is built.
135
135
136 # magics in class definition
136 # magics in class definition
137 class_magic = lambda fn: fn.startswith('magic_') and \
137 class_magic = lambda fn: fn.startswith('magic_') and \
138 callable(Magic.__dict__[fn])
138 callable(Magic.__dict__[fn])
139 # in instance namespace (run-time user additions)
139 # in instance namespace (run-time user additions)
140 inst_magic = lambda fn: fn.startswith('magic_') and \
140 inst_magic = lambda fn: fn.startswith('magic_') and \
141 callable(self.__dict__[fn])
141 callable(self.__dict__[fn])
142 # and bound magics by user (so they can access self):
142 # and bound magics by user (so they can access self):
143 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
143 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
144 callable(self.__class__.__dict__[fn])
144 callable(self.__class__.__dict__[fn])
145 magics = filter(class_magic,Magic.__dict__.keys()) + \
145 magics = filter(class_magic,Magic.__dict__.keys()) + \
146 filter(inst_magic,self.__dict__.keys()) + \
146 filter(inst_magic,self.__dict__.keys()) + \
147 filter(inst_bound_magic,self.__class__.__dict__.keys())
147 filter(inst_bound_magic,self.__class__.__dict__.keys())
148 out = []
148 out = []
149 for fn in set(magics):
149 for fn in set(magics):
150 out.append(fn.replace('magic_','',1))
150 out.append(fn.replace('magic_','',1))
151 out.sort()
151 out.sort()
152 return out
152 return out
153
153
154 def extract_input_slices(self,slices,raw=False):
154 def extract_input_slices(self,slices,raw=False):
155 """Return as a string a set of input history slices.
155 """Return as a string a set of input history slices.
156
156
157 Inputs:
157 Inputs:
158
158
159 - slices: the set of slices is given as a list of strings (like
159 - slices: the set of slices is given as a list of strings (like
160 ['1','4:8','9'], since this function is for use by magic functions
160 ['1','4:8','9'], since this function is for use by magic functions
161 which get their arguments as strings.
161 which get their arguments as strings.
162
162
163 Optional inputs:
163 Optional inputs:
164
164
165 - raw(False): by default, the processed input is used. If this is
165 - raw(False): by default, the processed input is used. If this is
166 true, the raw input history is used instead.
166 true, the raw input history is used instead.
167
167
168 Note that slices can be called with two notations:
168 Note that slices can be called with two notations:
169
169
170 N:M -> standard python form, means including items N...(M-1).
170 N:M -> standard python form, means including items N...(M-1).
171
171
172 N-M -> include items N..M (closed endpoint)."""
172 N-M -> include items N..M (closed endpoint)."""
173
173
174 if raw:
174 if raw:
175 hist = self.shell.input_hist_raw
175 hist = self.shell.input_hist_raw
176 else:
176 else:
177 hist = self.shell.input_hist
177 hist = self.shell.input_hist
178
178
179 cmds = []
179 cmds = []
180 for chunk in slices:
180 for chunk in slices:
181 if ':' in chunk:
181 if ':' in chunk:
182 ini,fin = map(int,chunk.split(':'))
182 ini,fin = map(int,chunk.split(':'))
183 elif '-' in chunk:
183 elif '-' in chunk:
184 ini,fin = map(int,chunk.split('-'))
184 ini,fin = map(int,chunk.split('-'))
185 fin += 1
185 fin += 1
186 else:
186 else:
187 ini = int(chunk)
187 ini = int(chunk)
188 fin = ini+1
188 fin = ini+1
189 cmds.append(hist[ini:fin])
189 cmds.append(hist[ini:fin])
190 return cmds
190 return cmds
191
191
192 def _ofind(self, oname, namespaces=None):
192 def _ofind(self, oname, namespaces=None):
193 """Find an object in the available namespaces.
193 """Find an object in the available namespaces.
194
194
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
195 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
196
196
197 Has special code to detect magic functions.
197 Has special code to detect magic functions.
198 """
198 """
199
199
200 oname = oname.strip()
200 oname = oname.strip()
201
201
202 alias_ns = None
202 alias_ns = None
203 if namespaces is None:
203 if namespaces is None:
204 # Namespaces to search in:
204 # Namespaces to search in:
205 # Put them in a list. The order is important so that we
205 # Put them in a list. The order is important so that we
206 # find things in the same order that Python finds them.
206 # find things in the same order that Python finds them.
207 namespaces = [ ('Interactive', self.shell.user_ns),
207 namespaces = [ ('Interactive', self.shell.user_ns),
208 ('IPython internal', self.shell.internal_ns),
208 ('IPython internal', self.shell.internal_ns),
209 ('Python builtin', __builtin__.__dict__),
209 ('Python builtin', __builtin__.__dict__),
210 ('Alias', self.shell.alias_manager.alias_table),
210 ('Alias', self.shell.alias_manager.alias_table),
211 ]
211 ]
212 alias_ns = self.shell.alias_manager.alias_table
212 alias_ns = self.shell.alias_manager.alias_table
213
213
214 # initialize results to 'null'
214 # initialize results to 'null'
215 found = 0; obj = None; ospace = None; ds = None;
215 found = 0; obj = None; ospace = None; ds = None;
216 ismagic = 0; isalias = 0; parent = None
216 ismagic = 0; isalias = 0; parent = None
217
217
218 # Look for the given name by splitting it in parts. If the head is
218 # Look for the given name by splitting it in parts. If the head is
219 # found, then we look for all the remaining parts as members, and only
219 # found, then we look for all the remaining parts as members, and only
220 # declare success if we can find them all.
220 # declare success if we can find them all.
221 oname_parts = oname.split('.')
221 oname_parts = oname.split('.')
222 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
222 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
223 for nsname,ns in namespaces:
223 for nsname,ns in namespaces:
224 try:
224 try:
225 obj = ns[oname_head]
225 obj = ns[oname_head]
226 except KeyError:
226 except KeyError:
227 continue
227 continue
228 else:
228 else:
229 #print 'oname_rest:', oname_rest # dbg
229 #print 'oname_rest:', oname_rest # dbg
230 for part in oname_rest:
230 for part in oname_rest:
231 try:
231 try:
232 parent = obj
232 parent = obj
233 obj = getattr(obj,part)
233 obj = getattr(obj,part)
234 except:
234 except:
235 # Blanket except b/c some badly implemented objects
235 # Blanket except b/c some badly implemented objects
236 # allow __getattr__ to raise exceptions other than
236 # allow __getattr__ to raise exceptions other than
237 # AttributeError, which then crashes IPython.
237 # AttributeError, which then crashes IPython.
238 break
238 break
239 else:
239 else:
240 # If we finish the for loop (no break), we got all members
240 # If we finish the for loop (no break), we got all members
241 found = 1
241 found = 1
242 ospace = nsname
242 ospace = nsname
243 if ns == alias_ns:
243 if ns == alias_ns:
244 isalias = 1
244 isalias = 1
245 break # namespace loop
245 break # namespace loop
246
246
247 # Try to see if it's magic
247 # Try to see if it's magic
248 if not found:
248 if not found:
249 if oname.startswith(ESC_MAGIC):
249 if oname.startswith(ESC_MAGIC):
250 oname = oname[1:]
250 oname = oname[1:]
251 obj = getattr(self,'magic_'+oname,None)
251 obj = getattr(self,'magic_'+oname,None)
252 if obj is not None:
252 if obj is not None:
253 found = 1
253 found = 1
254 ospace = 'IPython internal'
254 ospace = 'IPython internal'
255 ismagic = 1
255 ismagic = 1
256
256
257 # Last try: special-case some literals like '', [], {}, etc:
257 # Last try: special-case some literals like '', [], {}, etc:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
258 if not found and oname_head in ["''",'""','[]','{}','()']:
259 obj = eval(oname_head)
259 obj = eval(oname_head)
260 found = 1
260 found = 1
261 ospace = 'Interactive'
261 ospace = 'Interactive'
262
262
263 return {'found':found, 'obj':obj, 'namespace':ospace,
263 return {'found':found, 'obj':obj, 'namespace':ospace,
264 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
264 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
265
265
266 def arg_err(self,func):
266 def arg_err(self,func):
267 """Print docstring if incorrect arguments were passed"""
267 """Print docstring if incorrect arguments were passed"""
268 print 'Error in arguments:'
268 print 'Error in arguments:'
269 print OInspect.getdoc(func)
269 print OInspect.getdoc(func)
270
270
271 def format_latex(self,strng):
271 def format_latex(self,strng):
272 """Format a string for latex inclusion."""
272 """Format a string for latex inclusion."""
273
273
274 # Characters that need to be escaped for latex:
274 # Characters that need to be escaped for latex:
275 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
275 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
276 # Magic command names as headers:
276 # Magic command names as headers:
277 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
277 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
278 re.MULTILINE)
278 re.MULTILINE)
279 # Magic commands
279 # Magic commands
280 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
280 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
281 re.MULTILINE)
281 re.MULTILINE)
282 # Paragraph continue
282 # Paragraph continue
283 par_re = re.compile(r'\\$',re.MULTILINE)
283 par_re = re.compile(r'\\$',re.MULTILINE)
284
284
285 # The "\n" symbol
285 # The "\n" symbol
286 newline_re = re.compile(r'\\n')
286 newline_re = re.compile(r'\\n')
287
287
288 # Now build the string for output:
288 # Now build the string for output:
289 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
289 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
290 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
290 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
291 strng)
291 strng)
292 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
292 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
293 strng = par_re.sub(r'\\\\',strng)
293 strng = par_re.sub(r'\\\\',strng)
294 strng = escape_re.sub(r'\\\1',strng)
294 strng = escape_re.sub(r'\\\1',strng)
295 strng = newline_re.sub(r'\\textbackslash{}n',strng)
295 strng = newline_re.sub(r'\\textbackslash{}n',strng)
296 return strng
296 return strng
297
297
298 def format_screen(self,strng):
298 def format_screen(self,strng):
299 """Format a string for screen printing.
299 """Format a string for screen printing.
300
300
301 This removes some latex-type format codes."""
301 This removes some latex-type format codes."""
302 # Paragraph continue
302 # Paragraph continue
303 par_re = re.compile(r'\\$',re.MULTILINE)
303 par_re = re.compile(r'\\$',re.MULTILINE)
304 strng = par_re.sub('',strng)
304 strng = par_re.sub('',strng)
305 return strng
305 return strng
306
306
307 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
307 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
308 """Parse options passed to an argument string.
308 """Parse options passed to an argument string.
309
309
310 The interface is similar to that of getopt(), but it returns back a
310 The interface is similar to that of getopt(), but it returns back a
311 Struct with the options as keys and the stripped argument string still
311 Struct with the options as keys and the stripped argument string still
312 as a string.
312 as a string.
313
313
314 arg_str is quoted as a true sys.argv vector by using shlex.split.
314 arg_str is quoted as a true sys.argv vector by using shlex.split.
315 This allows us to easily expand variables, glob files, quote
315 This allows us to easily expand variables, glob files, quote
316 arguments, etc.
316 arguments, etc.
317
317
318 Options:
318 Options:
319 -mode: default 'string'. If given as 'list', the argument string is
319 -mode: default 'string'. If given as 'list', the argument string is
320 returned as a list (split on whitespace) instead of a string.
320 returned as a list (split on whitespace) instead of a string.
321
321
322 -list_all: put all option values in lists. Normally only options
322 -list_all: put all option values in lists. Normally only options
323 appearing more than once are put in a list.
323 appearing more than once are put in a list.
324
324
325 -posix (True): whether to split the input line in POSIX mode or not,
325 -posix (True): whether to split the input line in POSIX mode or not,
326 as per the conventions outlined in the shlex module from the
326 as per the conventions outlined in the shlex module from the
327 standard library."""
327 standard library."""
328
328
329 # inject default options at the beginning of the input line
329 # inject default options at the beginning of the input line
330 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
330 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
331 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
331 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
332
332
333 mode = kw.get('mode','string')
333 mode = kw.get('mode','string')
334 if mode not in ['string','list']:
334 if mode not in ['string','list']:
335 raise ValueError,'incorrect mode given: %s' % mode
335 raise ValueError,'incorrect mode given: %s' % mode
336 # Get options
336 # Get options
337 list_all = kw.get('list_all',0)
337 list_all = kw.get('list_all',0)
338 posix = kw.get('posix',True)
338 posix = kw.get('posix',True)
339
339
340 # Check if we have more than one argument to warrant extra processing:
340 # Check if we have more than one argument to warrant extra processing:
341 odict = {} # Dictionary with options
341 odict = {} # Dictionary with options
342 args = arg_str.split()
342 args = arg_str.split()
343 if len(args) >= 1:
343 if len(args) >= 1:
344 # If the list of inputs only has 0 or 1 thing in it, there's no
344 # If the list of inputs only has 0 or 1 thing in it, there's no
345 # need to look for options
345 # need to look for options
346 argv = arg_split(arg_str,posix)
346 argv = arg_split(arg_str,posix)
347 # Do regular option processing
347 # Do regular option processing
348 try:
348 try:
349 opts,args = getopt(argv,opt_str,*long_opts)
349 opts,args = getopt(argv,opt_str,*long_opts)
350 except GetoptError,e:
350 except GetoptError,e:
351 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
351 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
352 " ".join(long_opts)))
352 " ".join(long_opts)))
353 for o,a in opts:
353 for o,a in opts:
354 if o.startswith('--'):
354 if o.startswith('--'):
355 o = o[2:]
355 o = o[2:]
356 else:
356 else:
357 o = o[1:]
357 o = o[1:]
358 try:
358 try:
359 odict[o].append(a)
359 odict[o].append(a)
360 except AttributeError:
360 except AttributeError:
361 odict[o] = [odict[o],a]
361 odict[o] = [odict[o],a]
362 except KeyError:
362 except KeyError:
363 if list_all:
363 if list_all:
364 odict[o] = [a]
364 odict[o] = [a]
365 else:
365 else:
366 odict[o] = a
366 odict[o] = a
367
367
368 # Prepare opts,args for return
368 # Prepare opts,args for return
369 opts = Struct(odict)
369 opts = Struct(odict)
370 if mode == 'string':
370 if mode == 'string':
371 args = ' '.join(args)
371 args = ' '.join(args)
372
372
373 return opts,args
373 return opts,args
374
374
375 #......................................................................
375 #......................................................................
376 # And now the actual magic functions
376 # And now the actual magic functions
377
377
378 # Functions for IPython shell work (vars,funcs, config, etc)
378 # Functions for IPython shell work (vars,funcs, config, etc)
379 def magic_lsmagic(self, parameter_s = ''):
379 def magic_lsmagic(self, parameter_s = ''):
380 """List currently available magic functions."""
380 """List currently available magic functions."""
381 mesc = ESC_MAGIC
381 mesc = ESC_MAGIC
382 print 'Available magic functions:\n'+mesc+\
382 print 'Available magic functions:\n'+mesc+\
383 (' '+mesc).join(self.lsmagic())
383 (' '+mesc).join(self.lsmagic())
384 print '\n' + Magic.auto_status[self.shell.automagic]
384 print '\n' + Magic.auto_status[self.shell.automagic]
385 return None
385 return None
386
386
387 def magic_magic(self, parameter_s = ''):
387 def magic_magic(self, parameter_s = ''):
388 """Print information about the magic function system.
388 """Print information about the magic function system.
389
389
390 Supported formats: -latex, -brief, -rest
390 Supported formats: -latex, -brief, -rest
391 """
391 """
392
392
393 mode = ''
393 mode = ''
394 try:
394 try:
395 if parameter_s.split()[0] == '-latex':
395 if parameter_s.split()[0] == '-latex':
396 mode = 'latex'
396 mode = 'latex'
397 if parameter_s.split()[0] == '-brief':
397 if parameter_s.split()[0] == '-brief':
398 mode = 'brief'
398 mode = 'brief'
399 if parameter_s.split()[0] == '-rest':
399 if parameter_s.split()[0] == '-rest':
400 mode = 'rest'
400 mode = 'rest'
401 rest_docs = []
401 rest_docs = []
402 except:
402 except:
403 pass
403 pass
404
404
405 magic_docs = []
405 magic_docs = []
406 for fname in self.lsmagic():
406 for fname in self.lsmagic():
407 mname = 'magic_' + fname
407 mname = 'magic_' + fname
408 for space in (Magic,self,self.__class__):
408 for space in (Magic,self,self.__class__):
409 try:
409 try:
410 fn = space.__dict__[mname]
410 fn = space.__dict__[mname]
411 except KeyError:
411 except KeyError:
412 pass
412 pass
413 else:
413 else:
414 break
414 break
415 if mode == 'brief':
415 if mode == 'brief':
416 # only first line
416 # only first line
417 if fn.__doc__:
417 if fn.__doc__:
418 fndoc = fn.__doc__.split('\n',1)[0]
418 fndoc = fn.__doc__.split('\n',1)[0]
419 else:
419 else:
420 fndoc = 'No documentation'
420 fndoc = 'No documentation'
421 else:
421 else:
422 if fn.__doc__:
422 if fn.__doc__:
423 fndoc = fn.__doc__.rstrip()
423 fndoc = fn.__doc__.rstrip()
424 else:
424 else:
425 fndoc = 'No documentation'
425 fndoc = 'No documentation'
426
426
427
427
428 if mode == 'rest':
428 if mode == 'rest':
429 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
429 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
430 fname,fndoc))
430 fname,fndoc))
431
431
432 else:
432 else:
433 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
433 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
434 fname,fndoc))
434 fname,fndoc))
435
435
436 magic_docs = ''.join(magic_docs)
436 magic_docs = ''.join(magic_docs)
437
437
438 if mode == 'rest':
438 if mode == 'rest':
439 return "".join(rest_docs)
439 return "".join(rest_docs)
440
440
441 if mode == 'latex':
441 if mode == 'latex':
442 print self.format_latex(magic_docs)
442 print self.format_latex(magic_docs)
443 return
443 return
444 else:
444 else:
445 magic_docs = self.format_screen(magic_docs)
445 magic_docs = self.format_screen(magic_docs)
446 if mode == 'brief':
446 if mode == 'brief':
447 return magic_docs
447 return magic_docs
448
448
449 outmsg = """
449 outmsg = """
450 IPython's 'magic' functions
450 IPython's 'magic' functions
451 ===========================
451 ===========================
452
452
453 The magic function system provides a series of functions which allow you to
453 The magic function system provides a series of functions which allow you to
454 control the behavior of IPython itself, plus a lot of system-type
454 control the behavior of IPython itself, plus a lot of system-type
455 features. All these functions are prefixed with a % character, but parameters
455 features. All these functions are prefixed with a % character, but parameters
456 are given without parentheses or quotes.
456 are given without parentheses or quotes.
457
457
458 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 NOTE: If you have 'automagic' enabled (via the command line option or with the
459 %automagic function), you don't need to type in the % explicitly. By default,
459 %automagic function), you don't need to type in the % explicitly. By default,
460 IPython ships with automagic on, so you should only rarely need the % escape.
460 IPython ships with automagic on, so you should only rarely need the % escape.
461
461
462 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 Example: typing '%cd mydir' (without the quotes) changes you working directory
463 to 'mydir', if it exists.
463 to 'mydir', if it exists.
464
464
465 You can define your own magic functions to extend the system. See the supplied
465 You can define your own magic functions to extend the system. See the supplied
466 ipythonrc and example-magic.py files for details (in your ipython
466 ipythonrc and example-magic.py files for details (in your ipython
467 configuration directory, typically $HOME/.ipython/).
467 configuration directory, typically $HOME/.ipython/).
468
468
469 You can also define your own aliased names for magic functions. In your
469 You can also define your own aliased names for magic functions. In your
470 ipythonrc file, placing a line like:
470 ipythonrc file, placing a line like:
471
471
472 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
473
473
474 will define %pf as a new name for %profile.
474 will define %pf as a new name for %profile.
475
475
476 You can also call magics in code using the magic() function, which IPython
476 You can also call magics in code using the magic() function, which IPython
477 automatically adds to the builtin namespace. Type 'magic?' for details.
477 automatically adds to the builtin namespace. Type 'magic?' for details.
478
478
479 For a list of the available magic functions, use %lsmagic. For a description
479 For a list of the available magic functions, use %lsmagic. For a description
480 of any of them, type %magic_name?, e.g. '%cd?'.
480 of any of them, type %magic_name?, e.g. '%cd?'.
481
481
482 Currently the magic system has the following functions:\n"""
482 Currently the magic system has the following functions:\n"""
483
483
484 mesc = ESC_MAGIC
484 mesc = ESC_MAGIC
485 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
486 "\n\n%s%s\n\n%s" % (outmsg,
486 "\n\n%s%s\n\n%s" % (outmsg,
487 magic_docs,mesc,mesc,
487 magic_docs,mesc,mesc,
488 (' '+mesc).join(self.lsmagic()),
488 (' '+mesc).join(self.lsmagic()),
489 Magic.auto_status[self.shell.automagic] ) )
489 Magic.auto_status[self.shell.automagic] ) )
490
490
491 page(outmsg,screen_lines=self.shell.usable_screen_length)
491 page(outmsg,screen_lines=self.shell.usable_screen_length)
492
492
493
493
494 def magic_autoindent(self, parameter_s = ''):
494 def magic_autoindent(self, parameter_s = ''):
495 """Toggle autoindent on/off (if available)."""
495 """Toggle autoindent on/off (if available)."""
496
496
497 self.shell.set_autoindent()
497 self.shell.set_autoindent()
498 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
499
499
500
500
501 def magic_automagic(self, parameter_s = ''):
501 def magic_automagic(self, parameter_s = ''):
502 """Make magic functions callable without having to type the initial %.
502 """Make magic functions callable without having to type the initial %.
503
503
504 Without argumentsl toggles on/off (when off, you must call it as
504 Without argumentsl toggles on/off (when off, you must call it as
505 %automagic, of course). With arguments it sets the value, and you can
505 %automagic, of course). With arguments it sets the value, and you can
506 use any of (case insensitive):
506 use any of (case insensitive):
507
507
508 - on,1,True: to activate
508 - on,1,True: to activate
509
509
510 - off,0,False: to deactivate.
510 - off,0,False: to deactivate.
511
511
512 Note that magic functions have lowest priority, so if there's a
512 Note that magic functions have lowest priority, so if there's a
513 variable whose name collides with that of a magic fn, automagic won't
513 variable whose name collides with that of a magic fn, automagic won't
514 work for that function (you get the variable instead). However, if you
514 work for that function (you get the variable instead). However, if you
515 delete the variable (del var), the previously shadowed magic function
515 delete the variable (del var), the previously shadowed magic function
516 becomes visible to automagic again."""
516 becomes visible to automagic again."""
517
517
518 arg = parameter_s.lower()
518 arg = parameter_s.lower()
519 if parameter_s in ('on','1','true'):
519 if parameter_s in ('on','1','true'):
520 self.shell.automagic = True
520 self.shell.automagic = True
521 elif parameter_s in ('off','0','false'):
521 elif parameter_s in ('off','0','false'):
522 self.shell.automagic = False
522 self.shell.automagic = False
523 else:
523 else:
524 self.shell.automagic = not self.shell.automagic
524 self.shell.automagic = not self.shell.automagic
525 print '\n' + Magic.auto_status[self.shell.automagic]
525 print '\n' + Magic.auto_status[self.shell.automagic]
526
526
527 @testdec.skip_doctest
527 @testdec.skip_doctest
528 def magic_autocall(self, parameter_s = ''):
528 def magic_autocall(self, parameter_s = ''):
529 """Make functions callable without having to type parentheses.
529 """Make functions callable without having to type parentheses.
530
530
531 Usage:
531 Usage:
532
532
533 %autocall [mode]
533 %autocall [mode]
534
534
535 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
536 value is toggled on and off (remembering the previous state).
536 value is toggled on and off (remembering the previous state).
537
537
538 In more detail, these values mean:
538 In more detail, these values mean:
539
539
540 0 -> fully disabled
540 0 -> fully disabled
541
541
542 1 -> active, but do not apply if there are no arguments on the line.
542 1 -> active, but do not apply if there are no arguments on the line.
543
543
544 In this mode, you get:
544 In this mode, you get:
545
545
546 In [1]: callable
546 In [1]: callable
547 Out[1]: <built-in function callable>
547 Out[1]: <built-in function callable>
548
548
549 In [2]: callable 'hello'
549 In [2]: callable 'hello'
550 ------> callable('hello')
550 ------> callable('hello')
551 Out[2]: False
551 Out[2]: False
552
552
553 2 -> Active always. Even if no arguments are present, the callable
553 2 -> Active always. Even if no arguments are present, the callable
554 object is called:
554 object is called:
555
555
556 In [2]: float
556 In [2]: float
557 ------> float()
557 ------> float()
558 Out[2]: 0.0
558 Out[2]: 0.0
559
559
560 Note that even with autocall off, you can still use '/' at the start of
560 Note that even with autocall off, you can still use '/' at the start of
561 a line to treat the first argument on the command line as a function
561 a line to treat the first argument on the command line as a function
562 and add parentheses to it:
562 and add parentheses to it:
563
563
564 In [8]: /str 43
564 In [8]: /str 43
565 ------> str(43)
565 ------> str(43)
566 Out[8]: '43'
566 Out[8]: '43'
567
567
568 # all-random (note for auto-testing)
568 # all-random (note for auto-testing)
569 """
569 """
570
570
571 if parameter_s:
571 if parameter_s:
572 arg = int(parameter_s)
572 arg = int(parameter_s)
573 else:
573 else:
574 arg = 'toggle'
574 arg = 'toggle'
575
575
576 if not arg in (0,1,2,'toggle'):
576 if not arg in (0,1,2,'toggle'):
577 error('Valid modes: (0->Off, 1->Smart, 2->Full')
577 error('Valid modes: (0->Off, 1->Smart, 2->Full')
578 return
578 return
579
579
580 if arg in (0,1,2):
580 if arg in (0,1,2):
581 self.shell.autocall = arg
581 self.shell.autocall = arg
582 else: # toggle
582 else: # toggle
583 if self.shell.autocall:
583 if self.shell.autocall:
584 self._magic_state.autocall_save = self.shell.autocall
584 self._magic_state.autocall_save = self.shell.autocall
585 self.shell.autocall = 0
585 self.shell.autocall = 0
586 else:
586 else:
587 try:
587 try:
588 self.shell.autocall = self._magic_state.autocall_save
588 self.shell.autocall = self._magic_state.autocall_save
589 except AttributeError:
589 except AttributeError:
590 self.shell.autocall = self._magic_state.autocall_save = 1
590 self.shell.autocall = self._magic_state.autocall_save = 1
591
591
592 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
592 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
593
593
594 def magic_system_verbose(self, parameter_s = ''):
594 def magic_system_verbose(self, parameter_s = ''):
595 """Set verbose printing of system calls.
595 """Set verbose printing of system calls.
596
596
597 If called without an argument, act as a toggle"""
597 If called without an argument, act as a toggle"""
598
598
599 if parameter_s:
599 if parameter_s:
600 val = bool(eval(parameter_s))
600 val = bool(eval(parameter_s))
601 else:
601 else:
602 val = None
602 val = None
603
603
604 if self.shell.system_verbose:
604 if self.shell.system_verbose:
605 self.shell.system_verbose = False
605 self.shell.system_verbose = False
606 else:
606 else:
607 self.shell.system_verbose = True
607 self.shell.system_verbose = True
608 print "System verbose printing is:",\
608 print "System verbose printing is:",\
609 ['OFF','ON'][self.shell.system_verbose]
609 ['OFF','ON'][self.shell.system_verbose]
610
610
611
611
612 def magic_page(self, parameter_s=''):
612 def magic_page(self, parameter_s=''):
613 """Pretty print the object and display it through a pager.
613 """Pretty print the object and display it through a pager.
614
614
615 %page [options] OBJECT
615 %page [options] OBJECT
616
616
617 If no object is given, use _ (last output).
617 If no object is given, use _ (last output).
618
618
619 Options:
619 Options:
620
620
621 -r: page str(object), don't pretty-print it."""
621 -r: page str(object), don't pretty-print it."""
622
622
623 # After a function contributed by Olivier Aubert, slightly modified.
623 # After a function contributed by Olivier Aubert, slightly modified.
624
624
625 # Process options/args
625 # Process options/args
626 opts,args = self.parse_options(parameter_s,'r')
626 opts,args = self.parse_options(parameter_s,'r')
627 raw = 'r' in opts
627 raw = 'r' in opts
628
628
629 oname = args and args or '_'
629 oname = args and args or '_'
630 info = self._ofind(oname)
630 info = self._ofind(oname)
631 if info['found']:
631 if info['found']:
632 txt = (raw and str or pformat)( info['obj'] )
632 txt = (raw and str or pformat)( info['obj'] )
633 page(txt)
633 page(txt)
634 else:
634 else:
635 print 'Object `%s` not found' % oname
635 print 'Object `%s` not found' % oname
636
636
637 def magic_profile(self, parameter_s=''):
637 def magic_profile(self, parameter_s=''):
638 """Print your currently active IPyhton profile."""
638 """Print your currently active IPyhton profile."""
639 if self.shell.profile:
639 if self.shell.profile:
640 printpl('Current IPython profile: $self.shell.profile.')
640 printpl('Current IPython profile: $self.shell.profile.')
641 else:
641 else:
642 print 'No profile active.'
642 print 'No profile active.'
643
643
644 def magic_pinfo(self, parameter_s='', namespaces=None):
644 def magic_pinfo(self, parameter_s='', namespaces=None):
645 """Provide detailed information about an object.
645 """Provide detailed information about an object.
646
646
647 '%pinfo object' is just a synonym for object? or ?object."""
647 '%pinfo object' is just a synonym for object? or ?object."""
648
648
649 #print 'pinfo par: <%s>' % parameter_s # dbg
649 #print 'pinfo par: <%s>' % parameter_s # dbg
650
650
651
651
652 # detail_level: 0 -> obj? , 1 -> obj??
652 # detail_level: 0 -> obj? , 1 -> obj??
653 detail_level = 0
653 detail_level = 0
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
655 # happen if the user types 'pinfo foo?' at the cmd line.
655 # happen if the user types 'pinfo foo?' at the cmd line.
656 pinfo,qmark1,oname,qmark2 = \
656 pinfo,qmark1,oname,qmark2 = \
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
658 if pinfo or qmark1 or qmark2:
658 if pinfo or qmark1 or qmark2:
659 detail_level = 1
659 detail_level = 1
660 if "*" in oname:
660 if "*" in oname:
661 self.magic_psearch(oname)
661 self.magic_psearch(oname)
662 else:
662 else:
663 self._inspect('pinfo', oname, detail_level=detail_level,
663 self._inspect('pinfo', oname, detail_level=detail_level,
664 namespaces=namespaces)
664 namespaces=namespaces)
665
665
666 def magic_pdef(self, parameter_s='', namespaces=None):
666 def magic_pdef(self, parameter_s='', namespaces=None):
667 """Print the definition header for any callable object.
667 """Print the definition header for any callable object.
668
668
669 If the object is a class, print the constructor information."""
669 If the object is a class, print the constructor information."""
670 self._inspect('pdef',parameter_s, namespaces)
670 self._inspect('pdef',parameter_s, namespaces)
671
671
672 def magic_pdoc(self, parameter_s='', namespaces=None):
672 def magic_pdoc(self, parameter_s='', namespaces=None):
673 """Print the docstring for an object.
673 """Print the docstring for an object.
674
674
675 If the given object is a class, it will print both the class and the
675 If the given object is a class, it will print both the class and the
676 constructor docstrings."""
676 constructor docstrings."""
677 self._inspect('pdoc',parameter_s, namespaces)
677 self._inspect('pdoc',parameter_s, namespaces)
678
678
679 def magic_psource(self, parameter_s='', namespaces=None):
679 def magic_psource(self, parameter_s='', namespaces=None):
680 """Print (or run through pager) the source code for an object."""
680 """Print (or run through pager) the source code for an object."""
681 self._inspect('psource',parameter_s, namespaces)
681 self._inspect('psource',parameter_s, namespaces)
682
682
683 def magic_pfile(self, parameter_s=''):
683 def magic_pfile(self, parameter_s=''):
684 """Print (or run through pager) the file where an object is defined.
684 """Print (or run through pager) the file where an object is defined.
685
685
686 The file opens at the line where the object definition begins. IPython
686 The file opens at the line where the object definition begins. IPython
687 will honor the environment variable PAGER if set, and otherwise will
687 will honor the environment variable PAGER if set, and otherwise will
688 do its best to print the file in a convenient form.
688 do its best to print the file in a convenient form.
689
689
690 If the given argument is not an object currently defined, IPython will
690 If the given argument is not an object currently defined, IPython will
691 try to interpret it as a filename (automatically adding a .py extension
691 try to interpret it as a filename (automatically adding a .py extension
692 if needed). You can thus use %pfile as a syntax highlighting code
692 if needed). You can thus use %pfile as a syntax highlighting code
693 viewer."""
693 viewer."""
694
694
695 # first interpret argument as an object name
695 # first interpret argument as an object name
696 out = self._inspect('pfile',parameter_s)
696 out = self._inspect('pfile',parameter_s)
697 # if not, try the input as a filename
697 # if not, try the input as a filename
698 if out == 'not found':
698 if out == 'not found':
699 try:
699 try:
700 filename = get_py_filename(parameter_s)
700 filename = get_py_filename(parameter_s)
701 except IOError,msg:
701 except IOError,msg:
702 print msg
702 print msg
703 return
703 return
704 page(self.shell.inspector.format(file(filename).read()))
704 page(self.shell.inspector.format(file(filename).read()))
705
705
706 def _inspect(self,meth,oname,namespaces=None,**kw):
706 def _inspect(self,meth,oname,namespaces=None,**kw):
707 """Generic interface to the inspector system.
707 """Generic interface to the inspector system.
708
708
709 This function is meant to be called by pdef, pdoc & friends."""
709 This function is meant to be called by pdef, pdoc & friends."""
710
710
711 #oname = oname.strip()
711 #oname = oname.strip()
712 #print '1- oname: <%r>' % oname # dbg
712 #print '1- oname: <%r>' % oname # dbg
713 try:
713 try:
714 oname = oname.strip().encode('ascii')
714 oname = oname.strip().encode('ascii')
715 #print '2- oname: <%r>' % oname # dbg
715 #print '2- oname: <%r>' % oname # dbg
716 except UnicodeEncodeError:
716 except UnicodeEncodeError:
717 print 'Python identifiers can only contain ascii characters.'
717 print 'Python identifiers can only contain ascii characters.'
718 return 'not found'
718 return 'not found'
719
719
720 info = Struct(self._ofind(oname, namespaces))
720 info = Struct(self._ofind(oname, namespaces))
721
721
722 if info.found:
722 if info.found:
723 try:
723 try:
724 IPython.utils.generics.inspect_object(info.obj)
724 IPython.utils.generics.inspect_object(info.obj)
725 return
725 return
726 except TryNext:
726 except TryNext:
727 pass
727 pass
728 # Get the docstring of the class property if it exists.
728 # Get the docstring of the class property if it exists.
729 path = oname.split('.')
729 path = oname.split('.')
730 root = '.'.join(path[:-1])
730 root = '.'.join(path[:-1])
731 if info.parent is not None:
731 if info.parent is not None:
732 try:
732 try:
733 target = getattr(info.parent, '__class__')
733 target = getattr(info.parent, '__class__')
734 # The object belongs to a class instance.
734 # The object belongs to a class instance.
735 try:
735 try:
736 target = getattr(target, path[-1])
736 target = getattr(target, path[-1])
737 # The class defines the object.
737 # The class defines the object.
738 if isinstance(target, property):
738 if isinstance(target, property):
739 oname = root + '.__class__.' + path[-1]
739 oname = root + '.__class__.' + path[-1]
740 info = Struct(self._ofind(oname))
740 info = Struct(self._ofind(oname))
741 except AttributeError: pass
741 except AttributeError: pass
742 except AttributeError: pass
742 except AttributeError: pass
743
743
744 pmethod = getattr(self.shell.inspector,meth)
744 pmethod = getattr(self.shell.inspector,meth)
745 formatter = info.ismagic and self.format_screen or None
745 formatter = info.ismagic and self.format_screen or None
746 if meth == 'pdoc':
746 if meth == 'pdoc':
747 pmethod(info.obj,oname,formatter)
747 pmethod(info.obj,oname,formatter)
748 elif meth == 'pinfo':
748 elif meth == 'pinfo':
749 pmethod(info.obj,oname,formatter,info,**kw)
749 pmethod(info.obj,oname,formatter,info,**kw)
750 else:
750 else:
751 pmethod(info.obj,oname)
751 pmethod(info.obj,oname)
752 else:
752 else:
753 print 'Object `%s` not found.' % oname
753 print 'Object `%s` not found.' % oname
754 return 'not found' # so callers can take other action
754 return 'not found' # so callers can take other action
755
755
756 def magic_psearch(self, parameter_s=''):
756 def magic_psearch(self, parameter_s=''):
757 """Search for object in namespaces by wildcard.
757 """Search for object in namespaces by wildcard.
758
758
759 %psearch [options] PATTERN [OBJECT TYPE]
759 %psearch [options] PATTERN [OBJECT TYPE]
760
760
761 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 Note: ? can be used as a synonym for %psearch, at the beginning or at
762 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
763 rest of the command line must be unchanged (options come first), so
763 rest of the command line must be unchanged (options come first), so
764 for example the following forms are equivalent
764 for example the following forms are equivalent
765
765
766 %psearch -i a* function
766 %psearch -i a* function
767 -i a* function?
767 -i a* function?
768 ?-i a* function
768 ?-i a* function
769
769
770 Arguments:
770 Arguments:
771
771
772 PATTERN
772 PATTERN
773
773
774 where PATTERN is a string containing * as a wildcard similar to its
774 where PATTERN is a string containing * as a wildcard similar to its
775 use in a shell. The pattern is matched in all namespaces on the
775 use in a shell. The pattern is matched in all namespaces on the
776 search path. By default objects starting with a single _ are not
776 search path. By default objects starting with a single _ are not
777 matched, many IPython generated objects have a single
777 matched, many IPython generated objects have a single
778 underscore. The default is case insensitive matching. Matching is
778 underscore. The default is case insensitive matching. Matching is
779 also done on the attributes of objects and not only on the objects
779 also done on the attributes of objects and not only on the objects
780 in a module.
780 in a module.
781
781
782 [OBJECT TYPE]
782 [OBJECT TYPE]
783
783
784 Is the name of a python type from the types module. The name is
784 Is the name of a python type from the types module. The name is
785 given in lowercase without the ending type, ex. StringType is
785 given in lowercase without the ending type, ex. StringType is
786 written string. By adding a type here only objects matching the
786 written string. By adding a type here only objects matching the
787 given type are matched. Using all here makes the pattern match all
787 given type are matched. Using all here makes the pattern match all
788 types (this is the default).
788 types (this is the default).
789
789
790 Options:
790 Options:
791
791
792 -a: makes the pattern match even objects whose names start with a
792 -a: makes the pattern match even objects whose names start with a
793 single underscore. These names are normally ommitted from the
793 single underscore. These names are normally ommitted from the
794 search.
794 search.
795
795
796 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 -i/-c: make the pattern case insensitive/sensitive. If neither of
797 these options is given, the default is read from your ipythonrc
797 these options is given, the default is read from your ipythonrc
798 file. The option name which sets this value is
798 file. The option name which sets this value is
799 'wildcards_case_sensitive'. If this option is not specified in your
799 'wildcards_case_sensitive'. If this option is not specified in your
800 ipythonrc file, IPython's internal default is to do a case sensitive
800 ipythonrc file, IPython's internal default is to do a case sensitive
801 search.
801 search.
802
802
803 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
804 specifiy can be searched in any of the following namespaces:
804 specifiy can be searched in any of the following namespaces:
805 'builtin', 'user', 'user_global','internal', 'alias', where
805 'builtin', 'user', 'user_global','internal', 'alias', where
806 'builtin' and 'user' are the search defaults. Note that you should
806 'builtin' and 'user' are the search defaults. Note that you should
807 not use quotes when specifying namespaces.
807 not use quotes when specifying namespaces.
808
808
809 'Builtin' contains the python module builtin, 'user' contains all
809 'Builtin' contains the python module builtin, 'user' contains all
810 user data, 'alias' only contain the shell aliases and no python
810 user data, 'alias' only contain the shell aliases and no python
811 objects, 'internal' contains objects used by IPython. The
811 objects, 'internal' contains objects used by IPython. The
812 'user_global' namespace is only used by embedded IPython instances,
812 'user_global' namespace is only used by embedded IPython instances,
813 and it contains module-level globals. You can add namespaces to the
813 and it contains module-level globals. You can add namespaces to the
814 search with -s or exclude them with -e (these options can be given
814 search with -s or exclude them with -e (these options can be given
815 more than once).
815 more than once).
816
816
817 Examples:
817 Examples:
818
818
819 %psearch a* -> objects beginning with an a
819 %psearch a* -> objects beginning with an a
820 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
821 %psearch a* function -> all functions beginning with an a
821 %psearch a* function -> all functions beginning with an a
822 %psearch re.e* -> objects beginning with an e in module re
822 %psearch re.e* -> objects beginning with an e in module re
823 %psearch r*.e* -> objects that start with e in modules starting in r
823 %psearch r*.e* -> objects that start with e in modules starting in r
824 %psearch r*.* string -> all strings in modules beginning with r
824 %psearch r*.* string -> all strings in modules beginning with r
825
825
826 Case sensitve search:
826 Case sensitve search:
827
827
828 %psearch -c a* list all object beginning with lower case a
828 %psearch -c a* list all object beginning with lower case a
829
829
830 Show objects beginning with a single _:
830 Show objects beginning with a single _:
831
831
832 %psearch -a _* list objects beginning with a single underscore"""
832 %psearch -a _* list objects beginning with a single underscore"""
833 try:
833 try:
834 parameter_s = parameter_s.encode('ascii')
834 parameter_s = parameter_s.encode('ascii')
835 except UnicodeEncodeError:
835 except UnicodeEncodeError:
836 print 'Python identifiers can only contain ascii characters.'
836 print 'Python identifiers can only contain ascii characters.'
837 return
837 return
838
838
839 # default namespaces to be searched
839 # default namespaces to be searched
840 def_search = ['user','builtin']
840 def_search = ['user','builtin']
841
841
842 # Process options/args
842 # Process options/args
843 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
844 opt = opts.get
844 opt = opts.get
845 shell = self.shell
845 shell = self.shell
846 psearch = shell.inspector.psearch
846 psearch = shell.inspector.psearch
847
847
848 # select case options
848 # select case options
849 if opts.has_key('i'):
849 if opts.has_key('i'):
850 ignore_case = True
850 ignore_case = True
851 elif opts.has_key('c'):
851 elif opts.has_key('c'):
852 ignore_case = False
852 ignore_case = False
853 else:
853 else:
854 ignore_case = not shell.wildcards_case_sensitive
854 ignore_case = not shell.wildcards_case_sensitive
855
855
856 # Build list of namespaces to search from user options
856 # Build list of namespaces to search from user options
857 def_search.extend(opt('s',[]))
857 def_search.extend(opt('s',[]))
858 ns_exclude = ns_exclude=opt('e',[])
858 ns_exclude = ns_exclude=opt('e',[])
859 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859 ns_search = [nm for nm in def_search if nm not in ns_exclude]
860
860
861 # Call the actual search
861 # Call the actual search
862 try:
862 try:
863 psearch(args,shell.ns_table,ns_search,
863 psearch(args,shell.ns_table,ns_search,
864 show_all=opt('a'),ignore_case=ignore_case)
864 show_all=opt('a'),ignore_case=ignore_case)
865 except:
865 except:
866 shell.showtraceback()
866 shell.showtraceback()
867
867
868 def magic_who_ls(self, parameter_s=''):
868 def magic_who_ls(self, parameter_s=''):
869 """Return a sorted list of all interactive variables.
869 """Return a sorted list of all interactive variables.
870
870
871 If arguments are given, only variables of types matching these
871 If arguments are given, only variables of types matching these
872 arguments are returned."""
872 arguments are returned."""
873
873
874 user_ns = self.shell.user_ns
874 user_ns = self.shell.user_ns
875 internal_ns = self.shell.internal_ns
875 internal_ns = self.shell.internal_ns
876 user_config_ns = self.shell.user_config_ns
876 user_config_ns = self.shell.user_config_ns
877 out = []
877 out = []
878 typelist = parameter_s.split()
878 typelist = parameter_s.split()
879
879
880 for i in user_ns:
880 for i in user_ns:
881 if not (i.startswith('_') or i.startswith('_i')) \
881 if not (i.startswith('_') or i.startswith('_i')) \
882 and not (i in internal_ns or i in user_config_ns):
882 and not (i in internal_ns or i in user_config_ns):
883 if typelist:
883 if typelist:
884 if type(user_ns[i]).__name__ in typelist:
884 if type(user_ns[i]).__name__ in typelist:
885 out.append(i)
885 out.append(i)
886 else:
886 else:
887 out.append(i)
887 out.append(i)
888 out.sort()
888 out.sort()
889 return out
889 return out
890
890
891 def magic_who(self, parameter_s=''):
891 def magic_who(self, parameter_s=''):
892 """Print all interactive variables, with some minimal formatting.
892 """Print all interactive variables, with some minimal formatting.
893
893
894 If any arguments are given, only variables whose type matches one of
894 If any arguments are given, only variables whose type matches one of
895 these are printed. For example:
895 these are printed. For example:
896
896
897 %who function str
897 %who function str
898
898
899 will only list functions and strings, excluding all other types of
899 will only list functions and strings, excluding all other types of
900 variables. To find the proper type names, simply use type(var) at a
900 variables. To find the proper type names, simply use type(var) at a
901 command line to see how python prints type names. For example:
901 command line to see how python prints type names. For example:
902
902
903 In [1]: type('hello')\\
903 In [1]: type('hello')\\
904 Out[1]: <type 'str'>
904 Out[1]: <type 'str'>
905
905
906 indicates that the type name for strings is 'str'.
906 indicates that the type name for strings is 'str'.
907
907
908 %who always excludes executed names loaded through your configuration
908 %who always excludes executed names loaded through your configuration
909 file and things which are internal to IPython.
909 file and things which are internal to IPython.
910
910
911 This is deliberate, as typically you may load many modules and the
911 This is deliberate, as typically you may load many modules and the
912 purpose of %who is to show you only what you've manually defined."""
912 purpose of %who is to show you only what you've manually defined."""
913
913
914 varlist = self.magic_who_ls(parameter_s)
914 varlist = self.magic_who_ls(parameter_s)
915 if not varlist:
915 if not varlist:
916 if parameter_s:
916 if parameter_s:
917 print 'No variables match your requested type.'
917 print 'No variables match your requested type.'
918 else:
918 else:
919 print 'Interactive namespace is empty.'
919 print 'Interactive namespace is empty.'
920 return
920 return
921
921
922 # if we have variables, move on...
922 # if we have variables, move on...
923 count = 0
923 count = 0
924 for i in varlist:
924 for i in varlist:
925 print i+'\t',
925 print i+'\t',
926 count += 1
926 count += 1
927 if count > 8:
927 if count > 8:
928 count = 0
928 count = 0
929 print
929 print
930 print
930 print
931
931
932 def magic_whos(self, parameter_s=''):
932 def magic_whos(self, parameter_s=''):
933 """Like %who, but gives some extra information about each variable.
933 """Like %who, but gives some extra information about each variable.
934
934
935 The same type filtering of %who can be applied here.
935 The same type filtering of %who can be applied here.
936
936
937 For all variables, the type is printed. Additionally it prints:
937 For all variables, the type is printed. Additionally it prints:
938
938
939 - For {},[],(): their length.
939 - For {},[],(): their length.
940
940
941 - For numpy and Numeric arrays, a summary with shape, number of
941 - For numpy and Numeric arrays, a summary with shape, number of
942 elements, typecode and size in memory.
942 elements, typecode and size in memory.
943
943
944 - Everything else: a string representation, snipping their middle if
944 - Everything else: a string representation, snipping their middle if
945 too long."""
945 too long."""
946
946
947 varnames = self.magic_who_ls(parameter_s)
947 varnames = self.magic_who_ls(parameter_s)
948 if not varnames:
948 if not varnames:
949 if parameter_s:
949 if parameter_s:
950 print 'No variables match your requested type.'
950 print 'No variables match your requested type.'
951 else:
951 else:
952 print 'Interactive namespace is empty.'
952 print 'Interactive namespace is empty.'
953 return
953 return
954
954
955 # if we have variables, move on...
955 # if we have variables, move on...
956
956
957 # for these types, show len() instead of data:
957 # for these types, show len() instead of data:
958 seq_types = [types.DictType,types.ListType,types.TupleType]
958 seq_types = [types.DictType,types.ListType,types.TupleType]
959
959
960 # for numpy/Numeric arrays, display summary info
960 # for numpy/Numeric arrays, display summary info
961 try:
961 try:
962 import numpy
962 import numpy
963 except ImportError:
963 except ImportError:
964 ndarray_type = None
964 ndarray_type = None
965 else:
965 else:
966 ndarray_type = numpy.ndarray.__name__
966 ndarray_type = numpy.ndarray.__name__
967 try:
967 try:
968 import Numeric
968 import Numeric
969 except ImportError:
969 except ImportError:
970 array_type = None
970 array_type = None
971 else:
971 else:
972 array_type = Numeric.ArrayType.__name__
972 array_type = Numeric.ArrayType.__name__
973
973
974 # Find all variable names and types so we can figure out column sizes
974 # Find all variable names and types so we can figure out column sizes
975 def get_vars(i):
975 def get_vars(i):
976 return self.shell.user_ns[i]
976 return self.shell.user_ns[i]
977
977
978 # some types are well known and can be shorter
978 # some types are well known and can be shorter
979 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
979 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
980 def type_name(v):
980 def type_name(v):
981 tn = type(v).__name__
981 tn = type(v).__name__
982 return abbrevs.get(tn,tn)
982 return abbrevs.get(tn,tn)
983
983
984 varlist = map(get_vars,varnames)
984 varlist = map(get_vars,varnames)
985
985
986 typelist = []
986 typelist = []
987 for vv in varlist:
987 for vv in varlist:
988 tt = type_name(vv)
988 tt = type_name(vv)
989
989
990 if tt=='instance':
990 if tt=='instance':
991 typelist.append( abbrevs.get(str(vv.__class__),
991 typelist.append( abbrevs.get(str(vv.__class__),
992 str(vv.__class__)))
992 str(vv.__class__)))
993 else:
993 else:
994 typelist.append(tt)
994 typelist.append(tt)
995
995
996 # column labels and # of spaces as separator
996 # column labels and # of spaces as separator
997 varlabel = 'Variable'
997 varlabel = 'Variable'
998 typelabel = 'Type'
998 typelabel = 'Type'
999 datalabel = 'Data/Info'
999 datalabel = 'Data/Info'
1000 colsep = 3
1000 colsep = 3
1001 # variable format strings
1001 # variable format strings
1002 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1003 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1004 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 aformat = "%s: %s elems, type `%s`, %s bytes"
1005 # find the size of the columns to format the output nicely
1005 # find the size of the columns to format the output nicely
1006 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1007 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1008 # table header
1008 # table header
1009 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1010 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1011 # and the table itself
1011 # and the table itself
1012 kb = 1024
1012 kb = 1024
1013 Mb = 1048576 # kb**2
1013 Mb = 1048576 # kb**2
1014 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 for vname,var,vtype in zip(varnames,varlist,typelist):
1015 print itpl(vformat),
1015 print itpl(vformat),
1016 if vtype in seq_types:
1016 if vtype in seq_types:
1017 print len(var)
1017 print len(var)
1018 elif vtype in [array_type,ndarray_type]:
1018 elif vtype in [array_type,ndarray_type]:
1019 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1020 if vtype==ndarray_type:
1020 if vtype==ndarray_type:
1021 # numpy
1021 # numpy
1022 vsize = var.size
1022 vsize = var.size
1023 vbytes = vsize*var.itemsize
1023 vbytes = vsize*var.itemsize
1024 vdtype = var.dtype
1024 vdtype = var.dtype
1025 else:
1025 else:
1026 # Numeric
1026 # Numeric
1027 vsize = Numeric.size(var)
1027 vsize = Numeric.size(var)
1028 vbytes = vsize*var.itemsize()
1028 vbytes = vsize*var.itemsize()
1029 vdtype = var.typecode()
1029 vdtype = var.typecode()
1030
1030
1031 if vbytes < 100000:
1031 if vbytes < 100000:
1032 print aformat % (vshape,vsize,vdtype,vbytes)
1032 print aformat % (vshape,vsize,vdtype,vbytes)
1033 else:
1033 else:
1034 print aformat % (vshape,vsize,vdtype,vbytes),
1034 print aformat % (vshape,vsize,vdtype,vbytes),
1035 if vbytes < Mb:
1035 if vbytes < Mb:
1036 print '(%s kb)' % (vbytes/kb,)
1036 print '(%s kb)' % (vbytes/kb,)
1037 else:
1037 else:
1038 print '(%s Mb)' % (vbytes/Mb,)
1038 print '(%s Mb)' % (vbytes/Mb,)
1039 else:
1039 else:
1040 try:
1040 try:
1041 vstr = str(var)
1041 vstr = str(var)
1042 except UnicodeEncodeError:
1042 except UnicodeEncodeError:
1043 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 vstr = unicode(var).encode(sys.getdefaultencoding(),
1044 'backslashreplace')
1044 'backslashreplace')
1045 vstr = vstr.replace('\n','\\n')
1045 vstr = vstr.replace('\n','\\n')
1046 if len(vstr) < 50:
1046 if len(vstr) < 50:
1047 print vstr
1047 print vstr
1048 else:
1048 else:
1049 printpl(vfmt_short)
1049 printpl(vfmt_short)
1050
1050
1051 def magic_reset(self, parameter_s=''):
1051 def magic_reset(self, parameter_s=''):
1052 """Resets the namespace by removing all names defined by the user.
1052 """Resets the namespace by removing all names defined by the user.
1053
1053
1054 Input/Output history are left around in case you need them.
1054 Input/Output history are left around in case you need them.
1055
1055
1056 Parameters
1056 Parameters
1057 ----------
1057 ----------
1058 -y : force reset without asking for confirmation.
1058 -y : force reset without asking for confirmation.
1059
1059
1060 Examples
1060 Examples
1061 --------
1061 --------
1062 In [6]: a = 1
1062 In [6]: a = 1
1063
1063
1064 In [7]: a
1064 In [7]: a
1065 Out[7]: 1
1065 Out[7]: 1
1066
1066
1067 In [8]: 'a' in _ip.user_ns
1067 In [8]: 'a' in _ip.user_ns
1068 Out[8]: True
1068 Out[8]: True
1069
1069
1070 In [9]: %reset -f
1070 In [9]: %reset -f
1071
1071
1072 In [10]: 'a' in _ip.user_ns
1072 In [10]: 'a' in _ip.user_ns
1073 Out[10]: False
1073 Out[10]: False
1074 """
1074 """
1075
1075
1076 if parameter_s == '-f':
1076 if parameter_s == '-f':
1077 ans = True
1077 ans = True
1078 else:
1078 else:
1079 ans = self.shell.ask_yes_no(
1079 ans = self.shell.ask_yes_no(
1080 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1080 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1081 if not ans:
1081 if not ans:
1082 print 'Nothing done.'
1082 print 'Nothing done.'
1083 return
1083 return
1084 user_ns = self.shell.user_ns
1084 user_ns = self.shell.user_ns
1085 for i in self.magic_who_ls():
1085 for i in self.magic_who_ls():
1086 del(user_ns[i])
1086 del(user_ns[i])
1087
1087
1088 # Also flush the private list of module references kept for script
1088 # Also flush the private list of module references kept for script
1089 # execution protection
1089 # execution protection
1090 self.shell.clear_main_mod_cache()
1090 self.shell.clear_main_mod_cache()
1091
1091
1092 def magic_logstart(self,parameter_s=''):
1092 def magic_logstart(self,parameter_s=''):
1093 """Start logging anywhere in a session.
1093 """Start logging anywhere in a session.
1094
1094
1095 %logstart [-o|-r|-t] [log_name [log_mode]]
1095 %logstart [-o|-r|-t] [log_name [log_mode]]
1096
1096
1097 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 If no name is given, it defaults to a file named 'ipython_log.py' in your
1098 current directory, in 'rotate' mode (see below).
1098 current directory, in 'rotate' mode (see below).
1099
1099
1100 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1101 history up to that point and then continues logging.
1101 history up to that point and then continues logging.
1102
1102
1103 %logstart takes a second optional parameter: logging mode. This can be one
1103 %logstart takes a second optional parameter: logging mode. This can be one
1104 of (note that the modes are given unquoted):\\
1104 of (note that the modes are given unquoted):\\
1105 append: well, that says it.\\
1105 append: well, that says it.\\
1106 backup: rename (if exists) to name~ and start name.\\
1106 backup: rename (if exists) to name~ and start name.\\
1107 global: single logfile in your home dir, appended to.\\
1107 global: single logfile in your home dir, appended to.\\
1108 over : overwrite existing log.\\
1108 over : overwrite existing log.\\
1109 rotate: create rotating logs name.1~, name.2~, etc.
1109 rotate: create rotating logs name.1~, name.2~, etc.
1110
1110
1111 Options:
1111 Options:
1112
1112
1113 -o: log also IPython's output. In this mode, all commands which
1113 -o: log also IPython's output. In this mode, all commands which
1114 generate an Out[NN] prompt are recorded to the logfile, right after
1114 generate an Out[NN] prompt are recorded to the logfile, right after
1115 their corresponding input line. The output lines are always
1115 their corresponding input line. The output lines are always
1116 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 prepended with a '#[Out]# ' marker, so that the log remains valid
1117 Python code.
1117 Python code.
1118
1118
1119 Since this marker is always the same, filtering only the output from
1119 Since this marker is always the same, filtering only the output from
1120 a log is very easy, using for example a simple awk call:
1120 a log is very easy, using for example a simple awk call:
1121
1121
1122 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1123
1123
1124 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 -r: log 'raw' input. Normally, IPython's logs contain the processed
1125 input, so that user lines are logged in their final form, converted
1125 input, so that user lines are logged in their final form, converted
1126 into valid Python. For example, %Exit is logged as
1126 into valid Python. For example, %Exit is logged as
1127 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1128 exactly as typed, with no transformations applied.
1128 exactly as typed, with no transformations applied.
1129
1129
1130 -t: put timestamps before each input line logged (these are put in
1130 -t: put timestamps before each input line logged (these are put in
1131 comments)."""
1131 comments)."""
1132
1132
1133 opts,par = self.parse_options(parameter_s,'ort')
1133 opts,par = self.parse_options(parameter_s,'ort')
1134 log_output = 'o' in opts
1134 log_output = 'o' in opts
1135 log_raw_input = 'r' in opts
1135 log_raw_input = 'r' in opts
1136 timestamp = 't' in opts
1136 timestamp = 't' in opts
1137
1137
1138 logger = self.shell.logger
1138 logger = self.shell.logger
1139
1139
1140 # if no args are given, the defaults set in the logger constructor by
1140 # if no args are given, the defaults set in the logger constructor by
1141 # ipytohn remain valid
1141 # ipytohn remain valid
1142 if par:
1142 if par:
1143 try:
1143 try:
1144 logfname,logmode = par.split()
1144 logfname,logmode = par.split()
1145 except:
1145 except:
1146 logfname = par
1146 logfname = par
1147 logmode = 'backup'
1147 logmode = 'backup'
1148 else:
1148 else:
1149 logfname = logger.logfname
1149 logfname = logger.logfname
1150 logmode = logger.logmode
1150 logmode = logger.logmode
1151 # put logfname into rc struct as if it had been called on the command
1151 # put logfname into rc struct as if it had been called on the command
1152 # line, so it ends up saved in the log header Save it in case we need
1152 # line, so it ends up saved in the log header Save it in case we need
1153 # to restore it...
1153 # to restore it...
1154 old_logfile = self.shell.logfile
1154 old_logfile = self.shell.logfile
1155 if logfname:
1155 if logfname:
1156 logfname = os.path.expanduser(logfname)
1156 logfname = os.path.expanduser(logfname)
1157 self.shell.logfile = logfname
1157 self.shell.logfile = logfname
1158
1158
1159 loghead = '# IPython log file\n\n'
1159 loghead = '# IPython log file\n\n'
1160 try:
1160 try:
1161 started = logger.logstart(logfname,loghead,logmode,
1161 started = logger.logstart(logfname,loghead,logmode,
1162 log_output,timestamp,log_raw_input)
1162 log_output,timestamp,log_raw_input)
1163 except:
1163 except:
1164 rc.opts.logfile = old_logfile
1164 rc.opts.logfile = old_logfile
1165 warn("Couldn't start log: %s" % sys.exc_info()[1])
1165 warn("Couldn't start log: %s" % sys.exc_info()[1])
1166 else:
1166 else:
1167 # log input history up to this point, optionally interleaving
1167 # log input history up to this point, optionally interleaving
1168 # output if requested
1168 # output if requested
1169
1169
1170 if timestamp:
1170 if timestamp:
1171 # disable timestamping for the previous history, since we've
1171 # disable timestamping for the previous history, since we've
1172 # lost those already (no time machine here).
1172 # lost those already (no time machine here).
1173 logger.timestamp = False
1173 logger.timestamp = False
1174
1174
1175 if log_raw_input:
1175 if log_raw_input:
1176 input_hist = self.shell.input_hist_raw
1176 input_hist = self.shell.input_hist_raw
1177 else:
1177 else:
1178 input_hist = self.shell.input_hist
1178 input_hist = self.shell.input_hist
1179
1179
1180 if log_output:
1180 if log_output:
1181 log_write = logger.log_write
1181 log_write = logger.log_write
1182 output_hist = self.shell.output_hist
1182 output_hist = self.shell.output_hist
1183 for n in range(1,len(input_hist)-1):
1183 for n in range(1,len(input_hist)-1):
1184 log_write(input_hist[n].rstrip())
1184 log_write(input_hist[n].rstrip())
1185 if n in output_hist:
1185 if n in output_hist:
1186 log_write(repr(output_hist[n]),'output')
1186 log_write(repr(output_hist[n]),'output')
1187 else:
1187 else:
1188 logger.log_write(input_hist[1:])
1188 logger.log_write(input_hist[1:])
1189 if timestamp:
1189 if timestamp:
1190 # re-enable timestamping
1190 # re-enable timestamping
1191 logger.timestamp = True
1191 logger.timestamp = True
1192
1192
1193 print ('Activating auto-logging. '
1193 print ('Activating auto-logging. '
1194 'Current session state plus future input saved.')
1194 'Current session state plus future input saved.')
1195 logger.logstate()
1195 logger.logstate()
1196
1196
1197 def magic_logstop(self,parameter_s=''):
1197 def magic_logstop(self,parameter_s=''):
1198 """Fully stop logging and close log file.
1198 """Fully stop logging and close log file.
1199
1199
1200 In order to start logging again, a new %logstart call needs to be made,
1200 In order to start logging again, a new %logstart call needs to be made,
1201 possibly (though not necessarily) with a new filename, mode and other
1201 possibly (though not necessarily) with a new filename, mode and other
1202 options."""
1202 options."""
1203 self.logger.logstop()
1203 self.logger.logstop()
1204
1204
1205 def magic_logoff(self,parameter_s=''):
1205 def magic_logoff(self,parameter_s=''):
1206 """Temporarily stop logging.
1206 """Temporarily stop logging.
1207
1207
1208 You must have previously started logging."""
1208 You must have previously started logging."""
1209 self.shell.logger.switch_log(0)
1209 self.shell.logger.switch_log(0)
1210
1210
1211 def magic_logon(self,parameter_s=''):
1211 def magic_logon(self,parameter_s=''):
1212 """Restart logging.
1212 """Restart logging.
1213
1213
1214 This function is for restarting logging which you've temporarily
1214 This function is for restarting logging which you've temporarily
1215 stopped with %logoff. For starting logging for the first time, you
1215 stopped with %logoff. For starting logging for the first time, you
1216 must use the %logstart function, which allows you to specify an
1216 must use the %logstart function, which allows you to specify an
1217 optional log filename."""
1217 optional log filename."""
1218
1218
1219 self.shell.logger.switch_log(1)
1219 self.shell.logger.switch_log(1)
1220
1220
1221 def magic_logstate(self,parameter_s=''):
1221 def magic_logstate(self,parameter_s=''):
1222 """Print the status of the logging system."""
1222 """Print the status of the logging system."""
1223
1223
1224 self.shell.logger.logstate()
1224 self.shell.logger.logstate()
1225
1225
1226 def magic_pdb(self, parameter_s=''):
1226 def magic_pdb(self, parameter_s=''):
1227 """Control the automatic calling of the pdb interactive debugger.
1227 """Control the automatic calling of the pdb interactive debugger.
1228
1228
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1229 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1230 argument it works as a toggle.
1230 argument it works as a toggle.
1231
1231
1232 When an exception is triggered, IPython can optionally call the
1232 When an exception is triggered, IPython can optionally call the
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1233 interactive pdb debugger after the traceback printout. %pdb toggles
1234 this feature on and off.
1234 this feature on and off.
1235
1235
1236 The initial state of this feature is set in your ipythonrc
1236 The initial state of this feature is set in your ipythonrc
1237 configuration file (the variable is called 'pdb').
1237 configuration file (the variable is called 'pdb').
1238
1238
1239 If you want to just activate the debugger AFTER an exception has fired,
1239 If you want to just activate the debugger AFTER an exception has fired,
1240 without having to type '%pdb on' and rerunning your code, you can use
1240 without having to type '%pdb on' and rerunning your code, you can use
1241 the %debug magic."""
1241 the %debug magic."""
1242
1242
1243 par = parameter_s.strip().lower()
1243 par = parameter_s.strip().lower()
1244
1244
1245 if par:
1245 if par:
1246 try:
1246 try:
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1247 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1248 except KeyError:
1248 except KeyError:
1249 print ('Incorrect argument. Use on/1, off/0, '
1249 print ('Incorrect argument. Use on/1, off/0, '
1250 'or nothing for a toggle.')
1250 'or nothing for a toggle.')
1251 return
1251 return
1252 else:
1252 else:
1253 # toggle
1253 # toggle
1254 new_pdb = not self.shell.call_pdb
1254 new_pdb = not self.shell.call_pdb
1255
1255
1256 # set on the shell
1256 # set on the shell
1257 self.shell.call_pdb = new_pdb
1257 self.shell.call_pdb = new_pdb
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1258 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1259
1259
1260 def magic_debug(self, parameter_s=''):
1260 def magic_debug(self, parameter_s=''):
1261 """Activate the interactive debugger in post-mortem mode.
1261 """Activate the interactive debugger in post-mortem mode.
1262
1262
1263 If an exception has just occurred, this lets you inspect its stack
1263 If an exception has just occurred, this lets you inspect its stack
1264 frames interactively. Note that this will always work only on the last
1264 frames interactively. Note that this will always work only on the last
1265 traceback that occurred, so you must call this quickly after an
1265 traceback that occurred, so you must call this quickly after an
1266 exception that you wish to inspect has fired, because if another one
1266 exception that you wish to inspect has fired, because if another one
1267 occurs, it clobbers the previous one.
1267 occurs, it clobbers the previous one.
1268
1268
1269 If you want IPython to automatically do this on every exception, see
1269 If you want IPython to automatically do this on every exception, see
1270 the %pdb magic for more details.
1270 the %pdb magic for more details.
1271 """
1271 """
1272 self.shell.debugger(force=True)
1272 self.shell.debugger(force=True)
1273
1273
1274 @testdec.skip_doctest
1274 @testdec.skip_doctest
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1275 def magic_prun(self, parameter_s ='',user_mode=1,
1276 opts=None,arg_lst=None,prog_ns=None):
1276 opts=None,arg_lst=None,prog_ns=None):
1277
1277
1278 """Run a statement through the python code profiler.
1278 """Run a statement through the python code profiler.
1279
1279
1280 Usage:
1280 Usage:
1281 %prun [options] statement
1281 %prun [options] statement
1282
1282
1283 The given statement (which doesn't require quote marks) is run via the
1283 The given statement (which doesn't require quote marks) is run via the
1284 python profiler in a manner similar to the profile.run() function.
1284 python profiler in a manner similar to the profile.run() function.
1285 Namespaces are internally managed to work correctly; profile.run
1285 Namespaces are internally managed to work correctly; profile.run
1286 cannot be used in IPython because it makes certain assumptions about
1286 cannot be used in IPython because it makes certain assumptions about
1287 namespaces which do not hold under IPython.
1287 namespaces which do not hold under IPython.
1288
1288
1289 Options:
1289 Options:
1290
1290
1291 -l <limit>: you can place restrictions on what or how much of the
1291 -l <limit>: you can place restrictions on what or how much of the
1292 profile gets printed. The limit value can be:
1292 profile gets printed. The limit value can be:
1293
1293
1294 * A string: only information for function names containing this string
1294 * A string: only information for function names containing this string
1295 is printed.
1295 is printed.
1296
1296
1297 * An integer: only these many lines are printed.
1297 * An integer: only these many lines are printed.
1298
1298
1299 * A float (between 0 and 1): this fraction of the report is printed
1299 * A float (between 0 and 1): this fraction of the report is printed
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1300 (for example, use a limit of 0.4 to see the topmost 40% only).
1301
1301
1302 You can combine several limits with repeated use of the option. For
1302 You can combine several limits with repeated use of the option. For
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1303 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1304 information about class constructors.
1304 information about class constructors.
1305
1305
1306 -r: return the pstats.Stats object generated by the profiling. This
1306 -r: return the pstats.Stats object generated by the profiling. This
1307 object has all the information about the profile in it, and you can
1307 object has all the information about the profile in it, and you can
1308 later use it for further analysis or in other functions.
1308 later use it for further analysis or in other functions.
1309
1309
1310 -s <key>: sort profile by given key. You can provide more than one key
1310 -s <key>: sort profile by given key. You can provide more than one key
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1311 by using the option several times: '-s key1 -s key2 -s key3...'. The
1312 default sorting key is 'time'.
1312 default sorting key is 'time'.
1313
1313
1314 The following is copied verbatim from the profile documentation
1314 The following is copied verbatim from the profile documentation
1315 referenced below:
1315 referenced below:
1316
1316
1317 When more than one key is provided, additional keys are used as
1317 When more than one key is provided, additional keys are used as
1318 secondary criteria when the there is equality in all keys selected
1318 secondary criteria when the there is equality in all keys selected
1319 before them.
1319 before them.
1320
1320
1321 Abbreviations can be used for any key names, as long as the
1321 Abbreviations can be used for any key names, as long as the
1322 abbreviation is unambiguous. The following are the keys currently
1322 abbreviation is unambiguous. The following are the keys currently
1323 defined:
1323 defined:
1324
1324
1325 Valid Arg Meaning
1325 Valid Arg Meaning
1326 "calls" call count
1326 "calls" call count
1327 "cumulative" cumulative time
1327 "cumulative" cumulative time
1328 "file" file name
1328 "file" file name
1329 "module" file name
1329 "module" file name
1330 "pcalls" primitive call count
1330 "pcalls" primitive call count
1331 "line" line number
1331 "line" line number
1332 "name" function name
1332 "name" function name
1333 "nfl" name/file/line
1333 "nfl" name/file/line
1334 "stdname" standard name
1334 "stdname" standard name
1335 "time" internal time
1335 "time" internal time
1336
1336
1337 Note that all sorts on statistics are in descending order (placing
1337 Note that all sorts on statistics are in descending order (placing
1338 most time consuming items first), where as name, file, and line number
1338 most time consuming items first), where as name, file, and line number
1339 searches are in ascending order (i.e., alphabetical). The subtle
1339 searches are in ascending order (i.e., alphabetical). The subtle
1340 distinction between "nfl" and "stdname" is that the standard name is a
1340 distinction between "nfl" and "stdname" is that the standard name is a
1341 sort of the name as printed, which means that the embedded line
1341 sort of the name as printed, which means that the embedded line
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1342 numbers get compared in an odd way. For example, lines 3, 20, and 40
1343 would (if the file names were the same) appear in the string order
1343 would (if the file names were the same) appear in the string order
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1344 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1345 line numbers. In fact, sort_stats("nfl") is the same as
1345 line numbers. In fact, sort_stats("nfl") is the same as
1346 sort_stats("name", "file", "line").
1346 sort_stats("name", "file", "line").
1347
1347
1348 -T <filename>: save profile results as shown on screen to a text
1348 -T <filename>: save profile results as shown on screen to a text
1349 file. The profile is still shown on screen.
1349 file. The profile is still shown on screen.
1350
1350
1351 -D <filename>: save (via dump_stats) profile statistics to given
1351 -D <filename>: save (via dump_stats) profile statistics to given
1352 filename. This data is in a format understod by the pstats module, and
1352 filename. This data is in a format understod by the pstats module, and
1353 is generated by a call to the dump_stats() method of profile
1353 is generated by a call to the dump_stats() method of profile
1354 objects. The profile is still shown on screen.
1354 objects. The profile is still shown on screen.
1355
1355
1356 If you want to run complete programs under the profiler's control, use
1356 If you want to run complete programs under the profiler's control, use
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1357 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1358 contains profiler specific options as described here.
1358 contains profiler specific options as described here.
1359
1359
1360 You can read the complete documentation for the profile module with::
1360 You can read the complete documentation for the profile module with::
1361
1361
1362 In [1]: import profile; profile.help()
1362 In [1]: import profile; profile.help()
1363 """
1363 """
1364
1364
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1365 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1366 # protect user quote marks
1366 # protect user quote marks
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1367 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1368
1368
1369 if user_mode: # regular user call
1369 if user_mode: # regular user call
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1370 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1371 list_all=1)
1371 list_all=1)
1372 namespace = self.shell.user_ns
1372 namespace = self.shell.user_ns
1373 else: # called to run a program by %run -p
1373 else: # called to run a program by %run -p
1374 try:
1374 try:
1375 filename = get_py_filename(arg_lst[0])
1375 filename = get_py_filename(arg_lst[0])
1376 except IOError,msg:
1376 except IOError,msg:
1377 error(msg)
1377 error(msg)
1378 return
1378 return
1379
1379
1380 arg_str = 'execfile(filename,prog_ns)'
1380 arg_str = 'execfile(filename,prog_ns)'
1381 namespace = locals()
1381 namespace = locals()
1382
1382
1383 opts.merge(opts_def)
1383 opts.merge(opts_def)
1384
1384
1385 prof = profile.Profile()
1385 prof = profile.Profile()
1386 try:
1386 try:
1387 prof = prof.runctx(arg_str,namespace,namespace)
1387 prof = prof.runctx(arg_str,namespace,namespace)
1388 sys_exit = ''
1388 sys_exit = ''
1389 except SystemExit:
1389 except SystemExit:
1390 sys_exit = """*** SystemExit exception caught in code being profiled."""
1390 sys_exit = """*** SystemExit exception caught in code being profiled."""
1391
1391
1392 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1392 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1393
1393
1394 lims = opts.l
1394 lims = opts.l
1395 if lims:
1395 if lims:
1396 lims = [] # rebuild lims with ints/floats/strings
1396 lims = [] # rebuild lims with ints/floats/strings
1397 for lim in opts.l:
1397 for lim in opts.l:
1398 try:
1398 try:
1399 lims.append(int(lim))
1399 lims.append(int(lim))
1400 except ValueError:
1400 except ValueError:
1401 try:
1401 try:
1402 lims.append(float(lim))
1402 lims.append(float(lim))
1403 except ValueError:
1403 except ValueError:
1404 lims.append(lim)
1404 lims.append(lim)
1405
1405
1406 # Trap output.
1406 # Trap output.
1407 stdout_trap = StringIO()
1407 stdout_trap = StringIO()
1408
1408
1409 if hasattr(stats,'stream'):
1409 if hasattr(stats,'stream'):
1410 # In newer versions of python, the stats object has a 'stream'
1410 # In newer versions of python, the stats object has a 'stream'
1411 # attribute to write into.
1411 # attribute to write into.
1412 stats.stream = stdout_trap
1412 stats.stream = stdout_trap
1413 stats.print_stats(*lims)
1413 stats.print_stats(*lims)
1414 else:
1414 else:
1415 # For older versions, we manually redirect stdout during printing
1415 # For older versions, we manually redirect stdout during printing
1416 sys_stdout = sys.stdout
1416 sys_stdout = sys.stdout
1417 try:
1417 try:
1418 sys.stdout = stdout_trap
1418 sys.stdout = stdout_trap
1419 stats.print_stats(*lims)
1419 stats.print_stats(*lims)
1420 finally:
1420 finally:
1421 sys.stdout = sys_stdout
1421 sys.stdout = sys_stdout
1422
1422
1423 output = stdout_trap.getvalue()
1423 output = stdout_trap.getvalue()
1424 output = output.rstrip()
1424 output = output.rstrip()
1425
1425
1426 page(output,screen_lines=self.shell.usable_screen_length)
1426 page(output,screen_lines=self.shell.usable_screen_length)
1427 print sys_exit,
1427 print sys_exit,
1428
1428
1429 dump_file = opts.D[0]
1429 dump_file = opts.D[0]
1430 text_file = opts.T[0]
1430 text_file = opts.T[0]
1431 if dump_file:
1431 if dump_file:
1432 prof.dump_stats(dump_file)
1432 prof.dump_stats(dump_file)
1433 print '\n*** Profile stats marshalled to file',\
1433 print '\n*** Profile stats marshalled to file',\
1434 `dump_file`+'.',sys_exit
1434 `dump_file`+'.',sys_exit
1435 if text_file:
1435 if text_file:
1436 pfile = file(text_file,'w')
1436 pfile = file(text_file,'w')
1437 pfile.write(output)
1437 pfile.write(output)
1438 pfile.close()
1438 pfile.close()
1439 print '\n*** Profile printout saved to text file',\
1439 print '\n*** Profile printout saved to text file',\
1440 `text_file`+'.',sys_exit
1440 `text_file`+'.',sys_exit
1441
1441
1442 if opts.has_key('r'):
1442 if opts.has_key('r'):
1443 return stats
1443 return stats
1444 else:
1444 else:
1445 return None
1445 return None
1446
1446
1447 @testdec.skip_doctest
1447 @testdec.skip_doctest
1448 def magic_run(self, parameter_s ='',runner=None,
1448 def magic_run(self, parameter_s ='',runner=None,
1449 file_finder=get_py_filename):
1449 file_finder=get_py_filename):
1450 """Run the named file inside IPython as a program.
1450 """Run the named file inside IPython as a program.
1451
1451
1452 Usage:\\
1452 Usage:\\
1453 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1453 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1454
1454
1455 Parameters after the filename are passed as command-line arguments to
1455 Parameters after the filename are passed as command-line arguments to
1456 the program (put in sys.argv). Then, control returns to IPython's
1456 the program (put in sys.argv). Then, control returns to IPython's
1457 prompt.
1457 prompt.
1458
1458
1459 This is similar to running at a system prompt:\\
1459 This is similar to running at a system prompt:\\
1460 $ python file args\\
1460 $ python file args\\
1461 but with the advantage of giving you IPython's tracebacks, and of
1461 but with the advantage of giving you IPython's tracebacks, and of
1462 loading all variables into your interactive namespace for further use
1462 loading all variables into your interactive namespace for further use
1463 (unless -p is used, see below).
1463 (unless -p is used, see below).
1464
1464
1465 The file is executed in a namespace initially consisting only of
1465 The file is executed in a namespace initially consisting only of
1466 __name__=='__main__' and sys.argv constructed as indicated. It thus
1466 __name__=='__main__' and sys.argv constructed as indicated. It thus
1467 sees its environment as if it were being run as a stand-alone program
1467 sees its environment as if it were being run as a stand-alone program
1468 (except for sharing global objects such as previously imported
1468 (except for sharing global objects such as previously imported
1469 modules). But after execution, the IPython interactive namespace gets
1469 modules). But after execution, the IPython interactive namespace gets
1470 updated with all variables defined in the program (except for __name__
1470 updated with all variables defined in the program (except for __name__
1471 and sys.argv). This allows for very convenient loading of code for
1471 and sys.argv). This allows for very convenient loading of code for
1472 interactive work, while giving each program a 'clean sheet' to run in.
1472 interactive work, while giving each program a 'clean sheet' to run in.
1473
1473
1474 Options:
1474 Options:
1475
1475
1476 -n: __name__ is NOT set to '__main__', but to the running file's name
1476 -n: __name__ is NOT set to '__main__', but to the running file's name
1477 without extension (as python does under import). This allows running
1477 without extension (as python does under import). This allows running
1478 scripts and reloading the definitions in them without calling code
1478 scripts and reloading the definitions in them without calling code
1479 protected by an ' if __name__ == "__main__" ' clause.
1479 protected by an ' if __name__ == "__main__" ' clause.
1480
1480
1481 -i: run the file in IPython's namespace instead of an empty one. This
1481 -i: run the file in IPython's namespace instead of an empty one. This
1482 is useful if you are experimenting with code written in a text editor
1482 is useful if you are experimenting with code written in a text editor
1483 which depends on variables defined interactively.
1483 which depends on variables defined interactively.
1484
1484
1485 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1485 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1486 being run. This is particularly useful if IPython is being used to
1486 being run. This is particularly useful if IPython is being used to
1487 run unittests, which always exit with a sys.exit() call. In such
1487 run unittests, which always exit with a sys.exit() call. In such
1488 cases you are interested in the output of the test results, not in
1488 cases you are interested in the output of the test results, not in
1489 seeing a traceback of the unittest module.
1489 seeing a traceback of the unittest module.
1490
1490
1491 -t: print timing information at the end of the run. IPython will give
1491 -t: print timing information at the end of the run. IPython will give
1492 you an estimated CPU time consumption for your script, which under
1492 you an estimated CPU time consumption for your script, which under
1493 Unix uses the resource module to avoid the wraparound problems of
1493 Unix uses the resource module to avoid the wraparound problems of
1494 time.clock(). Under Unix, an estimate of time spent on system tasks
1494 time.clock(). Under Unix, an estimate of time spent on system tasks
1495 is also given (for Windows platforms this is reported as 0.0).
1495 is also given (for Windows platforms this is reported as 0.0).
1496
1496
1497 If -t is given, an additional -N<N> option can be given, where <N>
1497 If -t is given, an additional -N<N> option can be given, where <N>
1498 must be an integer indicating how many times you want the script to
1498 must be an integer indicating how many times you want the script to
1499 run. The final timing report will include total and per run results.
1499 run. The final timing report will include total and per run results.
1500
1500
1501 For example (testing the script uniq_stable.py):
1501 For example (testing the script uniq_stable.py):
1502
1502
1503 In [1]: run -t uniq_stable
1503 In [1]: run -t uniq_stable
1504
1504
1505 IPython CPU timings (estimated):\\
1505 IPython CPU timings (estimated):\\
1506 User : 0.19597 s.\\
1506 User : 0.19597 s.\\
1507 System: 0.0 s.\\
1507 System: 0.0 s.\\
1508
1508
1509 In [2]: run -t -N5 uniq_stable
1509 In [2]: run -t -N5 uniq_stable
1510
1510
1511 IPython CPU timings (estimated):\\
1511 IPython CPU timings (estimated):\\
1512 Total runs performed: 5\\
1512 Total runs performed: 5\\
1513 Times : Total Per run\\
1513 Times : Total Per run\\
1514 User : 0.910862 s, 0.1821724 s.\\
1514 User : 0.910862 s, 0.1821724 s.\\
1515 System: 0.0 s, 0.0 s.
1515 System: 0.0 s, 0.0 s.
1516
1516
1517 -d: run your program under the control of pdb, the Python debugger.
1517 -d: run your program under the control of pdb, the Python debugger.
1518 This allows you to execute your program step by step, watch variables,
1518 This allows you to execute your program step by step, watch variables,
1519 etc. Internally, what IPython does is similar to calling:
1519 etc. Internally, what IPython does is similar to calling:
1520
1520
1521 pdb.run('execfile("YOURFILENAME")')
1521 pdb.run('execfile("YOURFILENAME")')
1522
1522
1523 with a breakpoint set on line 1 of your file. You can change the line
1523 with a breakpoint set on line 1 of your file. You can change the line
1524 number for this automatic breakpoint to be <N> by using the -bN option
1524 number for this automatic breakpoint to be <N> by using the -bN option
1525 (where N must be an integer). For example:
1525 (where N must be an integer). For example:
1526
1526
1527 %run -d -b40 myscript
1527 %run -d -b40 myscript
1528
1528
1529 will set the first breakpoint at line 40 in myscript.py. Note that
1529 will set the first breakpoint at line 40 in myscript.py. Note that
1530 the first breakpoint must be set on a line which actually does
1530 the first breakpoint must be set on a line which actually does
1531 something (not a comment or docstring) for it to stop execution.
1531 something (not a comment or docstring) for it to stop execution.
1532
1532
1533 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1533 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1534 first enter 'c' (without qoutes) to start execution up to the first
1534 first enter 'c' (without qoutes) to start execution up to the first
1535 breakpoint.
1535 breakpoint.
1536
1536
1537 Entering 'help' gives information about the use of the debugger. You
1537 Entering 'help' gives information about the use of the debugger. You
1538 can easily see pdb's full documentation with "import pdb;pdb.help()"
1538 can easily see pdb's full documentation with "import pdb;pdb.help()"
1539 at a prompt.
1539 at a prompt.
1540
1540
1541 -p: run program under the control of the Python profiler module (which
1541 -p: run program under the control of the Python profiler module (which
1542 prints a detailed report of execution times, function calls, etc).
1542 prints a detailed report of execution times, function calls, etc).
1543
1543
1544 You can pass other options after -p which affect the behavior of the
1544 You can pass other options after -p which affect the behavior of the
1545 profiler itself. See the docs for %prun for details.
1545 profiler itself. See the docs for %prun for details.
1546
1546
1547 In this mode, the program's variables do NOT propagate back to the
1547 In this mode, the program's variables do NOT propagate back to the
1548 IPython interactive namespace (because they remain in the namespace
1548 IPython interactive namespace (because they remain in the namespace
1549 where the profiler executes them).
1549 where the profiler executes them).
1550
1550
1551 Internally this triggers a call to %prun, see its documentation for
1551 Internally this triggers a call to %prun, see its documentation for
1552 details on the options available specifically for profiling.
1552 details on the options available specifically for profiling.
1553
1553
1554 There is one special usage for which the text above doesn't apply:
1554 There is one special usage for which the text above doesn't apply:
1555 if the filename ends with .ipy, the file is run as ipython script,
1555 if the filename ends with .ipy, the file is run as ipython script,
1556 just as if the commands were written on IPython prompt.
1556 just as if the commands were written on IPython prompt.
1557 """
1557 """
1558
1558
1559 # get arguments and set sys.argv for program to be run.
1559 # get arguments and set sys.argv for program to be run.
1560 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1560 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1561 mode='list',list_all=1)
1561 mode='list',list_all=1)
1562
1562
1563 try:
1563 try:
1564 filename = file_finder(arg_lst[0])
1564 filename = file_finder(arg_lst[0])
1565 except IndexError:
1565 except IndexError:
1566 warn('you must provide at least a filename.')
1566 warn('you must provide at least a filename.')
1567 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1567 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1568 return
1568 return
1569 except IOError,msg:
1569 except IOError,msg:
1570 error(msg)
1570 error(msg)
1571 return
1571 return
1572
1572
1573 if filename.lower().endswith('.ipy'):
1573 if filename.lower().endswith('.ipy'):
1574 self.safe_execfile_ipy(filename)
1574 self.safe_execfile_ipy(filename)
1575 return
1575 return
1576
1576
1577 # Control the response to exit() calls made by the script being run
1577 # Control the response to exit() calls made by the script being run
1578 exit_ignore = opts.has_key('e')
1578 exit_ignore = opts.has_key('e')
1579
1579
1580 # Make sure that the running script gets a proper sys.argv as if it
1580 # Make sure that the running script gets a proper sys.argv as if it
1581 # were run from a system shell.
1581 # were run from a system shell.
1582 save_argv = sys.argv # save it for later restoring
1582 save_argv = sys.argv # save it for later restoring
1583 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1583 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1584
1584
1585 if opts.has_key('i'):
1585 if opts.has_key('i'):
1586 # Run in user's interactive namespace
1586 # Run in user's interactive namespace
1587 prog_ns = self.shell.user_ns
1587 prog_ns = self.shell.user_ns
1588 __name__save = self.shell.user_ns['__name__']
1588 __name__save = self.shell.user_ns['__name__']
1589 prog_ns['__name__'] = '__main__'
1589 prog_ns['__name__'] = '__main__'
1590 main_mod = self.shell.new_main_mod(prog_ns)
1590 main_mod = self.shell.new_main_mod(prog_ns)
1591 else:
1591 else:
1592 # Run in a fresh, empty namespace
1592 # Run in a fresh, empty namespace
1593 if opts.has_key('n'):
1593 if opts.has_key('n'):
1594 name = os.path.splitext(os.path.basename(filename))[0]
1594 name = os.path.splitext(os.path.basename(filename))[0]
1595 else:
1595 else:
1596 name = '__main__'
1596 name = '__main__'
1597
1597
1598 main_mod = self.shell.new_main_mod()
1598 main_mod = self.shell.new_main_mod()
1599 prog_ns = main_mod.__dict__
1599 prog_ns = main_mod.__dict__
1600 prog_ns['__name__'] = name
1600 prog_ns['__name__'] = name
1601
1601
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1602 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1603 # set the __file__ global in the script's namespace
1603 # set the __file__ global in the script's namespace
1604 prog_ns['__file__'] = filename
1604 prog_ns['__file__'] = filename
1605
1605
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1606 # pickle fix. See iplib for an explanation. But we need to make sure
1607 # that, if we overwrite __main__, we replace it at the end
1607 # that, if we overwrite __main__, we replace it at the end
1608 main_mod_name = prog_ns['__name__']
1608 main_mod_name = prog_ns['__name__']
1609
1609
1610 if main_mod_name == '__main__':
1610 if main_mod_name == '__main__':
1611 restore_main = sys.modules['__main__']
1611 restore_main = sys.modules['__main__']
1612 else:
1612 else:
1613 restore_main = False
1613 restore_main = False
1614
1614
1615 # This needs to be undone at the end to prevent holding references to
1615 # This needs to be undone at the end to prevent holding references to
1616 # every single object ever created.
1616 # every single object ever created.
1617 sys.modules[main_mod_name] = main_mod
1617 sys.modules[main_mod_name] = main_mod
1618
1618
1619 stats = None
1619 stats = None
1620 try:
1620 try:
1621 self.shell.savehist()
1621 self.shell.savehist()
1622
1622
1623 if opts.has_key('p'):
1623 if opts.has_key('p'):
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1624 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1625 else:
1625 else:
1626 if opts.has_key('d'):
1626 if opts.has_key('d'):
1627 deb = debugger.Pdb(self.shell.colors)
1627 deb = debugger.Pdb(self.shell.colors)
1628 # reset Breakpoint state, which is moronically kept
1628 # reset Breakpoint state, which is moronically kept
1629 # in a class
1629 # in a class
1630 bdb.Breakpoint.next = 1
1630 bdb.Breakpoint.next = 1
1631 bdb.Breakpoint.bplist = {}
1631 bdb.Breakpoint.bplist = {}
1632 bdb.Breakpoint.bpbynumber = [None]
1632 bdb.Breakpoint.bpbynumber = [None]
1633 # Set an initial breakpoint to stop execution
1633 # Set an initial breakpoint to stop execution
1634 maxtries = 10
1634 maxtries = 10
1635 bp = int(opts.get('b',[1])[0])
1635 bp = int(opts.get('b',[1])[0])
1636 checkline = deb.checkline(filename,bp)
1636 checkline = deb.checkline(filename,bp)
1637 if not checkline:
1637 if not checkline:
1638 for bp in range(bp+1,bp+maxtries+1):
1638 for bp in range(bp+1,bp+maxtries+1):
1639 if deb.checkline(filename,bp):
1639 if deb.checkline(filename,bp):
1640 break
1640 break
1641 else:
1641 else:
1642 msg = ("\nI failed to find a valid line to set "
1642 msg = ("\nI failed to find a valid line to set "
1643 "a breakpoint\n"
1643 "a breakpoint\n"
1644 "after trying up to line: %s.\n"
1644 "after trying up to line: %s.\n"
1645 "Please set a valid breakpoint manually "
1645 "Please set a valid breakpoint manually "
1646 "with the -b option." % bp)
1646 "with the -b option." % bp)
1647 error(msg)
1647 error(msg)
1648 return
1648 return
1649 # if we find a good linenumber, set the breakpoint
1649 # if we find a good linenumber, set the breakpoint
1650 deb.do_break('%s:%s' % (filename,bp))
1650 deb.do_break('%s:%s' % (filename,bp))
1651 # Start file run
1651 # Start file run
1652 print "NOTE: Enter 'c' at the",
1652 print "NOTE: Enter 'c' at the",
1653 print "%s prompt to start your script." % deb.prompt
1653 print "%s prompt to start your script." % deb.prompt
1654 try:
1654 try:
1655 deb.run('execfile("%s")' % filename,prog_ns)
1655 deb.run('execfile("%s")' % filename,prog_ns)
1656
1656
1657 except:
1657 except:
1658 etype, value, tb = sys.exc_info()
1658 etype, value, tb = sys.exc_info()
1659 # Skip three frames in the traceback: the %run one,
1659 # Skip three frames in the traceback: the %run one,
1660 # one inside bdb.py, and the command-line typed by the
1660 # one inside bdb.py, and the command-line typed by the
1661 # user (run by exec in pdb itself).
1661 # user (run by exec in pdb itself).
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1662 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1663 else:
1663 else:
1664 if runner is None:
1664 if runner is None:
1665 runner = self.shell.safe_execfile
1665 runner = self.shell.safe_execfile
1666 if opts.has_key('t'):
1666 if opts.has_key('t'):
1667 # timed execution
1667 # timed execution
1668 try:
1668 try:
1669 nruns = int(opts['N'][0])
1669 nruns = int(opts['N'][0])
1670 if nruns < 1:
1670 if nruns < 1:
1671 error('Number of runs must be >=1')
1671 error('Number of runs must be >=1')
1672 return
1672 return
1673 except (KeyError):
1673 except (KeyError):
1674 nruns = 1
1674 nruns = 1
1675 if nruns == 1:
1675 if nruns == 1:
1676 t0 = clock2()
1676 t0 = clock2()
1677 runner(filename,prog_ns,prog_ns,
1677 runner(filename,prog_ns,prog_ns,
1678 exit_ignore=exit_ignore)
1678 exit_ignore=exit_ignore)
1679 t1 = clock2()
1679 t1 = clock2()
1680 t_usr = t1[0]-t0[0]
1680 t_usr = t1[0]-t0[0]
1681 t_sys = t1[1]-t0[1]
1681 t_sys = t1[1]-t0[1]
1682 print "\nIPython CPU timings (estimated):"
1682 print "\nIPython CPU timings (estimated):"
1683 print " User : %10s s." % t_usr
1683 print " User : %10s s." % t_usr
1684 print " System: %10s s." % t_sys
1684 print " System: %10s s." % t_sys
1685 else:
1685 else:
1686 runs = range(nruns)
1686 runs = range(nruns)
1687 t0 = clock2()
1687 t0 = clock2()
1688 for nr in runs:
1688 for nr in runs:
1689 runner(filename,prog_ns,prog_ns,
1689 runner(filename,prog_ns,prog_ns,
1690 exit_ignore=exit_ignore)
1690 exit_ignore=exit_ignore)
1691 t1 = clock2()
1691 t1 = clock2()
1692 t_usr = t1[0]-t0[0]
1692 t_usr = t1[0]-t0[0]
1693 t_sys = t1[1]-t0[1]
1693 t_sys = t1[1]-t0[1]
1694 print "\nIPython CPU timings (estimated):"
1694 print "\nIPython CPU timings (estimated):"
1695 print "Total runs performed:",nruns
1695 print "Total runs performed:",nruns
1696 print " Times : %10s %10s" % ('Total','Per run')
1696 print " Times : %10s %10s" % ('Total','Per run')
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1697 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1698 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1699
1699
1700 else:
1700 else:
1701 # regular execution
1701 # regular execution
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1702 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1703
1703
1704 if opts.has_key('i'):
1704 if opts.has_key('i'):
1705 self.shell.user_ns['__name__'] = __name__save
1705 self.shell.user_ns['__name__'] = __name__save
1706 else:
1706 else:
1707 # The shell MUST hold a reference to prog_ns so after %run
1707 # The shell MUST hold a reference to prog_ns so after %run
1708 # exits, the python deletion mechanism doesn't zero it out
1708 # exits, the python deletion mechanism doesn't zero it out
1709 # (leaving dangling references).
1709 # (leaving dangling references).
1710 self.shell.cache_main_mod(prog_ns,filename)
1710 self.shell.cache_main_mod(prog_ns,filename)
1711 # update IPython interactive namespace
1711 # update IPython interactive namespace
1712
1712
1713 # Some forms of read errors on the file may mean the
1713 # Some forms of read errors on the file may mean the
1714 # __name__ key was never set; using pop we don't have to
1714 # __name__ key was never set; using pop we don't have to
1715 # worry about a possible KeyError.
1715 # worry about a possible KeyError.
1716 prog_ns.pop('__name__', None)
1716 prog_ns.pop('__name__', None)
1717
1717
1718 self.shell.user_ns.update(prog_ns)
1718 self.shell.user_ns.update(prog_ns)
1719 finally:
1719 finally:
1720 # It's a bit of a mystery why, but __builtins__ can change from
1720 # It's a bit of a mystery why, but __builtins__ can change from
1721 # being a module to becoming a dict missing some key data after
1721 # being a module to becoming a dict missing some key data after
1722 # %run. As best I can see, this is NOT something IPython is doing
1722 # %run. As best I can see, this is NOT something IPython is doing
1723 # at all, and similar problems have been reported before:
1723 # at all, and similar problems have been reported before:
1724 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1724 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1725 # Since this seems to be done by the interpreter itself, the best
1725 # Since this seems to be done by the interpreter itself, the best
1726 # we can do is to at least restore __builtins__ for the user on
1726 # we can do is to at least restore __builtins__ for the user on
1727 # exit.
1727 # exit.
1728 self.shell.user_ns['__builtins__'] = __builtin__
1728 self.shell.user_ns['__builtins__'] = __builtin__
1729
1729
1730 # Ensure key global structures are restored
1730 # Ensure key global structures are restored
1731 sys.argv = save_argv
1731 sys.argv = save_argv
1732 if restore_main:
1732 if restore_main:
1733 sys.modules['__main__'] = restore_main
1733 sys.modules['__main__'] = restore_main
1734 else:
1734 else:
1735 # Remove from sys.modules the reference to main_mod we'd
1735 # Remove from sys.modules the reference to main_mod we'd
1736 # added. Otherwise it will trap references to objects
1736 # added. Otherwise it will trap references to objects
1737 # contained therein.
1737 # contained therein.
1738 del sys.modules[main_mod_name]
1738 del sys.modules[main_mod_name]
1739
1739
1740 self.shell.reloadhist()
1740 self.shell.reloadhist()
1741
1741
1742 return stats
1742 return stats
1743
1743
1744 @testdec.skip_doctest
1744 @testdec.skip_doctest
1745 def magic_timeit(self, parameter_s =''):
1745 def magic_timeit(self, parameter_s =''):
1746 """Time execution of a Python statement or expression
1746 """Time execution of a Python statement or expression
1747
1747
1748 Usage:\\
1748 Usage:\\
1749 %timeit [-n<N> -r<R> [-t|-c]] statement
1749 %timeit [-n<N> -r<R> [-t|-c]] statement
1750
1750
1751 Time execution of a Python statement or expression using the timeit
1751 Time execution of a Python statement or expression using the timeit
1752 module.
1752 module.
1753
1753
1754 Options:
1754 Options:
1755 -n<N>: execute the given statement <N> times in a loop. If this value
1755 -n<N>: execute the given statement <N> times in a loop. If this value
1756 is not given, a fitting value is chosen.
1756 is not given, a fitting value is chosen.
1757
1757
1758 -r<R>: repeat the loop iteration <R> times and take the best result.
1758 -r<R>: repeat the loop iteration <R> times and take the best result.
1759 Default: 3
1759 Default: 3
1760
1760
1761 -t: use time.time to measure the time, which is the default on Unix.
1761 -t: use time.time to measure the time, which is the default on Unix.
1762 This function measures wall time.
1762 This function measures wall time.
1763
1763
1764 -c: use time.clock to measure the time, which is the default on
1764 -c: use time.clock to measure the time, which is the default on
1765 Windows and measures wall time. On Unix, resource.getrusage is used
1765 Windows and measures wall time. On Unix, resource.getrusage is used
1766 instead and returns the CPU user time.
1766 instead and returns the CPU user time.
1767
1767
1768 -p<P>: use a precision of <P> digits to display the timing result.
1768 -p<P>: use a precision of <P> digits to display the timing result.
1769 Default: 3
1769 Default: 3
1770
1770
1771
1771
1772 Examples:
1772 Examples:
1773
1773
1774 In [1]: %timeit pass
1774 In [1]: %timeit pass
1775 10000000 loops, best of 3: 53.3 ns per loop
1775 10000000 loops, best of 3: 53.3 ns per loop
1776
1776
1777 In [2]: u = None
1777 In [2]: u = None
1778
1778
1779 In [3]: %timeit u is None
1779 In [3]: %timeit u is None
1780 10000000 loops, best of 3: 184 ns per loop
1780 10000000 loops, best of 3: 184 ns per loop
1781
1781
1782 In [4]: %timeit -r 4 u == None
1782 In [4]: %timeit -r 4 u == None
1783 1000000 loops, best of 4: 242 ns per loop
1783 1000000 loops, best of 4: 242 ns per loop
1784
1784
1785 In [5]: import time
1785 In [5]: import time
1786
1786
1787 In [6]: %timeit -n1 time.sleep(2)
1787 In [6]: %timeit -n1 time.sleep(2)
1788 1 loops, best of 3: 2 s per loop
1788 1 loops, best of 3: 2 s per loop
1789
1789
1790
1790
1791 The times reported by %timeit will be slightly higher than those
1791 The times reported by %timeit will be slightly higher than those
1792 reported by the timeit.py script when variables are accessed. This is
1792 reported by the timeit.py script when variables are accessed. This is
1793 due to the fact that %timeit executes the statement in the namespace
1793 due to the fact that %timeit executes the statement in the namespace
1794 of the shell, compared with timeit.py, which uses a single setup
1794 of the shell, compared with timeit.py, which uses a single setup
1795 statement to import function or create variables. Generally, the bias
1795 statement to import function or create variables. Generally, the bias
1796 does not matter as long as results from timeit.py are not mixed with
1796 does not matter as long as results from timeit.py are not mixed with
1797 those from %timeit."""
1797 those from %timeit."""
1798
1798
1799 import timeit
1799 import timeit
1800 import math
1800 import math
1801
1801
1802 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1802 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1803 # certain terminals. Until we figure out a robust way of
1803 # certain terminals. Until we figure out a robust way of
1804 # auto-detecting if the terminal can deal with it, use plain 'us' for
1804 # auto-detecting if the terminal can deal with it, use plain 'us' for
1805 # microseconds. I am really NOT happy about disabling the proper
1805 # microseconds. I am really NOT happy about disabling the proper
1806 # 'micro' prefix, but crashing is worse... If anyone knows what the
1806 # 'micro' prefix, but crashing is worse... If anyone knows what the
1807 # right solution for this is, I'm all ears...
1807 # right solution for this is, I'm all ears...
1808 #
1808 #
1809 # Note: using
1809 # Note: using
1810 #
1810 #
1811 # s = u'\xb5'
1811 # s = u'\xb5'
1812 # s.encode(sys.getdefaultencoding())
1812 # s.encode(sys.getdefaultencoding())
1813 #
1813 #
1814 # is not sufficient, as I've seen terminals where that fails but
1814 # is not sufficient, as I've seen terminals where that fails but
1815 # print s
1815 # print s
1816 #
1816 #
1817 # succeeds
1817 # succeeds
1818 #
1818 #
1819 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1819 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1820
1820
1821 #units = [u"s", u"ms",u'\xb5',"ns"]
1821 #units = [u"s", u"ms",u'\xb5',"ns"]
1822 units = [u"s", u"ms",u'us',"ns"]
1822 units = [u"s", u"ms",u'us',"ns"]
1823
1823
1824 scaling = [1, 1e3, 1e6, 1e9]
1824 scaling = [1, 1e3, 1e6, 1e9]
1825
1825
1826 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1826 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1827 posix=False)
1827 posix=False)
1828 if stmt == "":
1828 if stmt == "":
1829 return
1829 return
1830 timefunc = timeit.default_timer
1830 timefunc = timeit.default_timer
1831 number = int(getattr(opts, "n", 0))
1831 number = int(getattr(opts, "n", 0))
1832 repeat = int(getattr(opts, "r", timeit.default_repeat))
1832 repeat = int(getattr(opts, "r", timeit.default_repeat))
1833 precision = int(getattr(opts, "p", 3))
1833 precision = int(getattr(opts, "p", 3))
1834 if hasattr(opts, "t"):
1834 if hasattr(opts, "t"):
1835 timefunc = time.time
1835 timefunc = time.time
1836 if hasattr(opts, "c"):
1836 if hasattr(opts, "c"):
1837 timefunc = clock
1837 timefunc = clock
1838
1838
1839 timer = timeit.Timer(timer=timefunc)
1839 timer = timeit.Timer(timer=timefunc)
1840 # this code has tight coupling to the inner workings of timeit.Timer,
1840 # this code has tight coupling to the inner workings of timeit.Timer,
1841 # but is there a better way to achieve that the code stmt has access
1841 # but is there a better way to achieve that the code stmt has access
1842 # to the shell namespace?
1842 # to the shell namespace?
1843
1843
1844 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1844 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1845 'setup': "pass"}
1845 'setup': "pass"}
1846 # Track compilation time so it can be reported if too long
1846 # Track compilation time so it can be reported if too long
1847 # Minimum time above which compilation time will be reported
1847 # Minimum time above which compilation time will be reported
1848 tc_min = 0.1
1848 tc_min = 0.1
1849
1849
1850 t0 = clock()
1850 t0 = clock()
1851 code = compile(src, "<magic-timeit>", "exec")
1851 code = compile(src, "<magic-timeit>", "exec")
1852 tc = clock()-t0
1852 tc = clock()-t0
1853
1853
1854 ns = {}
1854 ns = {}
1855 exec code in self.shell.user_ns, ns
1855 exec code in self.shell.user_ns, ns
1856 timer.inner = ns["inner"]
1856 timer.inner = ns["inner"]
1857
1857
1858 if number == 0:
1858 if number == 0:
1859 # determine number so that 0.2 <= total time < 2.0
1859 # determine number so that 0.2 <= total time < 2.0
1860 number = 1
1860 number = 1
1861 for i in range(1, 10):
1861 for i in range(1, 10):
1862 if timer.timeit(number) >= 0.2:
1862 if timer.timeit(number) >= 0.2:
1863 break
1863 break
1864 number *= 10
1864 number *= 10
1865
1865
1866 best = min(timer.repeat(repeat, number)) / number
1866 best = min(timer.repeat(repeat, number)) / number
1867
1867
1868 if best > 0.0:
1868 if best > 0.0:
1869 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1869 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1870 else:
1870 else:
1871 order = 3
1871 order = 3
1872 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1872 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1873 precision,
1873 precision,
1874 best * scaling[order],
1874 best * scaling[order],
1875 units[order])
1875 units[order])
1876 if tc > tc_min:
1876 if tc > tc_min:
1877 print "Compiler time: %.2f s" % tc
1877 print "Compiler time: %.2f s" % tc
1878
1878
1879 @testdec.skip_doctest
1879 @testdec.skip_doctest
1880 def magic_time(self,parameter_s = ''):
1880 def magic_time(self,parameter_s = ''):
1881 """Time execution of a Python statement or expression.
1881 """Time execution of a Python statement or expression.
1882
1882
1883 The CPU and wall clock times are printed, and the value of the
1883 The CPU and wall clock times are printed, and the value of the
1884 expression (if any) is returned. Note that under Win32, system time
1884 expression (if any) is returned. Note that under Win32, system time
1885 is always reported as 0, since it can not be measured.
1885 is always reported as 0, since it can not be measured.
1886
1886
1887 This function provides very basic timing functionality. In Python
1887 This function provides very basic timing functionality. In Python
1888 2.3, the timeit module offers more control and sophistication, so this
1888 2.3, the timeit module offers more control and sophistication, so this
1889 could be rewritten to use it (patches welcome).
1889 could be rewritten to use it (patches welcome).
1890
1890
1891 Some examples:
1891 Some examples:
1892
1892
1893 In [1]: time 2**128
1893 In [1]: time 2**128
1894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1894 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1895 Wall time: 0.00
1895 Wall time: 0.00
1896 Out[1]: 340282366920938463463374607431768211456L
1896 Out[1]: 340282366920938463463374607431768211456L
1897
1897
1898 In [2]: n = 1000000
1898 In [2]: n = 1000000
1899
1899
1900 In [3]: time sum(range(n))
1900 In [3]: time sum(range(n))
1901 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1901 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1902 Wall time: 1.37
1902 Wall time: 1.37
1903 Out[3]: 499999500000L
1903 Out[3]: 499999500000L
1904
1904
1905 In [4]: time print 'hello world'
1905 In [4]: time print 'hello world'
1906 hello world
1906 hello world
1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1908 Wall time: 0.00
1908 Wall time: 0.00
1909
1909
1910 Note that the time needed by Python to compile the given expression
1910 Note that the time needed by Python to compile the given expression
1911 will be reported if it is more than 0.1s. In this example, the
1911 will be reported if it is more than 0.1s. In this example, the
1912 actual exponentiation is done by Python at compilation time, so while
1912 actual exponentiation is done by Python at compilation time, so while
1913 the expression can take a noticeable amount of time to compute, that
1913 the expression can take a noticeable amount of time to compute, that
1914 time is purely due to the compilation:
1914 time is purely due to the compilation:
1915
1915
1916 In [5]: time 3**9999;
1916 In [5]: time 3**9999;
1917 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1917 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 Wall time: 0.00 s
1918 Wall time: 0.00 s
1919
1919
1920 In [6]: time 3**999999;
1920 In [6]: time 3**999999;
1921 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1921 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1922 Wall time: 0.00 s
1922 Wall time: 0.00 s
1923 Compiler : 0.78 s
1923 Compiler : 0.78 s
1924 """
1924 """
1925
1925
1926 # fail immediately if the given expression can't be compiled
1926 # fail immediately if the given expression can't be compiled
1927
1927
1928 expr = self.shell.prefilter(parameter_s,False)
1928 expr = self.shell.prefilter(parameter_s,False)
1929
1929
1930 # Minimum time above which compilation time will be reported
1930 # Minimum time above which compilation time will be reported
1931 tc_min = 0.1
1931 tc_min = 0.1
1932
1932
1933 try:
1933 try:
1934 mode = 'eval'
1934 mode = 'eval'
1935 t0 = clock()
1935 t0 = clock()
1936 code = compile(expr,'<timed eval>',mode)
1936 code = compile(expr,'<timed eval>',mode)
1937 tc = clock()-t0
1937 tc = clock()-t0
1938 except SyntaxError:
1938 except SyntaxError:
1939 mode = 'exec'
1939 mode = 'exec'
1940 t0 = clock()
1940 t0 = clock()
1941 code = compile(expr,'<timed exec>',mode)
1941 code = compile(expr,'<timed exec>',mode)
1942 tc = clock()-t0
1942 tc = clock()-t0
1943 # skew measurement as little as possible
1943 # skew measurement as little as possible
1944 glob = self.shell.user_ns
1944 glob = self.shell.user_ns
1945 clk = clock2
1945 clk = clock2
1946 wtime = time.time
1946 wtime = time.time
1947 # time execution
1947 # time execution
1948 wall_st = wtime()
1948 wall_st = wtime()
1949 if mode=='eval':
1949 if mode=='eval':
1950 st = clk()
1950 st = clk()
1951 out = eval(code,glob)
1951 out = eval(code,glob)
1952 end = clk()
1952 end = clk()
1953 else:
1953 else:
1954 st = clk()
1954 st = clk()
1955 exec code in glob
1955 exec code in glob
1956 end = clk()
1956 end = clk()
1957 out = None
1957 out = None
1958 wall_end = wtime()
1958 wall_end = wtime()
1959 # Compute actual times and report
1959 # Compute actual times and report
1960 wall_time = wall_end-wall_st
1960 wall_time = wall_end-wall_st
1961 cpu_user = end[0]-st[0]
1961 cpu_user = end[0]-st[0]
1962 cpu_sys = end[1]-st[1]
1962 cpu_sys = end[1]-st[1]
1963 cpu_tot = cpu_user+cpu_sys
1963 cpu_tot = cpu_user+cpu_sys
1964 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1964 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1965 (cpu_user,cpu_sys,cpu_tot)
1965 (cpu_user,cpu_sys,cpu_tot)
1966 print "Wall time: %.2f s" % wall_time
1966 print "Wall time: %.2f s" % wall_time
1967 if tc > tc_min:
1967 if tc > tc_min:
1968 print "Compiler : %.2f s" % tc
1968 print "Compiler : %.2f s" % tc
1969 return out
1969 return out
1970
1970
1971 @testdec.skip_doctest
1971 @testdec.skip_doctest
1972 def magic_macro(self,parameter_s = ''):
1972 def magic_macro(self,parameter_s = ''):
1973 """Define a set of input lines as a macro for future re-execution.
1973 """Define a set of input lines as a macro for future re-execution.
1974
1974
1975 Usage:\\
1975 Usage:\\
1976 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1976 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1977
1977
1978 Options:
1978 Options:
1979
1979
1980 -r: use 'raw' input. By default, the 'processed' history is used,
1980 -r: use 'raw' input. By default, the 'processed' history is used,
1981 so that magics are loaded in their transformed version to valid
1981 so that magics are loaded in their transformed version to valid
1982 Python. If this option is given, the raw input as typed as the
1982 Python. If this option is given, the raw input as typed as the
1983 command line is used instead.
1983 command line is used instead.
1984
1984
1985 This will define a global variable called `name` which is a string
1985 This will define a global variable called `name` which is a string
1986 made of joining the slices and lines you specify (n1,n2,... numbers
1986 made of joining the slices and lines you specify (n1,n2,... numbers
1987 above) from your input history into a single string. This variable
1987 above) from your input history into a single string. This variable
1988 acts like an automatic function which re-executes those lines as if
1988 acts like an automatic function which re-executes those lines as if
1989 you had typed them. You just type 'name' at the prompt and the code
1989 you had typed them. You just type 'name' at the prompt and the code
1990 executes.
1990 executes.
1991
1991
1992 The notation for indicating number ranges is: n1-n2 means 'use line
1992 The notation for indicating number ranges is: n1-n2 means 'use line
1993 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1993 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1994 using the lines numbered 5,6 and 7.
1994 using the lines numbered 5,6 and 7.
1995
1995
1996 Note: as a 'hidden' feature, you can also use traditional python slice
1996 Note: as a 'hidden' feature, you can also use traditional python slice
1997 notation, where N:M means numbers N through M-1.
1997 notation, where N:M means numbers N through M-1.
1998
1998
1999 For example, if your history contains (%hist prints it):
1999 For example, if your history contains (%hist prints it):
2000
2000
2001 44: x=1
2001 44: x=1
2002 45: y=3
2002 45: y=3
2003 46: z=x+y
2003 46: z=x+y
2004 47: print x
2004 47: print x
2005 48: a=5
2005 48: a=5
2006 49: print 'x',x,'y',y
2006 49: print 'x',x,'y',y
2007
2007
2008 you can create a macro with lines 44 through 47 (included) and line 49
2008 you can create a macro with lines 44 through 47 (included) and line 49
2009 called my_macro with:
2009 called my_macro with:
2010
2010
2011 In [55]: %macro my_macro 44-47 49
2011 In [55]: %macro my_macro 44-47 49
2012
2012
2013 Now, typing `my_macro` (without quotes) will re-execute all this code
2013 Now, typing `my_macro` (without quotes) will re-execute all this code
2014 in one pass.
2014 in one pass.
2015
2015
2016 You don't need to give the line-numbers in order, and any given line
2016 You don't need to give the line-numbers in order, and any given line
2017 number can appear multiple times. You can assemble macros with any
2017 number can appear multiple times. You can assemble macros with any
2018 lines from your input history in any order.
2018 lines from your input history in any order.
2019
2019
2020 The macro is a simple object which holds its value in an attribute,
2020 The macro is a simple object which holds its value in an attribute,
2021 but IPython's display system checks for macros and executes them as
2021 but IPython's display system checks for macros and executes them as
2022 code instead of printing them when you type their name.
2022 code instead of printing them when you type their name.
2023
2023
2024 You can view a macro's contents by explicitly printing it with:
2024 You can view a macro's contents by explicitly printing it with:
2025
2025
2026 'print macro_name'.
2026 'print macro_name'.
2027
2027
2028 For one-off cases which DON'T contain magic function calls in them you
2028 For one-off cases which DON'T contain magic function calls in them you
2029 can obtain similar results by explicitly executing slices from your
2029 can obtain similar results by explicitly executing slices from your
2030 input history with:
2030 input history with:
2031
2031
2032 In [60]: exec In[44:48]+In[49]"""
2032 In [60]: exec In[44:48]+In[49]"""
2033
2033
2034 opts,args = self.parse_options(parameter_s,'r',mode='list')
2034 opts,args = self.parse_options(parameter_s,'r',mode='list')
2035 if not args:
2035 if not args:
2036 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2036 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2037 macs.sort()
2037 macs.sort()
2038 return macs
2038 return macs
2039 if len(args) == 1:
2039 if len(args) == 1:
2040 raise UsageError(
2040 raise UsageError(
2041 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2041 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2042 name,ranges = args[0], args[1:]
2042 name,ranges = args[0], args[1:]
2043
2043
2044 #print 'rng',ranges # dbg
2044 #print 'rng',ranges # dbg
2045 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2045 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2046 macro = Macro(lines)
2046 macro = Macro(lines)
2047 self.shell.define_macro(name, macro)
2047 self.shell.define_macro(name, macro)
2048 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2048 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2049 print 'Macro contents:'
2049 print 'Macro contents:'
2050 print macro,
2050 print macro,
2051
2051
2052 def magic_save(self,parameter_s = ''):
2052 def magic_save(self,parameter_s = ''):
2053 """Save a set of lines to a given filename.
2053 """Save a set of lines to a given filename.
2054
2054
2055 Usage:\\
2055 Usage:\\
2056 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2056 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2057
2057
2058 Options:
2058 Options:
2059
2059
2060 -r: use 'raw' input. By default, the 'processed' history is used,
2060 -r: use 'raw' input. By default, the 'processed' history is used,
2061 so that magics are loaded in their transformed version to valid
2061 so that magics are loaded in their transformed version to valid
2062 Python. If this option is given, the raw input as typed as the
2062 Python. If this option is given, the raw input as typed as the
2063 command line is used instead.
2063 command line is used instead.
2064
2064
2065 This function uses the same syntax as %macro for line extraction, but
2065 This function uses the same syntax as %macro for line extraction, but
2066 instead of creating a macro it saves the resulting string to the
2066 instead of creating a macro it saves the resulting string to the
2067 filename you specify.
2067 filename you specify.
2068
2068
2069 It adds a '.py' extension to the file if you don't do so yourself, and
2069 It adds a '.py' extension to the file if you don't do so yourself, and
2070 it asks for confirmation before overwriting existing files."""
2070 it asks for confirmation before overwriting existing files."""
2071
2071
2072 opts,args = self.parse_options(parameter_s,'r',mode='list')
2072 opts,args = self.parse_options(parameter_s,'r',mode='list')
2073 fname,ranges = args[0], args[1:]
2073 fname,ranges = args[0], args[1:]
2074 if not fname.endswith('.py'):
2074 if not fname.endswith('.py'):
2075 fname += '.py'
2075 fname += '.py'
2076 if os.path.isfile(fname):
2076 if os.path.isfile(fname):
2077 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2077 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2078 if ans.lower() not in ['y','yes']:
2078 if ans.lower() not in ['y','yes']:
2079 print 'Operation cancelled.'
2079 print 'Operation cancelled.'
2080 return
2080 return
2081 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2081 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2082 f = file(fname,'w')
2082 f = file(fname,'w')
2083 f.write(cmds)
2083 f.write(cmds)
2084 f.close()
2084 f.close()
2085 print 'The following commands were written to file `%s`:' % fname
2085 print 'The following commands were written to file `%s`:' % fname
2086 print cmds
2086 print cmds
2087
2087
2088 def _edit_macro(self,mname,macro):
2088 def _edit_macro(self,mname,macro):
2089 """open an editor with the macro data in a file"""
2089 """open an editor with the macro data in a file"""
2090 filename = self.shell.mktempfile(macro.value)
2090 filename = self.shell.mktempfile(macro.value)
2091 self.shell.hooks.editor(filename)
2091 self.shell.hooks.editor(filename)
2092
2092
2093 # and make a new macro object, to replace the old one
2093 # and make a new macro object, to replace the old one
2094 mfile = open(filename)
2094 mfile = open(filename)
2095 mvalue = mfile.read()
2095 mvalue = mfile.read()
2096 mfile.close()
2096 mfile.close()
2097 self.shell.user_ns[mname] = Macro(mvalue)
2097 self.shell.user_ns[mname] = Macro(mvalue)
2098
2098
2099 def magic_ed(self,parameter_s=''):
2099 def magic_ed(self,parameter_s=''):
2100 """Alias to %edit."""
2100 """Alias to %edit."""
2101 return self.magic_edit(parameter_s)
2101 return self.magic_edit(parameter_s)
2102
2102
2103 @testdec.skip_doctest
2103 @testdec.skip_doctest
2104 def magic_edit(self,parameter_s='',last_call=['','']):
2104 def magic_edit(self,parameter_s='',last_call=['','']):
2105 """Bring up an editor and execute the resulting code.
2105 """Bring up an editor and execute the resulting code.
2106
2106
2107 Usage:
2107 Usage:
2108 %edit [options] [args]
2108 %edit [options] [args]
2109
2109
2110 %edit runs IPython's editor hook. The default version of this hook is
2110 %edit runs IPython's editor hook. The default version of this hook is
2111 set to call the __IPYTHON__.rc.editor command. This is read from your
2111 set to call the __IPYTHON__.rc.editor command. This is read from your
2112 environment variable $EDITOR. If this isn't found, it will default to
2112 environment variable $EDITOR. If this isn't found, it will default to
2113 vi under Linux/Unix and to notepad under Windows. See the end of this
2113 vi under Linux/Unix and to notepad under Windows. See the end of this
2114 docstring for how to change the editor hook.
2114 docstring for how to change the editor hook.
2115
2115
2116 You can also set the value of this editor via the command line option
2116 You can also set the value of this editor via the command line option
2117 '-editor' or in your ipythonrc file. This is useful if you wish to use
2117 '-editor' or in your ipythonrc file. This is useful if you wish to use
2118 specifically for IPython an editor different from your typical default
2118 specifically for IPython an editor different from your typical default
2119 (and for Windows users who typically don't set environment variables).
2119 (and for Windows users who typically don't set environment variables).
2120
2120
2121 This command allows you to conveniently edit multi-line code right in
2121 This command allows you to conveniently edit multi-line code right in
2122 your IPython session.
2122 your IPython session.
2123
2123
2124 If called without arguments, %edit opens up an empty editor with a
2124 If called without arguments, %edit opens up an empty editor with a
2125 temporary file and will execute the contents of this file when you
2125 temporary file and will execute the contents of this file when you
2126 close it (don't forget to save it!).
2126 close it (don't forget to save it!).
2127
2127
2128
2128
2129 Options:
2129 Options:
2130
2130
2131 -n <number>: open the editor at a specified line number. By default,
2131 -n <number>: open the editor at a specified line number. By default,
2132 the IPython editor hook uses the unix syntax 'editor +N filename', but
2132 the IPython editor hook uses the unix syntax 'editor +N filename', but
2133 you can configure this by providing your own modified hook if your
2133 you can configure this by providing your own modified hook if your
2134 favorite editor supports line-number specifications with a different
2134 favorite editor supports line-number specifications with a different
2135 syntax.
2135 syntax.
2136
2136
2137 -p: this will call the editor with the same data as the previous time
2137 -p: this will call the editor with the same data as the previous time
2138 it was used, regardless of how long ago (in your current session) it
2138 it was used, regardless of how long ago (in your current session) it
2139 was.
2139 was.
2140
2140
2141 -r: use 'raw' input. This option only applies to input taken from the
2141 -r: use 'raw' input. This option only applies to input taken from the
2142 user's history. By default, the 'processed' history is used, so that
2142 user's history. By default, the 'processed' history is used, so that
2143 magics are loaded in their transformed version to valid Python. If
2143 magics are loaded in their transformed version to valid Python. If
2144 this option is given, the raw input as typed as the command line is
2144 this option is given, the raw input as typed as the command line is
2145 used instead. When you exit the editor, it will be executed by
2145 used instead. When you exit the editor, it will be executed by
2146 IPython's own processor.
2146 IPython's own processor.
2147
2147
2148 -x: do not execute the edited code immediately upon exit. This is
2148 -x: do not execute the edited code immediately upon exit. This is
2149 mainly useful if you are editing programs which need to be called with
2149 mainly useful if you are editing programs which need to be called with
2150 command line arguments, which you can then do using %run.
2150 command line arguments, which you can then do using %run.
2151
2151
2152
2152
2153 Arguments:
2153 Arguments:
2154
2154
2155 If arguments are given, the following possibilites exist:
2155 If arguments are given, the following possibilites exist:
2156
2156
2157 - The arguments are numbers or pairs of colon-separated numbers (like
2157 - The arguments are numbers or pairs of colon-separated numbers (like
2158 1 4:8 9). These are interpreted as lines of previous input to be
2158 1 4:8 9). These are interpreted as lines of previous input to be
2159 loaded into the editor. The syntax is the same of the %macro command.
2159 loaded into the editor. The syntax is the same of the %macro command.
2160
2160
2161 - If the argument doesn't start with a number, it is evaluated as a
2161 - If the argument doesn't start with a number, it is evaluated as a
2162 variable and its contents loaded into the editor. You can thus edit
2162 variable and its contents loaded into the editor. You can thus edit
2163 any string which contains python code (including the result of
2163 any string which contains python code (including the result of
2164 previous edits).
2164 previous edits).
2165
2165
2166 - If the argument is the name of an object (other than a string),
2166 - If the argument is the name of an object (other than a string),
2167 IPython will try to locate the file where it was defined and open the
2167 IPython will try to locate the file where it was defined and open the
2168 editor at the point where it is defined. You can use `%edit function`
2168 editor at the point where it is defined. You can use `%edit function`
2169 to load an editor exactly at the point where 'function' is defined,
2169 to load an editor exactly at the point where 'function' is defined,
2170 edit it and have the file be executed automatically.
2170 edit it and have the file be executed automatically.
2171
2171
2172 If the object is a macro (see %macro for details), this opens up your
2172 If the object is a macro (see %macro for details), this opens up your
2173 specified editor with a temporary file containing the macro's data.
2173 specified editor with a temporary file containing the macro's data.
2174 Upon exit, the macro is reloaded with the contents of the file.
2174 Upon exit, the macro is reloaded with the contents of the file.
2175
2175
2176 Note: opening at an exact line is only supported under Unix, and some
2176 Note: opening at an exact line is only supported under Unix, and some
2177 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2177 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2178 '+NUMBER' parameter necessary for this feature. Good editors like
2178 '+NUMBER' parameter necessary for this feature. Good editors like
2179 (X)Emacs, vi, jed, pico and joe all do.
2179 (X)Emacs, vi, jed, pico and joe all do.
2180
2180
2181 - If the argument is not found as a variable, IPython will look for a
2181 - If the argument is not found as a variable, IPython will look for a
2182 file with that name (adding .py if necessary) and load it into the
2182 file with that name (adding .py if necessary) and load it into the
2183 editor. It will execute its contents with execfile() when you exit,
2183 editor. It will execute its contents with execfile() when you exit,
2184 loading any code in the file into your interactive namespace.
2184 loading any code in the file into your interactive namespace.
2185
2185
2186 After executing your code, %edit will return as output the code you
2186 After executing your code, %edit will return as output the code you
2187 typed in the editor (except when it was an existing file). This way
2187 typed in the editor (except when it was an existing file). This way
2188 you can reload the code in further invocations of %edit as a variable,
2188 you can reload the code in further invocations of %edit as a variable,
2189 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2189 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2190 the output.
2190 the output.
2191
2191
2192 Note that %edit is also available through the alias %ed.
2192 Note that %edit is also available through the alias %ed.
2193
2193
2194 This is an example of creating a simple function inside the editor and
2194 This is an example of creating a simple function inside the editor and
2195 then modifying it. First, start up the editor:
2195 then modifying it. First, start up the editor:
2196
2196
2197 In [1]: ed
2197 In [1]: ed
2198 Editing... done. Executing edited code...
2198 Editing... done. Executing edited code...
2199 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2199 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2200
2200
2201 We can then call the function foo():
2201 We can then call the function foo():
2202
2202
2203 In [2]: foo()
2203 In [2]: foo()
2204 foo() was defined in an editing session
2204 foo() was defined in an editing session
2205
2205
2206 Now we edit foo. IPython automatically loads the editor with the
2206 Now we edit foo. IPython automatically loads the editor with the
2207 (temporary) file where foo() was previously defined:
2207 (temporary) file where foo() was previously defined:
2208
2208
2209 In [3]: ed foo
2209 In [3]: ed foo
2210 Editing... done. Executing edited code...
2210 Editing... done. Executing edited code...
2211
2211
2212 And if we call foo() again we get the modified version:
2212 And if we call foo() again we get the modified version:
2213
2213
2214 In [4]: foo()
2214 In [4]: foo()
2215 foo() has now been changed!
2215 foo() has now been changed!
2216
2216
2217 Here is an example of how to edit a code snippet successive
2217 Here is an example of how to edit a code snippet successive
2218 times. First we call the editor:
2218 times. First we call the editor:
2219
2219
2220 In [5]: ed
2220 In [5]: ed
2221 Editing... done. Executing edited code...
2221 Editing... done. Executing edited code...
2222 hello
2222 hello
2223 Out[5]: "print 'hello'n"
2223 Out[5]: "print 'hello'n"
2224
2224
2225 Now we call it again with the previous output (stored in _):
2225 Now we call it again with the previous output (stored in _):
2226
2226
2227 In [6]: ed _
2227 In [6]: ed _
2228 Editing... done. Executing edited code...
2228 Editing... done. Executing edited code...
2229 hello world
2229 hello world
2230 Out[6]: "print 'hello world'n"
2230 Out[6]: "print 'hello world'n"
2231
2231
2232 Now we call it with the output #8 (stored in _8, also as Out[8]):
2232 Now we call it with the output #8 (stored in _8, also as Out[8]):
2233
2233
2234 In [7]: ed _8
2234 In [7]: ed _8
2235 Editing... done. Executing edited code...
2235 Editing... done. Executing edited code...
2236 hello again
2236 hello again
2237 Out[7]: "print 'hello again'n"
2237 Out[7]: "print 'hello again'n"
2238
2238
2239
2239
2240 Changing the default editor hook:
2240 Changing the default editor hook:
2241
2241
2242 If you wish to write your own editor hook, you can put it in a
2242 If you wish to write your own editor hook, you can put it in a
2243 configuration file which you load at startup time. The default hook
2243 configuration file which you load at startup time. The default hook
2244 is defined in the IPython.core.hooks module, and you can use that as a
2244 is defined in the IPython.core.hooks module, and you can use that as a
2245 starting example for further modifications. That file also has
2245 starting example for further modifications. That file also has
2246 general instructions on how to set a new hook for use once you've
2246 general instructions on how to set a new hook for use once you've
2247 defined it."""
2247 defined it."""
2248
2248
2249 # FIXME: This function has become a convoluted mess. It needs a
2249 # FIXME: This function has become a convoluted mess. It needs a
2250 # ground-up rewrite with clean, simple logic.
2250 # ground-up rewrite with clean, simple logic.
2251
2251
2252 def make_filename(arg):
2252 def make_filename(arg):
2253 "Make a filename from the given args"
2253 "Make a filename from the given args"
2254 try:
2254 try:
2255 filename = get_py_filename(arg)
2255 filename = get_py_filename(arg)
2256 except IOError:
2256 except IOError:
2257 if args.endswith('.py'):
2257 if args.endswith('.py'):
2258 filename = arg
2258 filename = arg
2259 else:
2259 else:
2260 filename = None
2260 filename = None
2261 return filename
2261 return filename
2262
2262
2263 # custom exceptions
2263 # custom exceptions
2264 class DataIsObject(Exception): pass
2264 class DataIsObject(Exception): pass
2265
2265
2266 opts,args = self.parse_options(parameter_s,'prxn:')
2266 opts,args = self.parse_options(parameter_s,'prxn:')
2267 # Set a few locals from the options for convenience:
2267 # Set a few locals from the options for convenience:
2268 opts_p = opts.has_key('p')
2268 opts_p = opts.has_key('p')
2269 opts_r = opts.has_key('r')
2269 opts_r = opts.has_key('r')
2270
2270
2271 # Default line number value
2271 # Default line number value
2272 lineno = opts.get('n',None)
2272 lineno = opts.get('n',None)
2273
2273
2274 if opts_p:
2274 if opts_p:
2275 args = '_%s' % last_call[0]
2275 args = '_%s' % last_call[0]
2276 if not self.shell.user_ns.has_key(args):
2276 if not self.shell.user_ns.has_key(args):
2277 args = last_call[1]
2277 args = last_call[1]
2278
2278
2279 # use last_call to remember the state of the previous call, but don't
2279 # use last_call to remember the state of the previous call, but don't
2280 # let it be clobbered by successive '-p' calls.
2280 # let it be clobbered by successive '-p' calls.
2281 try:
2281 try:
2282 last_call[0] = self.shell.outputcache.prompt_count
2282 last_call[0] = self.shell.outputcache.prompt_count
2283 if not opts_p:
2283 if not opts_p:
2284 last_call[1] = parameter_s
2284 last_call[1] = parameter_s
2285 except:
2285 except:
2286 pass
2286 pass
2287
2287
2288 # by default this is done with temp files, except when the given
2288 # by default this is done with temp files, except when the given
2289 # arg is a filename
2289 # arg is a filename
2290 use_temp = 1
2290 use_temp = 1
2291
2291
2292 if re.match(r'\d',args):
2292 if re.match(r'\d',args):
2293 # Mode where user specifies ranges of lines, like in %macro.
2293 # Mode where user specifies ranges of lines, like in %macro.
2294 # This means that you can't edit files whose names begin with
2294 # This means that you can't edit files whose names begin with
2295 # numbers this way. Tough.
2295 # numbers this way. Tough.
2296 ranges = args.split()
2296 ranges = args.split()
2297 data = ''.join(self.extract_input_slices(ranges,opts_r))
2297 data = ''.join(self.extract_input_slices(ranges,opts_r))
2298 elif args.endswith('.py'):
2298 elif args.endswith('.py'):
2299 filename = make_filename(args)
2299 filename = make_filename(args)
2300 data = ''
2300 data = ''
2301 use_temp = 0
2301 use_temp = 0
2302 elif args:
2302 elif args:
2303 try:
2303 try:
2304 # Load the parameter given as a variable. If not a string,
2304 # Load the parameter given as a variable. If not a string,
2305 # process it as an object instead (below)
2305 # process it as an object instead (below)
2306
2306
2307 #print '*** args',args,'type',type(args) # dbg
2307 #print '*** args',args,'type',type(args) # dbg
2308 data = eval(args,self.shell.user_ns)
2308 data = eval(args,self.shell.user_ns)
2309 if not type(data) in StringTypes:
2309 if not type(data) in StringTypes:
2310 raise DataIsObject
2310 raise DataIsObject
2311
2311
2312 except (NameError,SyntaxError):
2312 except (NameError,SyntaxError):
2313 # given argument is not a variable, try as a filename
2313 # given argument is not a variable, try as a filename
2314 filename = make_filename(args)
2314 filename = make_filename(args)
2315 if filename is None:
2315 if filename is None:
2316 warn("Argument given (%s) can't be found as a variable "
2316 warn("Argument given (%s) can't be found as a variable "
2317 "or as a filename." % args)
2317 "or as a filename." % args)
2318 return
2318 return
2319
2319
2320 data = ''
2320 data = ''
2321 use_temp = 0
2321 use_temp = 0
2322 except DataIsObject:
2322 except DataIsObject:
2323
2323
2324 # macros have a special edit function
2324 # macros have a special edit function
2325 if isinstance(data,Macro):
2325 if isinstance(data,Macro):
2326 self._edit_macro(args,data)
2326 self._edit_macro(args,data)
2327 return
2327 return
2328
2328
2329 # For objects, try to edit the file where they are defined
2329 # For objects, try to edit the file where they are defined
2330 try:
2330 try:
2331 filename = inspect.getabsfile(data)
2331 filename = inspect.getabsfile(data)
2332 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2332 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2333 # class created by %edit? Try to find source
2333 # class created by %edit? Try to find source
2334 # by looking for method definitions instead, the
2334 # by looking for method definitions instead, the
2335 # __module__ in those classes is FakeModule.
2335 # __module__ in those classes is FakeModule.
2336 attrs = [getattr(data, aname) for aname in dir(data)]
2336 attrs = [getattr(data, aname) for aname in dir(data)]
2337 for attr in attrs:
2337 for attr in attrs:
2338 if not inspect.ismethod(attr):
2338 if not inspect.ismethod(attr):
2339 continue
2339 continue
2340 filename = inspect.getabsfile(attr)
2340 filename = inspect.getabsfile(attr)
2341 if filename and 'fakemodule' not in filename.lower():
2341 if filename and 'fakemodule' not in filename.lower():
2342 # change the attribute to be the edit target instead
2342 # change the attribute to be the edit target instead
2343 data = attr
2343 data = attr
2344 break
2344 break
2345
2345
2346 datafile = 1
2346 datafile = 1
2347 except TypeError:
2347 except TypeError:
2348 filename = make_filename(args)
2348 filename = make_filename(args)
2349 datafile = 1
2349 datafile = 1
2350 warn('Could not find file where `%s` is defined.\n'
2350 warn('Could not find file where `%s` is defined.\n'
2351 'Opening a file named `%s`' % (args,filename))
2351 'Opening a file named `%s`' % (args,filename))
2352 # Now, make sure we can actually read the source (if it was in
2352 # Now, make sure we can actually read the source (if it was in
2353 # a temp file it's gone by now).
2353 # a temp file it's gone by now).
2354 if datafile:
2354 if datafile:
2355 try:
2355 try:
2356 if lineno is None:
2356 if lineno is None:
2357 lineno = inspect.getsourcelines(data)[1]
2357 lineno = inspect.getsourcelines(data)[1]
2358 except IOError:
2358 except IOError:
2359 filename = make_filename(args)
2359 filename = make_filename(args)
2360 if filename is None:
2360 if filename is None:
2361 warn('The file `%s` where `%s` was defined cannot '
2361 warn('The file `%s` where `%s` was defined cannot '
2362 'be read.' % (filename,data))
2362 'be read.' % (filename,data))
2363 return
2363 return
2364 use_temp = 0
2364 use_temp = 0
2365 else:
2365 else:
2366 data = ''
2366 data = ''
2367
2367
2368 if use_temp:
2368 if use_temp:
2369 filename = self.shell.mktempfile(data)
2369 filename = self.shell.mktempfile(data)
2370 print 'IPython will make a temporary file named:',filename
2370 print 'IPython will make a temporary file named:',filename
2371
2371
2372 # do actual editing here
2372 # do actual editing here
2373 print 'Editing...',
2373 print 'Editing...',
2374 sys.stdout.flush()
2374 sys.stdout.flush()
2375 try:
2375 try:
2376 self.shell.hooks.editor(filename,lineno)
2376 self.shell.hooks.editor(filename,lineno)
2377 except TryNext:
2377 except TryNext:
2378 warn('Could not open editor')
2378 warn('Could not open editor')
2379 return
2379 return
2380
2380
2381 # XXX TODO: should this be generalized for all string vars?
2381 # XXX TODO: should this be generalized for all string vars?
2382 # For now, this is special-cased to blocks created by cpaste
2382 # For now, this is special-cased to blocks created by cpaste
2383 if args.strip() == 'pasted_block':
2383 if args.strip() == 'pasted_block':
2384 self.shell.user_ns['pasted_block'] = file_read(filename)
2384 self.shell.user_ns['pasted_block'] = file_read(filename)
2385
2385
2386 if opts.has_key('x'): # -x prevents actual execution
2386 if opts.has_key('x'): # -x prevents actual execution
2387 print
2387 print
2388 else:
2388 else:
2389 print 'done. Executing edited code...'
2389 print 'done. Executing edited code...'
2390 if opts_r:
2390 if opts_r:
2391 self.shell.runlines(file_read(filename))
2391 self.shell.runlines(file_read(filename))
2392 else:
2392 else:
2393 self.shell.safe_execfile(filename,self.shell.user_ns,
2393 self.shell.safe_execfile(filename,self.shell.user_ns,
2394 self.shell.user_ns)
2394 self.shell.user_ns)
2395
2395
2396
2396
2397 if use_temp:
2397 if use_temp:
2398 try:
2398 try:
2399 return open(filename).read()
2399 return open(filename).read()
2400 except IOError,msg:
2400 except IOError,msg:
2401 if msg.filename == filename:
2401 if msg.filename == filename:
2402 warn('File not found. Did you forget to save?')
2402 warn('File not found. Did you forget to save?')
2403 return
2403 return
2404 else:
2404 else:
2405 self.shell.showtraceback()
2405 self.shell.showtraceback()
2406
2406
2407 def magic_xmode(self,parameter_s = ''):
2407 def magic_xmode(self,parameter_s = ''):
2408 """Switch modes for the exception handlers.
2408 """Switch modes for the exception handlers.
2409
2409
2410 Valid modes: Plain, Context and Verbose.
2410 Valid modes: Plain, Context and Verbose.
2411
2411
2412 If called without arguments, acts as a toggle."""
2412 If called without arguments, acts as a toggle."""
2413
2413
2414 def xmode_switch_err(name):
2414 def xmode_switch_err(name):
2415 warn('Error changing %s exception modes.\n%s' %
2415 warn('Error changing %s exception modes.\n%s' %
2416 (name,sys.exc_info()[1]))
2416 (name,sys.exc_info()[1]))
2417
2417
2418 shell = self.shell
2418 shell = self.shell
2419 new_mode = parameter_s.strip().capitalize()
2419 new_mode = parameter_s.strip().capitalize()
2420 try:
2420 try:
2421 shell.InteractiveTB.set_mode(mode=new_mode)
2421 shell.InteractiveTB.set_mode(mode=new_mode)
2422 print 'Exception reporting mode:',shell.InteractiveTB.mode
2422 print 'Exception reporting mode:',shell.InteractiveTB.mode
2423 except:
2423 except:
2424 xmode_switch_err('user')
2424 xmode_switch_err('user')
2425
2425
2426 # threaded shells use a special handler in sys.excepthook
2426 # threaded shells use a special handler in sys.excepthook
2427 if shell.isthreaded:
2427 if shell.isthreaded:
2428 try:
2428 try:
2429 shell.sys_excepthook.set_mode(mode=new_mode)
2429 shell.sys_excepthook.set_mode(mode=new_mode)
2430 except:
2430 except:
2431 xmode_switch_err('threaded')
2431 xmode_switch_err('threaded')
2432
2432
2433 def magic_colors(self,parameter_s = ''):
2433 def magic_colors(self,parameter_s = ''):
2434 """Switch color scheme for prompts, info system and exception handlers.
2434 """Switch color scheme for prompts, info system and exception handlers.
2435
2435
2436 Currently implemented schemes: NoColor, Linux, LightBG.
2436 Currently implemented schemes: NoColor, Linux, LightBG.
2437
2437
2438 Color scheme names are not case-sensitive."""
2438 Color scheme names are not case-sensitive."""
2439
2439
2440 def color_switch_err(name):
2440 def color_switch_err(name):
2441 warn('Error changing %s color schemes.\n%s' %
2441 warn('Error changing %s color schemes.\n%s' %
2442 (name,sys.exc_info()[1]))
2442 (name,sys.exc_info()[1]))
2443
2443
2444
2444
2445 new_scheme = parameter_s.strip()
2445 new_scheme = parameter_s.strip()
2446 if not new_scheme:
2446 if not new_scheme:
2447 raise UsageError(
2447 raise UsageError(
2448 "%colors: you must specify a color scheme. See '%colors?'")
2448 "%colors: you must specify a color scheme. See '%colors?'")
2449 return
2449 return
2450 # local shortcut
2450 # local shortcut
2451 shell = self.shell
2451 shell = self.shell
2452
2452
2453 import IPython.utils.rlineimpl as readline
2453 import IPython.utils.rlineimpl as readline
2454
2454
2455 if not readline.have_readline and sys.platform == "win32":
2455 if not readline.have_readline and sys.platform == "win32":
2456 msg = """\
2456 msg = """\
2457 Proper color support under MS Windows requires the pyreadline library.
2457 Proper color support under MS Windows requires the pyreadline library.
2458 You can find it at:
2458 You can find it at:
2459 http://ipython.scipy.org/moin/PyReadline/Intro
2459 http://ipython.scipy.org/moin/PyReadline/Intro
2460 Gary's readline needs the ctypes module, from:
2460 Gary's readline needs the ctypes module, from:
2461 http://starship.python.net/crew/theller/ctypes
2461 http://starship.python.net/crew/theller/ctypes
2462 (Note that ctypes is already part of Python versions 2.5 and newer).
2462 (Note that ctypes is already part of Python versions 2.5 and newer).
2463
2463
2464 Defaulting color scheme to 'NoColor'"""
2464 Defaulting color scheme to 'NoColor'"""
2465 new_scheme = 'NoColor'
2465 new_scheme = 'NoColor'
2466 warn(msg)
2466 warn(msg)
2467
2467
2468 # readline option is 0
2468 # readline option is 0
2469 if not shell.has_readline:
2469 if not shell.has_readline:
2470 new_scheme = 'NoColor'
2470 new_scheme = 'NoColor'
2471
2471
2472 # Set prompt colors
2472 # Set prompt colors
2473 try:
2473 try:
2474 shell.outputcache.set_colors(new_scheme)
2474 shell.outputcache.set_colors(new_scheme)
2475 except:
2475 except:
2476 color_switch_err('prompt')
2476 color_switch_err('prompt')
2477 else:
2477 else:
2478 shell.colors = \
2478 shell.colors = \
2479 shell.outputcache.color_table.active_scheme_name
2479 shell.outputcache.color_table.active_scheme_name
2480 # Set exception colors
2480 # Set exception colors
2481 try:
2481 try:
2482 shell.InteractiveTB.set_colors(scheme = new_scheme)
2482 shell.InteractiveTB.set_colors(scheme = new_scheme)
2483 shell.SyntaxTB.set_colors(scheme = new_scheme)
2483 shell.SyntaxTB.set_colors(scheme = new_scheme)
2484 except:
2484 except:
2485 color_switch_err('exception')
2485 color_switch_err('exception')
2486
2486
2487 # threaded shells use a verbose traceback in sys.excepthook
2487 # threaded shells use a verbose traceback in sys.excepthook
2488 if shell.isthreaded:
2488 if shell.isthreaded:
2489 try:
2489 try:
2490 shell.sys_excepthook.set_colors(scheme=new_scheme)
2490 shell.sys_excepthook.set_colors(scheme=new_scheme)
2491 except:
2491 except:
2492 color_switch_err('system exception handler')
2492 color_switch_err('system exception handler')
2493
2493
2494 # Set info (for 'object?') colors
2494 # Set info (for 'object?') colors
2495 if shell.color_info:
2495 if shell.color_info:
2496 try:
2496 try:
2497 shell.inspector.set_active_scheme(new_scheme)
2497 shell.inspector.set_active_scheme(new_scheme)
2498 except:
2498 except:
2499 color_switch_err('object inspector')
2499 color_switch_err('object inspector')
2500 else:
2500 else:
2501 shell.inspector.set_active_scheme('NoColor')
2501 shell.inspector.set_active_scheme('NoColor')
2502
2502
2503 def magic_color_info(self,parameter_s = ''):
2503 def magic_color_info(self,parameter_s = ''):
2504 """Toggle color_info.
2504 """Toggle color_info.
2505
2505
2506 The color_info configuration parameter controls whether colors are
2506 The color_info configuration parameter controls whether colors are
2507 used for displaying object details (by things like %psource, %pfile or
2507 used for displaying object details (by things like %psource, %pfile or
2508 the '?' system). This function toggles this value with each call.
2508 the '?' system). This function toggles this value with each call.
2509
2509
2510 Note that unless you have a fairly recent pager (less works better
2510 Note that unless you have a fairly recent pager (less works better
2511 than more) in your system, using colored object information displays
2511 than more) in your system, using colored object information displays
2512 will not work properly. Test it and see."""
2512 will not work properly. Test it and see."""
2513
2513
2514 self.shell.color_info = not self.shell.color_info
2514 self.shell.color_info = not self.shell.color_info
2515 self.magic_colors(self.shell.colors)
2515 self.magic_colors(self.shell.colors)
2516 print 'Object introspection functions have now coloring:',
2516 print 'Object introspection functions have now coloring:',
2517 print ['OFF','ON'][int(self.shell.color_info)]
2517 print ['OFF','ON'][int(self.shell.color_info)]
2518
2518
2519 def magic_Pprint(self, parameter_s=''):
2519 def magic_Pprint(self, parameter_s=''):
2520 """Toggle pretty printing on/off."""
2520 """Toggle pretty printing on/off."""
2521
2521
2522 self.shell.pprint = 1 - self.shell.pprint
2522 self.shell.pprint = 1 - self.shell.pprint
2523 print 'Pretty printing has been turned', \
2523 print 'Pretty printing has been turned', \
2524 ['OFF','ON'][self.shell.pprint]
2524 ['OFF','ON'][self.shell.pprint]
2525
2525
2526 def magic_exit(self, parameter_s=''):
2526 def magic_exit(self, parameter_s=''):
2527 """Exit IPython, confirming if configured to do so.
2527 """Exit IPython, confirming if configured to do so.
2528
2528
2529 You can configure whether IPython asks for confirmation upon exit by
2529 You can configure whether IPython asks for confirmation upon exit by
2530 setting the confirm_exit flag in the ipythonrc file."""
2530 setting the confirm_exit flag in the ipythonrc file."""
2531
2531
2532 self.shell.exit()
2532 self.shell.exit()
2533
2533
2534 def magic_quit(self, parameter_s=''):
2534 def magic_quit(self, parameter_s=''):
2535 """Exit IPython, confirming if configured to do so (like %exit)"""
2535 """Exit IPython, confirming if configured to do so (like %exit)"""
2536
2536
2537 self.shell.exit()
2537 self.shell.exit()
2538
2538
2539 def magic_Exit(self, parameter_s=''):
2539 def magic_Exit(self, parameter_s=''):
2540 """Exit IPython without confirmation."""
2540 """Exit IPython without confirmation."""
2541
2541
2542 self.shell.ask_exit()
2542 self.shell.ask_exit()
2543
2543
2544 #......................................................................
2544 #......................................................................
2545 # Functions to implement unix shell-type things
2545 # Functions to implement unix shell-type things
2546
2546
2547 @testdec.skip_doctest
2547 @testdec.skip_doctest
2548 def magic_alias(self, parameter_s = ''):
2548 def magic_alias(self, parameter_s = ''):
2549 """Define an alias for a system command.
2549 """Define an alias for a system command.
2550
2550
2551 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2551 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2552
2552
2553 Then, typing 'alias_name params' will execute the system command 'cmd
2553 Then, typing 'alias_name params' will execute the system command 'cmd
2554 params' (from your underlying operating system).
2554 params' (from your underlying operating system).
2555
2555
2556 Aliases have lower precedence than magic functions and Python normal
2556 Aliases have lower precedence than magic functions and Python normal
2557 variables, so if 'foo' is both a Python variable and an alias, the
2557 variables, so if 'foo' is both a Python variable and an alias, the
2558 alias can not be executed until 'del foo' removes the Python variable.
2558 alias can not be executed until 'del foo' removes the Python variable.
2559
2559
2560 You can use the %l specifier in an alias definition to represent the
2560 You can use the %l specifier in an alias definition to represent the
2561 whole line when the alias is called. For example:
2561 whole line when the alias is called. For example:
2562
2562
2563 In [2]: alias all echo "Input in brackets: <%l>"
2563 In [2]: alias all echo "Input in brackets: <%l>"
2564 In [3]: all hello world
2564 In [3]: all hello world
2565 Input in brackets: <hello world>
2565 Input in brackets: <hello world>
2566
2566
2567 You can also define aliases with parameters using %s specifiers (one
2567 You can also define aliases with parameters using %s specifiers (one
2568 per parameter):
2568 per parameter):
2569
2569
2570 In [1]: alias parts echo first %s second %s
2570 In [1]: alias parts echo first %s second %s
2571 In [2]: %parts A B
2571 In [2]: %parts A B
2572 first A second B
2572 first A second B
2573 In [3]: %parts A
2573 In [3]: %parts A
2574 Incorrect number of arguments: 2 expected.
2574 Incorrect number of arguments: 2 expected.
2575 parts is an alias to: 'echo first %s second %s'
2575 parts is an alias to: 'echo first %s second %s'
2576
2576
2577 Note that %l and %s are mutually exclusive. You can only use one or
2577 Note that %l and %s are mutually exclusive. You can only use one or
2578 the other in your aliases.
2578 the other in your aliases.
2579
2579
2580 Aliases expand Python variables just like system calls using ! or !!
2580 Aliases expand Python variables just like system calls using ! or !!
2581 do: all expressions prefixed with '$' get expanded. For details of
2581 do: all expressions prefixed with '$' get expanded. For details of
2582 the semantic rules, see PEP-215:
2582 the semantic rules, see PEP-215:
2583 http://www.python.org/peps/pep-0215.html. This is the library used by
2583 http://www.python.org/peps/pep-0215.html. This is the library used by
2584 IPython for variable expansion. If you want to access a true shell
2584 IPython for variable expansion. If you want to access a true shell
2585 variable, an extra $ is necessary to prevent its expansion by IPython:
2585 variable, an extra $ is necessary to prevent its expansion by IPython:
2586
2586
2587 In [6]: alias show echo
2587 In [6]: alias show echo
2588 In [7]: PATH='A Python string'
2588 In [7]: PATH='A Python string'
2589 In [8]: show $PATH
2589 In [8]: show $PATH
2590 A Python string
2590 A Python string
2591 In [9]: show $$PATH
2591 In [9]: show $$PATH
2592 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2592 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2593
2593
2594 You can use the alias facility to acess all of $PATH. See the %rehash
2594 You can use the alias facility to acess all of $PATH. See the %rehash
2595 and %rehashx functions, which automatically create aliases for the
2595 and %rehashx functions, which automatically create aliases for the
2596 contents of your $PATH.
2596 contents of your $PATH.
2597
2597
2598 If called with no parameters, %alias prints the current alias table."""
2598 If called with no parameters, %alias prints the current alias table."""
2599
2599
2600 par = parameter_s.strip()
2600 par = parameter_s.strip()
2601 if not par:
2601 if not par:
2602 stored = self.db.get('stored_aliases', {} )
2602 stored = self.db.get('stored_aliases', {} )
2603 aliases = sorted(self.shell.alias_manager.aliases)
2603 aliases = sorted(self.shell.alias_manager.aliases)
2604 # for k, v in stored:
2604 # for k, v in stored:
2605 # atab.append(k, v[0])
2605 # atab.append(k, v[0])
2606
2606
2607 print "Total number of aliases:", len(aliases)
2607 print "Total number of aliases:", len(aliases)
2608 return aliases
2608 return aliases
2609
2609
2610 # Now try to define a new one
2610 # Now try to define a new one
2611 try:
2611 try:
2612 alias,cmd = par.split(None, 1)
2612 alias,cmd = par.split(None, 1)
2613 except:
2613 except:
2614 print oinspect.getdoc(self.magic_alias)
2614 print oinspect.getdoc(self.magic_alias)
2615 else:
2615 else:
2616 self.shell.alias_manager.soft_define_alias(alias, cmd)
2616 self.shell.alias_manager.soft_define_alias(alias, cmd)
2617 # end magic_alias
2617 # end magic_alias
2618
2618
2619 def magic_unalias(self, parameter_s = ''):
2619 def magic_unalias(self, parameter_s = ''):
2620 """Remove an alias"""
2620 """Remove an alias"""
2621
2621
2622 aname = parameter_s.strip()
2622 aname = parameter_s.strip()
2623 self.shell.alias_manager.undefine_alias(aname)
2623 self.shell.alias_manager.undefine_alias(aname)
2624 stored = self.db.get('stored_aliases', {} )
2624 stored = self.db.get('stored_aliases', {} )
2625 if aname in stored:
2625 if aname in stored:
2626 print "Removing %stored alias",aname
2626 print "Removing %stored alias",aname
2627 del stored[aname]
2627 del stored[aname]
2628 self.db['stored_aliases'] = stored
2628 self.db['stored_aliases'] = stored
2629
2629
2630
2630
2631 def magic_rehashx(self, parameter_s = ''):
2631 def magic_rehashx(self, parameter_s = ''):
2632 """Update the alias table with all executable files in $PATH.
2632 """Update the alias table with all executable files in $PATH.
2633
2633
2634 This version explicitly checks that every entry in $PATH is a file
2634 This version explicitly checks that every entry in $PATH is a file
2635 with execute access (os.X_OK), so it is much slower than %rehash.
2635 with execute access (os.X_OK), so it is much slower than %rehash.
2636
2636
2637 Under Windows, it checks executability as a match agains a
2637 Under Windows, it checks executability as a match agains a
2638 '|'-separated string of extensions, stored in the IPython config
2638 '|'-separated string of extensions, stored in the IPython config
2639 variable win_exec_ext. This defaults to 'exe|com|bat'.
2639 variable win_exec_ext. This defaults to 'exe|com|bat'.
2640
2640
2641 This function also resets the root module cache of module completer,
2641 This function also resets the root module cache of module completer,
2642 used on slow filesystems.
2642 used on slow filesystems.
2643 """
2643 """
2644 from IPython.core.alias import InvalidAliasError
2644 from IPython.core.alias import InvalidAliasError
2645
2645
2646 # for the benefit of module completer in ipy_completers.py
2646 # for the benefit of module completer in ipy_completers.py
2647 del self.db['rootmodules']
2647 del self.db['rootmodules']
2648
2648
2649 path = [os.path.abspath(os.path.expanduser(p)) for p in
2649 path = [os.path.abspath(os.path.expanduser(p)) for p in
2650 os.environ.get('PATH','').split(os.pathsep)]
2650 os.environ.get('PATH','').split(os.pathsep)]
2651 path = filter(os.path.isdir,path)
2651 path = filter(os.path.isdir,path)
2652
2652
2653 syscmdlist = []
2653 syscmdlist = []
2654 # Now define isexec in a cross platform manner.
2654 # Now define isexec in a cross platform manner.
2655 if os.name == 'posix':
2655 if os.name == 'posix':
2656 isexec = lambda fname:os.path.isfile(fname) and \
2656 isexec = lambda fname:os.path.isfile(fname) and \
2657 os.access(fname,os.X_OK)
2657 os.access(fname,os.X_OK)
2658 else:
2658 else:
2659 try:
2659 try:
2660 winext = os.environ['pathext'].replace(';','|').replace('.','')
2660 winext = os.environ['pathext'].replace(';','|').replace('.','')
2661 except KeyError:
2661 except KeyError:
2662 winext = 'exe|com|bat|py'
2662 winext = 'exe|com|bat|py'
2663 if 'py' not in winext:
2663 if 'py' not in winext:
2664 winext += '|py'
2664 winext += '|py'
2665 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2665 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2666 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2666 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2667 savedir = os.getcwd()
2667 savedir = os.getcwd()
2668
2668
2669 # Now walk the paths looking for executables to alias.
2669 # Now walk the paths looking for executables to alias.
2670 try:
2670 try:
2671 # write the whole loop for posix/Windows so we don't have an if in
2671 # write the whole loop for posix/Windows so we don't have an if in
2672 # the innermost part
2672 # the innermost part
2673 if os.name == 'posix':
2673 if os.name == 'posix':
2674 for pdir in path:
2674 for pdir in path:
2675 os.chdir(pdir)
2675 os.chdir(pdir)
2676 for ff in os.listdir(pdir):
2676 for ff in os.listdir(pdir):
2677 if isexec(ff):
2677 if isexec(ff):
2678 try:
2678 try:
2679 # Removes dots from the name since ipython
2679 # Removes dots from the name since ipython
2680 # will assume names with dots to be python.
2680 # will assume names with dots to be python.
2681 self.shell.alias_manager.define_alias(
2681 self.shell.alias_manager.define_alias(
2682 ff.replace('.',''), ff)
2682 ff.replace('.',''), ff)
2683 except InvalidAliasError:
2683 except InvalidAliasError:
2684 pass
2684 pass
2685 else:
2685 else:
2686 syscmdlist.append(ff)
2686 syscmdlist.append(ff)
2687 else:
2687 else:
2688 for pdir in path:
2688 for pdir in path:
2689 os.chdir(pdir)
2689 os.chdir(pdir)
2690 for ff in os.listdir(pdir):
2690 for ff in os.listdir(pdir):
2691 base, ext = os.path.splitext(ff)
2691 base, ext = os.path.splitext(ff)
2692 if isexec(ff) and base.lower() not in self.shell.no_alias:
2692 if isexec(ff) and base.lower() not in self.shell.no_alias:
2693 if ext.lower() == '.exe':
2693 if ext.lower() == '.exe':
2694 ff = base
2694 ff = base
2695 try:
2695 try:
2696 # Removes dots from the name since ipython
2696 # Removes dots from the name since ipython
2697 # will assume names with dots to be python.
2697 # will assume names with dots to be python.
2698 self.shell.alias_manager.define_alias(
2698 self.shell.alias_manager.define_alias(
2699 base.lower().replace('.',''), ff)
2699 base.lower().replace('.',''), ff)
2700 except InvalidAliasError:
2700 except InvalidAliasError:
2701 pass
2701 pass
2702 syscmdlist.append(ff)
2702 syscmdlist.append(ff)
2703 db = self.db
2703 db = self.db
2704 db['syscmdlist'] = syscmdlist
2704 db['syscmdlist'] = syscmdlist
2705 finally:
2705 finally:
2706 os.chdir(savedir)
2706 os.chdir(savedir)
2707
2707
2708 def magic_pwd(self, parameter_s = ''):
2708 def magic_pwd(self, parameter_s = ''):
2709 """Return the current working directory path."""
2709 """Return the current working directory path."""
2710 return os.getcwd()
2710 return os.getcwd()
2711
2711
2712 def magic_cd(self, parameter_s=''):
2712 def magic_cd(self, parameter_s=''):
2713 """Change the current working directory.
2713 """Change the current working directory.
2714
2714
2715 This command automatically maintains an internal list of directories
2715 This command automatically maintains an internal list of directories
2716 you visit during your IPython session, in the variable _dh. The
2716 you visit during your IPython session, in the variable _dh. The
2717 command %dhist shows this history nicely formatted. You can also
2717 command %dhist shows this history nicely formatted. You can also
2718 do 'cd -<tab>' to see directory history conveniently.
2718 do 'cd -<tab>' to see directory history conveniently.
2719
2719
2720 Usage:
2720 Usage:
2721
2721
2722 cd 'dir': changes to directory 'dir'.
2722 cd 'dir': changes to directory 'dir'.
2723
2723
2724 cd -: changes to the last visited directory.
2724 cd -: changes to the last visited directory.
2725
2725
2726 cd -<n>: changes to the n-th directory in the directory history.
2726 cd -<n>: changes to the n-th directory in the directory history.
2727
2727
2728 cd --foo: change to directory that matches 'foo' in history
2728 cd --foo: change to directory that matches 'foo' in history
2729
2729
2730 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2730 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2731 (note: cd <bookmark_name> is enough if there is no
2731 (note: cd <bookmark_name> is enough if there is no
2732 directory <bookmark_name>, but a bookmark with the name exists.)
2732 directory <bookmark_name>, but a bookmark with the name exists.)
2733 'cd -b <tab>' allows you to tab-complete bookmark names.
2733 'cd -b <tab>' allows you to tab-complete bookmark names.
2734
2734
2735 Options:
2735 Options:
2736
2736
2737 -q: quiet. Do not print the working directory after the cd command is
2737 -q: quiet. Do not print the working directory after the cd command is
2738 executed. By default IPython's cd command does print this directory,
2738 executed. By default IPython's cd command does print this directory,
2739 since the default prompts do not display path information.
2739 since the default prompts do not display path information.
2740
2740
2741 Note that !cd doesn't work for this purpose because the shell where
2741 Note that !cd doesn't work for this purpose because the shell where
2742 !command runs is immediately discarded after executing 'command'."""
2742 !command runs is immediately discarded after executing 'command'."""
2743
2743
2744 parameter_s = parameter_s.strip()
2744 parameter_s = parameter_s.strip()
2745 #bkms = self.shell.persist.get("bookmarks",{})
2745 #bkms = self.shell.persist.get("bookmarks",{})
2746
2746
2747 oldcwd = os.getcwd()
2747 oldcwd = os.getcwd()
2748 numcd = re.match(r'(-)(\d+)$',parameter_s)
2748 numcd = re.match(r'(-)(\d+)$',parameter_s)
2749 # jump in directory history by number
2749 # jump in directory history by number
2750 if numcd:
2750 if numcd:
2751 nn = int(numcd.group(2))
2751 nn = int(numcd.group(2))
2752 try:
2752 try:
2753 ps = self.shell.user_ns['_dh'][nn]
2753 ps = self.shell.user_ns['_dh'][nn]
2754 except IndexError:
2754 except IndexError:
2755 print 'The requested directory does not exist in history.'
2755 print 'The requested directory does not exist in history.'
2756 return
2756 return
2757 else:
2757 else:
2758 opts = {}
2758 opts = {}
2759 elif parameter_s.startswith('--'):
2759 elif parameter_s.startswith('--'):
2760 ps = None
2760 ps = None
2761 fallback = None
2761 fallback = None
2762 pat = parameter_s[2:]
2762 pat = parameter_s[2:]
2763 dh = self.shell.user_ns['_dh']
2763 dh = self.shell.user_ns['_dh']
2764 # first search only by basename (last component)
2764 # first search only by basename (last component)
2765 for ent in reversed(dh):
2765 for ent in reversed(dh):
2766 if pat in os.path.basename(ent) and os.path.isdir(ent):
2766 if pat in os.path.basename(ent) and os.path.isdir(ent):
2767 ps = ent
2767 ps = ent
2768 break
2768 break
2769
2769
2770 if fallback is None and pat in ent and os.path.isdir(ent):
2770 if fallback is None and pat in ent and os.path.isdir(ent):
2771 fallback = ent
2771 fallback = ent
2772
2772
2773 # if we have no last part match, pick the first full path match
2773 # if we have no last part match, pick the first full path match
2774 if ps is None:
2774 if ps is None:
2775 ps = fallback
2775 ps = fallback
2776
2776
2777 if ps is None:
2777 if ps is None:
2778 print "No matching entry in directory history"
2778 print "No matching entry in directory history"
2779 return
2779 return
2780 else:
2780 else:
2781 opts = {}
2781 opts = {}
2782
2782
2783
2783
2784 else:
2784 else:
2785 #turn all non-space-escaping backslashes to slashes,
2785 #turn all non-space-escaping backslashes to slashes,
2786 # for c:\windows\directory\names\
2786 # for c:\windows\directory\names\
2787 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2787 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2788 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2788 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2789 # jump to previous
2789 # jump to previous
2790 if ps == '-':
2790 if ps == '-':
2791 try:
2791 try:
2792 ps = self.shell.user_ns['_dh'][-2]
2792 ps = self.shell.user_ns['_dh'][-2]
2793 except IndexError:
2793 except IndexError:
2794 raise UsageError('%cd -: No previous directory to change to.')
2794 raise UsageError('%cd -: No previous directory to change to.')
2795 # jump to bookmark if needed
2795 # jump to bookmark if needed
2796 else:
2796 else:
2797 if not os.path.isdir(ps) or opts.has_key('b'):
2797 if not os.path.isdir(ps) or opts.has_key('b'):
2798 bkms = self.db.get('bookmarks', {})
2798 bkms = self.db.get('bookmarks', {})
2799
2799
2800 if bkms.has_key(ps):
2800 if bkms.has_key(ps):
2801 target = bkms[ps]
2801 target = bkms[ps]
2802 print '(bookmark:%s) -> %s' % (ps,target)
2802 print '(bookmark:%s) -> %s' % (ps,target)
2803 ps = target
2803 ps = target
2804 else:
2804 else:
2805 if opts.has_key('b'):
2805 if opts.has_key('b'):
2806 raise UsageError("Bookmark '%s' not found. "
2806 raise UsageError("Bookmark '%s' not found. "
2807 "Use '%%bookmark -l' to see your bookmarks." % ps)
2807 "Use '%%bookmark -l' to see your bookmarks." % ps)
2808
2808
2809 # at this point ps should point to the target dir
2809 # at this point ps should point to the target dir
2810 if ps:
2810 if ps:
2811 try:
2811 try:
2812 os.chdir(os.path.expanduser(ps))
2812 os.chdir(os.path.expanduser(ps))
2813 if self.shell.term_title:
2813 if self.shell.term_title:
2814 platutils.set_term_title('IPython: ' + abbrev_cwd())
2814 platutils.set_term_title('IPython: ' + abbrev_cwd())
2815 except OSError:
2815 except OSError:
2816 print sys.exc_info()[1]
2816 print sys.exc_info()[1]
2817 else:
2817 else:
2818 cwd = os.getcwd()
2818 cwd = os.getcwd()
2819 dhist = self.shell.user_ns['_dh']
2819 dhist = self.shell.user_ns['_dh']
2820 if oldcwd != cwd:
2820 if oldcwd != cwd:
2821 dhist.append(cwd)
2821 dhist.append(cwd)
2822 self.db['dhist'] = compress_dhist(dhist)[-100:]
2822 self.db['dhist'] = compress_dhist(dhist)[-100:]
2823
2823
2824 else:
2824 else:
2825 os.chdir(self.shell.home_dir)
2825 os.chdir(self.shell.home_dir)
2826 if self.shell.term_title:
2826 if self.shell.term_title:
2827 platutils.set_term_title('IPython: ' + '~')
2827 platutils.set_term_title('IPython: ' + '~')
2828 cwd = os.getcwd()
2828 cwd = os.getcwd()
2829 dhist = self.shell.user_ns['_dh']
2829 dhist = self.shell.user_ns['_dh']
2830
2830
2831 if oldcwd != cwd:
2831 if oldcwd != cwd:
2832 dhist.append(cwd)
2832 dhist.append(cwd)
2833 self.db['dhist'] = compress_dhist(dhist)[-100:]
2833 self.db['dhist'] = compress_dhist(dhist)[-100:]
2834 if not 'q' in opts and self.shell.user_ns['_dh']:
2834 if not 'q' in opts and self.shell.user_ns['_dh']:
2835 print self.shell.user_ns['_dh'][-1]
2835 print self.shell.user_ns['_dh'][-1]
2836
2836
2837
2837
2838 def magic_env(self, parameter_s=''):
2838 def magic_env(self, parameter_s=''):
2839 """List environment variables."""
2839 """List environment variables."""
2840
2840
2841 return os.environ.data
2841 return os.environ.data
2842
2842
2843 def magic_pushd(self, parameter_s=''):
2843 def magic_pushd(self, parameter_s=''):
2844 """Place the current dir on stack and change directory.
2844 """Place the current dir on stack and change directory.
2845
2845
2846 Usage:\\
2846 Usage:\\
2847 %pushd ['dirname']
2847 %pushd ['dirname']
2848 """
2848 """
2849
2849
2850 dir_s = self.shell.dir_stack
2850 dir_s = self.shell.dir_stack
2851 tgt = os.path.expanduser(parameter_s)
2851 tgt = os.path.expanduser(parameter_s)
2852 cwd = os.getcwd().replace(self.home_dir,'~')
2852 cwd = os.getcwd().replace(self.home_dir,'~')
2853 if tgt:
2853 if tgt:
2854 self.magic_cd(parameter_s)
2854 self.magic_cd(parameter_s)
2855 dir_s.insert(0,cwd)
2855 dir_s.insert(0,cwd)
2856 return self.magic_dirs()
2856 return self.magic_dirs()
2857
2857
2858 def magic_popd(self, parameter_s=''):
2858 def magic_popd(self, parameter_s=''):
2859 """Change to directory popped off the top of the stack.
2859 """Change to directory popped off the top of the stack.
2860 """
2860 """
2861 if not self.shell.dir_stack:
2861 if not self.shell.dir_stack:
2862 raise UsageError("%popd on empty stack")
2862 raise UsageError("%popd on empty stack")
2863 top = self.shell.dir_stack.pop(0)
2863 top = self.shell.dir_stack.pop(0)
2864 self.magic_cd(top)
2864 self.magic_cd(top)
2865 print "popd ->",top
2865 print "popd ->",top
2866
2866
2867 def magic_dirs(self, parameter_s=''):
2867 def magic_dirs(self, parameter_s=''):
2868 """Return the current directory stack."""
2868 """Return the current directory stack."""
2869
2869
2870 return self.shell.dir_stack
2870 return self.shell.dir_stack
2871
2871
2872 def magic_dhist(self, parameter_s=''):
2872 def magic_dhist(self, parameter_s=''):
2873 """Print your history of visited directories.
2873 """Print your history of visited directories.
2874
2874
2875 %dhist -> print full history\\
2875 %dhist -> print full history\\
2876 %dhist n -> print last n entries only\\
2876 %dhist n -> print last n entries only\\
2877 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2877 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2878
2878
2879 This history is automatically maintained by the %cd command, and
2879 This history is automatically maintained by the %cd command, and
2880 always available as the global list variable _dh. You can use %cd -<n>
2880 always available as the global list variable _dh. You can use %cd -<n>
2881 to go to directory number <n>.
2881 to go to directory number <n>.
2882
2882
2883 Note that most of time, you should view directory history by entering
2883 Note that most of time, you should view directory history by entering
2884 cd -<TAB>.
2884 cd -<TAB>.
2885
2885
2886 """
2886 """
2887
2887
2888 dh = self.shell.user_ns['_dh']
2888 dh = self.shell.user_ns['_dh']
2889 if parameter_s:
2889 if parameter_s:
2890 try:
2890 try:
2891 args = map(int,parameter_s.split())
2891 args = map(int,parameter_s.split())
2892 except:
2892 except:
2893 self.arg_err(Magic.magic_dhist)
2893 self.arg_err(Magic.magic_dhist)
2894 return
2894 return
2895 if len(args) == 1:
2895 if len(args) == 1:
2896 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2896 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2897 elif len(args) == 2:
2897 elif len(args) == 2:
2898 ini,fin = args
2898 ini,fin = args
2899 else:
2899 else:
2900 self.arg_err(Magic.magic_dhist)
2900 self.arg_err(Magic.magic_dhist)
2901 return
2901 return
2902 else:
2902 else:
2903 ini,fin = 0,len(dh)
2903 ini,fin = 0,len(dh)
2904 nlprint(dh,
2904 nlprint(dh,
2905 header = 'Directory history (kept in _dh)',
2905 header = 'Directory history (kept in _dh)',
2906 start=ini,stop=fin)
2906 start=ini,stop=fin)
2907
2907
2908 @testdec.skip_doctest
2908 @testdec.skip_doctest
2909 def magic_sc(self, parameter_s=''):
2909 def magic_sc(self, parameter_s=''):
2910 """Shell capture - execute a shell command and capture its output.
2910 """Shell capture - execute a shell command and capture its output.
2911
2911
2912 DEPRECATED. Suboptimal, retained for backwards compatibility.
2912 DEPRECATED. Suboptimal, retained for backwards compatibility.
2913
2913
2914 You should use the form 'var = !command' instead. Example:
2914 You should use the form 'var = !command' instead. Example:
2915
2915
2916 "%sc -l myfiles = ls ~" should now be written as
2916 "%sc -l myfiles = ls ~" should now be written as
2917
2917
2918 "myfiles = !ls ~"
2918 "myfiles = !ls ~"
2919
2919
2920 myfiles.s, myfiles.l and myfiles.n still apply as documented
2920 myfiles.s, myfiles.l and myfiles.n still apply as documented
2921 below.
2921 below.
2922
2922
2923 --
2923 --
2924 %sc [options] varname=command
2924 %sc [options] varname=command
2925
2925
2926 IPython will run the given command using commands.getoutput(), and
2926 IPython will run the given command using commands.getoutput(), and
2927 will then update the user's interactive namespace with a variable
2927 will then update the user's interactive namespace with a variable
2928 called varname, containing the value of the call. Your command can
2928 called varname, containing the value of the call. Your command can
2929 contain shell wildcards, pipes, etc.
2929 contain shell wildcards, pipes, etc.
2930
2930
2931 The '=' sign in the syntax is mandatory, and the variable name you
2931 The '=' sign in the syntax is mandatory, and the variable name you
2932 supply must follow Python's standard conventions for valid names.
2932 supply must follow Python's standard conventions for valid names.
2933
2933
2934 (A special format without variable name exists for internal use)
2934 (A special format without variable name exists for internal use)
2935
2935
2936 Options:
2936 Options:
2937
2937
2938 -l: list output. Split the output on newlines into a list before
2938 -l: list output. Split the output on newlines into a list before
2939 assigning it to the given variable. By default the output is stored
2939 assigning it to the given variable. By default the output is stored
2940 as a single string.
2940 as a single string.
2941
2941
2942 -v: verbose. Print the contents of the variable.
2942 -v: verbose. Print the contents of the variable.
2943
2943
2944 In most cases you should not need to split as a list, because the
2944 In most cases you should not need to split as a list, because the
2945 returned value is a special type of string which can automatically
2945 returned value is a special type of string which can automatically
2946 provide its contents either as a list (split on newlines) or as a
2946 provide its contents either as a list (split on newlines) or as a
2947 space-separated string. These are convenient, respectively, either
2947 space-separated string. These are convenient, respectively, either
2948 for sequential processing or to be passed to a shell command.
2948 for sequential processing or to be passed to a shell command.
2949
2949
2950 For example:
2950 For example:
2951
2951
2952 # all-random
2952 # all-random
2953
2953
2954 # Capture into variable a
2954 # Capture into variable a
2955 In [1]: sc a=ls *py
2955 In [1]: sc a=ls *py
2956
2956
2957 # a is a string with embedded newlines
2957 # a is a string with embedded newlines
2958 In [2]: a
2958 In [2]: a
2959 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2959 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2960
2960
2961 # which can be seen as a list:
2961 # which can be seen as a list:
2962 In [3]: a.l
2962 In [3]: a.l
2963 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2963 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2964
2964
2965 # or as a whitespace-separated string:
2965 # or as a whitespace-separated string:
2966 In [4]: a.s
2966 In [4]: a.s
2967 Out[4]: 'setup.py win32_manual_post_install.py'
2967 Out[4]: 'setup.py win32_manual_post_install.py'
2968
2968
2969 # a.s is useful to pass as a single command line:
2969 # a.s is useful to pass as a single command line:
2970 In [5]: !wc -l $a.s
2970 In [5]: !wc -l $a.s
2971 146 setup.py
2971 146 setup.py
2972 130 win32_manual_post_install.py
2972 130 win32_manual_post_install.py
2973 276 total
2973 276 total
2974
2974
2975 # while the list form is useful to loop over:
2975 # while the list form is useful to loop over:
2976 In [6]: for f in a.l:
2976 In [6]: for f in a.l:
2977 ...: !wc -l $f
2977 ...: !wc -l $f
2978 ...:
2978 ...:
2979 146 setup.py
2979 146 setup.py
2980 130 win32_manual_post_install.py
2980 130 win32_manual_post_install.py
2981
2981
2982 Similiarly, the lists returned by the -l option are also special, in
2982 Similiarly, the lists returned by the -l option are also special, in
2983 the sense that you can equally invoke the .s attribute on them to
2983 the sense that you can equally invoke the .s attribute on them to
2984 automatically get a whitespace-separated string from their contents:
2984 automatically get a whitespace-separated string from their contents:
2985
2985
2986 In [7]: sc -l b=ls *py
2986 In [7]: sc -l b=ls *py
2987
2987
2988 In [8]: b
2988 In [8]: b
2989 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2989 Out[8]: ['setup.py', 'win32_manual_post_install.py']
2990
2990
2991 In [9]: b.s
2991 In [9]: b.s
2992 Out[9]: 'setup.py win32_manual_post_install.py'
2992 Out[9]: 'setup.py win32_manual_post_install.py'
2993
2993
2994 In summary, both the lists and strings used for ouptut capture have
2994 In summary, both the lists and strings used for ouptut capture have
2995 the following special attributes:
2995 the following special attributes:
2996
2996
2997 .l (or .list) : value as list.
2997 .l (or .list) : value as list.
2998 .n (or .nlstr): value as newline-separated string.
2998 .n (or .nlstr): value as newline-separated string.
2999 .s (or .spstr): value as space-separated string.
2999 .s (or .spstr): value as space-separated string.
3000 """
3000 """
3001
3001
3002 opts,args = self.parse_options(parameter_s,'lv')
3002 opts,args = self.parse_options(parameter_s,'lv')
3003 # Try to get a variable name and command to run
3003 # Try to get a variable name and command to run
3004 try:
3004 try:
3005 # the variable name must be obtained from the parse_options
3005 # the variable name must be obtained from the parse_options
3006 # output, which uses shlex.split to strip options out.
3006 # output, which uses shlex.split to strip options out.
3007 var,_ = args.split('=',1)
3007 var,_ = args.split('=',1)
3008 var = var.strip()
3008 var = var.strip()
3009 # But the the command has to be extracted from the original input
3009 # But the the command has to be extracted from the original input
3010 # parameter_s, not on what parse_options returns, to avoid the
3010 # parameter_s, not on what parse_options returns, to avoid the
3011 # quote stripping which shlex.split performs on it.
3011 # quote stripping which shlex.split performs on it.
3012 _,cmd = parameter_s.split('=',1)
3012 _,cmd = parameter_s.split('=',1)
3013 except ValueError:
3013 except ValueError:
3014 var,cmd = '',''
3014 var,cmd = '',''
3015 # If all looks ok, proceed
3015 # If all looks ok, proceed
3016 out,err = self.shell.getoutputerror(cmd)
3016 out,err = self.shell.getoutputerror(cmd)
3017 if err:
3017 if err:
3018 print >> Term.cerr,err
3018 print >> Term.cerr,err
3019 if opts.has_key('l'):
3019 if opts.has_key('l'):
3020 out = SList(out.split('\n'))
3020 out = SList(out.split('\n'))
3021 else:
3021 else:
3022 out = LSString(out)
3022 out = LSString(out)
3023 if opts.has_key('v'):
3023 if opts.has_key('v'):
3024 print '%s ==\n%s' % (var,pformat(out))
3024 print '%s ==\n%s' % (var,pformat(out))
3025 if var:
3025 if var:
3026 self.shell.user_ns.update({var:out})
3026 self.shell.user_ns.update({var:out})
3027 else:
3027 else:
3028 return out
3028 return out
3029
3029
3030 def magic_sx(self, parameter_s=''):
3030 def magic_sx(self, parameter_s=''):
3031 """Shell execute - run a shell command and capture its output.
3031 """Shell execute - run a shell command and capture its output.
3032
3032
3033 %sx command
3033 %sx command
3034
3034
3035 IPython will run the given command using commands.getoutput(), and
3035 IPython will run the given command using commands.getoutput(), and
3036 return the result formatted as a list (split on '\\n'). Since the
3036 return the result formatted as a list (split on '\\n'). Since the
3037 output is _returned_, it will be stored in ipython's regular output
3037 output is _returned_, it will be stored in ipython's regular output
3038 cache Out[N] and in the '_N' automatic variables.
3038 cache Out[N] and in the '_N' automatic variables.
3039
3039
3040 Notes:
3040 Notes:
3041
3041
3042 1) If an input line begins with '!!', then %sx is automatically
3042 1) If an input line begins with '!!', then %sx is automatically
3043 invoked. That is, while:
3043 invoked. That is, while:
3044 !ls
3044 !ls
3045 causes ipython to simply issue system('ls'), typing
3045 causes ipython to simply issue system('ls'), typing
3046 !!ls
3046 !!ls
3047 is a shorthand equivalent to:
3047 is a shorthand equivalent to:
3048 %sx ls
3048 %sx ls
3049
3049
3050 2) %sx differs from %sc in that %sx automatically splits into a list,
3050 2) %sx differs from %sc in that %sx automatically splits into a list,
3051 like '%sc -l'. The reason for this is to make it as easy as possible
3051 like '%sc -l'. The reason for this is to make it as easy as possible
3052 to process line-oriented shell output via further python commands.
3052 to process line-oriented shell output via further python commands.
3053 %sc is meant to provide much finer control, but requires more
3053 %sc is meant to provide much finer control, but requires more
3054 typing.
3054 typing.
3055
3055
3056 3) Just like %sc -l, this is a list with special attributes:
3056 3) Just like %sc -l, this is a list with special attributes:
3057
3057
3058 .l (or .list) : value as list.
3058 .l (or .list) : value as list.
3059 .n (or .nlstr): value as newline-separated string.
3059 .n (or .nlstr): value as newline-separated string.
3060 .s (or .spstr): value as whitespace-separated string.
3060 .s (or .spstr): value as whitespace-separated string.
3061
3061
3062 This is very useful when trying to use such lists as arguments to
3062 This is very useful when trying to use such lists as arguments to
3063 system commands."""
3063 system commands."""
3064
3064
3065 if parameter_s:
3065 if parameter_s:
3066 out,err = self.shell.getoutputerror(parameter_s)
3066 out,err = self.shell.getoutputerror(parameter_s)
3067 if err:
3067 if err:
3068 print >> Term.cerr,err
3068 print >> Term.cerr,err
3069 return SList(out.split('\n'))
3069 return SList(out.split('\n'))
3070
3070
3071 def magic_bg(self, parameter_s=''):
3071 def magic_bg(self, parameter_s=''):
3072 """Run a job in the background, in a separate thread.
3072 """Run a job in the background, in a separate thread.
3073
3073
3074 For example,
3074 For example,
3075
3075
3076 %bg myfunc(x,y,z=1)
3076 %bg myfunc(x,y,z=1)
3077
3077
3078 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3078 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3079 execution starts, a message will be printed indicating the job
3079 execution starts, a message will be printed indicating the job
3080 number. If your job number is 5, you can use
3080 number. If your job number is 5, you can use
3081
3081
3082 myvar = jobs.result(5) or myvar = jobs[5].result
3082 myvar = jobs.result(5) or myvar = jobs[5].result
3083
3083
3084 to assign this result to variable 'myvar'.
3084 to assign this result to variable 'myvar'.
3085
3085
3086 IPython has a job manager, accessible via the 'jobs' object. You can
3086 IPython has a job manager, accessible via the 'jobs' object. You can
3087 type jobs? to get more information about it, and use jobs.<TAB> to see
3087 type jobs? to get more information about it, and use jobs.<TAB> to see
3088 its attributes. All attributes not starting with an underscore are
3088 its attributes. All attributes not starting with an underscore are
3089 meant for public use.
3089 meant for public use.
3090
3090
3091 In particular, look at the jobs.new() method, which is used to create
3091 In particular, look at the jobs.new() method, which is used to create
3092 new jobs. This magic %bg function is just a convenience wrapper
3092 new jobs. This magic %bg function is just a convenience wrapper
3093 around jobs.new(), for expression-based jobs. If you want to create a
3093 around jobs.new(), for expression-based jobs. If you want to create a
3094 new job with an explicit function object and arguments, you must call
3094 new job with an explicit function object and arguments, you must call
3095 jobs.new() directly.
3095 jobs.new() directly.
3096
3096
3097 The jobs.new docstring also describes in detail several important
3097 The jobs.new docstring also describes in detail several important
3098 caveats associated with a thread-based model for background job
3098 caveats associated with a thread-based model for background job
3099 execution. Type jobs.new? for details.
3099 execution. Type jobs.new? for details.
3100
3100
3101 You can check the status of all jobs with jobs.status().
3101 You can check the status of all jobs with jobs.status().
3102
3102
3103 The jobs variable is set by IPython into the Python builtin namespace.
3103 The jobs variable is set by IPython into the Python builtin namespace.
3104 If you ever declare a variable named 'jobs', you will shadow this
3104 If you ever declare a variable named 'jobs', you will shadow this
3105 name. You can either delete your global jobs variable to regain
3105 name. You can either delete your global jobs variable to regain
3106 access to the job manager, or make a new name and assign it manually
3106 access to the job manager, or make a new name and assign it manually
3107 to the manager (stored in IPython's namespace). For example, to
3107 to the manager (stored in IPython's namespace). For example, to
3108 assign the job manager to the Jobs name, use:
3108 assign the job manager to the Jobs name, use:
3109
3109
3110 Jobs = __builtins__.jobs"""
3110 Jobs = __builtins__.jobs"""
3111
3111
3112 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3112 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3113
3113
3114 def magic_r(self, parameter_s=''):
3114 def magic_r(self, parameter_s=''):
3115 """Repeat previous input.
3115 """Repeat previous input.
3116
3116
3117 Note: Consider using the more powerfull %rep instead!
3117 Note: Consider using the more powerfull %rep instead!
3118
3118
3119 If given an argument, repeats the previous command which starts with
3119 If given an argument, repeats the previous command which starts with
3120 the same string, otherwise it just repeats the previous input.
3120 the same string, otherwise it just repeats the previous input.
3121
3121
3122 Shell escaped commands (with ! as first character) are not recognized
3122 Shell escaped commands (with ! as first character) are not recognized
3123 by this system, only pure python code and magic commands.
3123 by this system, only pure python code and magic commands.
3124 """
3124 """
3125
3125
3126 start = parameter_s.strip()
3126 start = parameter_s.strip()
3127 esc_magic = ESC_MAGIC
3127 esc_magic = ESC_MAGIC
3128 # Identify magic commands even if automagic is on (which means
3128 # Identify magic commands even if automagic is on (which means
3129 # the in-memory version is different from that typed by the user).
3129 # the in-memory version is different from that typed by the user).
3130 if self.shell.automagic:
3130 if self.shell.automagic:
3131 start_magic = esc_magic+start
3131 start_magic = esc_magic+start
3132 else:
3132 else:
3133 start_magic = start
3133 start_magic = start
3134 # Look through the input history in reverse
3134 # Look through the input history in reverse
3135 for n in range(len(self.shell.input_hist)-2,0,-1):
3135 for n in range(len(self.shell.input_hist)-2,0,-1):
3136 input = self.shell.input_hist[n]
3136 input = self.shell.input_hist[n]
3137 # skip plain 'r' lines so we don't recurse to infinity
3137 # skip plain 'r' lines so we don't recurse to infinity
3138 if input != '_ip.magic("r")\n' and \
3138 if input != '_ip.magic("r")\n' and \
3139 (input.startswith(start) or input.startswith(start_magic)):
3139 (input.startswith(start) or input.startswith(start_magic)):
3140 #print 'match',`input` # dbg
3140 #print 'match',`input` # dbg
3141 print 'Executing:',input,
3141 print 'Executing:',input,
3142 self.shell.runlines(input)
3142 self.shell.runlines(input)
3143 return
3143 return
3144 print 'No previous input matching `%s` found.' % start
3144 print 'No previous input matching `%s` found.' % start
3145
3145
3146
3146
3147 def magic_bookmark(self, parameter_s=''):
3147 def magic_bookmark(self, parameter_s=''):
3148 """Manage IPython's bookmark system.
3148 """Manage IPython's bookmark system.
3149
3149
3150 %bookmark <name> - set bookmark to current dir
3150 %bookmark <name> - set bookmark to current dir
3151 %bookmark <name> <dir> - set bookmark to <dir>
3151 %bookmark <name> <dir> - set bookmark to <dir>
3152 %bookmark -l - list all bookmarks
3152 %bookmark -l - list all bookmarks
3153 %bookmark -d <name> - remove bookmark
3153 %bookmark -d <name> - remove bookmark
3154 %bookmark -r - remove all bookmarks
3154 %bookmark -r - remove all bookmarks
3155
3155
3156 You can later on access a bookmarked folder with:
3156 You can later on access a bookmarked folder with:
3157 %cd -b <name>
3157 %cd -b <name>
3158 or simply '%cd <name>' if there is no directory called <name> AND
3158 or simply '%cd <name>' if there is no directory called <name> AND
3159 there is such a bookmark defined.
3159 there is such a bookmark defined.
3160
3160
3161 Your bookmarks persist through IPython sessions, but they are
3161 Your bookmarks persist through IPython sessions, but they are
3162 associated with each profile."""
3162 associated with each profile."""
3163
3163
3164 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3164 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3165 if len(args) > 2:
3165 if len(args) > 2:
3166 raise UsageError("%bookmark: too many arguments")
3166 raise UsageError("%bookmark: too many arguments")
3167
3167
3168 bkms = self.db.get('bookmarks',{})
3168 bkms = self.db.get('bookmarks',{})
3169
3169
3170 if opts.has_key('d'):
3170 if opts.has_key('d'):
3171 try:
3171 try:
3172 todel = args[0]
3172 todel = args[0]
3173 except IndexError:
3173 except IndexError:
3174 raise UsageError(
3174 raise UsageError(
3175 "%bookmark -d: must provide a bookmark to delete")
3175 "%bookmark -d: must provide a bookmark to delete")
3176 else:
3176 else:
3177 try:
3177 try:
3178 del bkms[todel]
3178 del bkms[todel]
3179 except KeyError:
3179 except KeyError:
3180 raise UsageError(
3180 raise UsageError(
3181 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3181 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3182
3182
3183 elif opts.has_key('r'):
3183 elif opts.has_key('r'):
3184 bkms = {}
3184 bkms = {}
3185 elif opts.has_key('l'):
3185 elif opts.has_key('l'):
3186 bks = bkms.keys()
3186 bks = bkms.keys()
3187 bks.sort()
3187 bks.sort()
3188 if bks:
3188 if bks:
3189 size = max(map(len,bks))
3189 size = max(map(len,bks))
3190 else:
3190 else:
3191 size = 0
3191 size = 0
3192 fmt = '%-'+str(size)+'s -> %s'
3192 fmt = '%-'+str(size)+'s -> %s'
3193 print 'Current bookmarks:'
3193 print 'Current bookmarks:'
3194 for bk in bks:
3194 for bk in bks:
3195 print fmt % (bk,bkms[bk])
3195 print fmt % (bk,bkms[bk])
3196 else:
3196 else:
3197 if not args:
3197 if not args:
3198 raise UsageError("%bookmark: You must specify the bookmark name")
3198 raise UsageError("%bookmark: You must specify the bookmark name")
3199 elif len(args)==1:
3199 elif len(args)==1:
3200 bkms[args[0]] = os.getcwd()
3200 bkms[args[0]] = os.getcwd()
3201 elif len(args)==2:
3201 elif len(args)==2:
3202 bkms[args[0]] = args[1]
3202 bkms[args[0]] = args[1]
3203 self.db['bookmarks'] = bkms
3203 self.db['bookmarks'] = bkms
3204
3204
3205 def magic_pycat(self, parameter_s=''):
3205 def magic_pycat(self, parameter_s=''):
3206 """Show a syntax-highlighted file through a pager.
3206 """Show a syntax-highlighted file through a pager.
3207
3207
3208 This magic is similar to the cat utility, but it will assume the file
3208 This magic is similar to the cat utility, but it will assume the file
3209 to be Python source and will show it with syntax highlighting. """
3209 to be Python source and will show it with syntax highlighting. """
3210
3210
3211 try:
3211 try:
3212 filename = get_py_filename(parameter_s)
3212 filename = get_py_filename(parameter_s)
3213 cont = file_read(filename)
3213 cont = file_read(filename)
3214 except IOError:
3214 except IOError:
3215 try:
3215 try:
3216 cont = eval(parameter_s,self.user_ns)
3216 cont = eval(parameter_s,self.user_ns)
3217 except NameError:
3217 except NameError:
3218 cont = None
3218 cont = None
3219 if cont is None:
3219 if cont is None:
3220 print "Error: no such file or variable"
3220 print "Error: no such file or variable"
3221 return
3221 return
3222
3222
3223 page(self.shell.pycolorize(cont),
3223 page(self.shell.pycolorize(cont),
3224 screen_lines=self.shell.usable_screen_length)
3224 screen_lines=self.shell.usable_screen_length)
3225
3225
3226 def _rerun_pasted(self):
3226 def _rerun_pasted(self):
3227 """ Rerun a previously pasted command.
3227 """ Rerun a previously pasted command.
3228 """
3228 """
3229 b = self.user_ns.get('pasted_block', None)
3229 b = self.user_ns.get('pasted_block', None)
3230 if b is None:
3230 if b is None:
3231 raise UsageError('No previous pasted block available')
3231 raise UsageError('No previous pasted block available')
3232 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3232 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3233 exec b in self.user_ns
3233 exec b in self.user_ns
3234
3234
3235 def _get_pasted_lines(self, sentinel):
3235 def _get_pasted_lines(self, sentinel):
3236 """ Yield pasted lines until the user enters the given sentinel value.
3236 """ Yield pasted lines until the user enters the given sentinel value.
3237 """
3237 """
3238 from IPython.core import iplib
3238 from IPython.core import iplib
3239 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3239 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3240 while True:
3240 while True:
3241 l = iplib.raw_input_original(':')
3241 l = iplib.raw_input_original(':')
3242 if l == sentinel:
3242 if l == sentinel:
3243 return
3243 return
3244 else:
3244 else:
3245 yield l
3245 yield l
3246
3246
3247 def _strip_pasted_lines_for_code(self, raw_lines):
3247 def _strip_pasted_lines_for_code(self, raw_lines):
3248 """ Strip non-code parts of a sequence of lines to return a block of
3248 """ Strip non-code parts of a sequence of lines to return a block of
3249 code.
3249 code.
3250 """
3250 """
3251 # Regular expressions that declare text we strip from the input:
3251 # Regular expressions that declare text we strip from the input:
3252 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3252 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3253 r'^\s*(\s?>)+', # Python input prompt
3253 r'^\s*(\s?>)+', # Python input prompt
3254 r'^\s*\.{3,}', # Continuation prompts
3254 r'^\s*\.{3,}', # Continuation prompts
3255 r'^\++',
3255 r'^\++',
3256 ]
3256 ]
3257
3257
3258 strip_from_start = map(re.compile,strip_re)
3258 strip_from_start = map(re.compile,strip_re)
3259
3259
3260 lines = []
3260 lines = []
3261 for l in raw_lines:
3261 for l in raw_lines:
3262 for pat in strip_from_start:
3262 for pat in strip_from_start:
3263 l = pat.sub('',l)
3263 l = pat.sub('',l)
3264 lines.append(l)
3264 lines.append(l)
3265
3265
3266 block = "\n".join(lines) + '\n'
3266 block = "\n".join(lines) + '\n'
3267 #print "block:\n",block
3267 #print "block:\n",block
3268 return block
3268 return block
3269
3269
3270 def _execute_block(self, block, par):
3270 def _execute_block(self, block, par):
3271 """ Execute a block, or store it in a variable, per the user's request.
3271 """ Execute a block, or store it in a variable, per the user's request.
3272 """
3272 """
3273 if not par:
3273 if not par:
3274 b = textwrap.dedent(block)
3274 b = textwrap.dedent(block)
3275 self.user_ns['pasted_block'] = b
3275 self.user_ns['pasted_block'] = b
3276 exec b in self.user_ns
3276 exec b in self.user_ns
3277 else:
3277 else:
3278 self.user_ns[par] = SList(block.splitlines())
3278 self.user_ns[par] = SList(block.splitlines())
3279 print "Block assigned to '%s'" % par
3279 print "Block assigned to '%s'" % par
3280
3280
3281 def magic_cpaste(self, parameter_s=''):
3281 def magic_cpaste(self, parameter_s=''):
3282 """Allows you to paste & execute a pre-formatted code block from clipboard.
3282 """Allows you to paste & execute a pre-formatted code block from clipboard.
3283
3283
3284 You must terminate the block with '--' (two minus-signs) alone on the
3284 You must terminate the block with '--' (two minus-signs) alone on the
3285 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3285 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3286 is the new sentinel for this operation)
3286 is the new sentinel for this operation)
3287
3287
3288 The block is dedented prior to execution to enable execution of method
3288 The block is dedented prior to execution to enable execution of method
3289 definitions. '>' and '+' characters at the beginning of a line are
3289 definitions. '>' and '+' characters at the beginning of a line are
3290 ignored, to allow pasting directly from e-mails, diff files and
3290 ignored, to allow pasting directly from e-mails, diff files and
3291 doctests (the '...' continuation prompt is also stripped). The
3291 doctests (the '...' continuation prompt is also stripped). The
3292 executed block is also assigned to variable named 'pasted_block' for
3292 executed block is also assigned to variable named 'pasted_block' for
3293 later editing with '%edit pasted_block'.
3293 later editing with '%edit pasted_block'.
3294
3294
3295 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3295 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3296 This assigns the pasted block to variable 'foo' as string, without
3296 This assigns the pasted block to variable 'foo' as string, without
3297 dedenting or executing it (preceding >>> and + is still stripped)
3297 dedenting or executing it (preceding >>> and + is still stripped)
3298
3298
3299 '%cpaste -r' re-executes the block previously entered by cpaste.
3299 '%cpaste -r' re-executes the block previously entered by cpaste.
3300
3300
3301 Do not be alarmed by garbled output on Windows (it's a readline bug).
3301 Do not be alarmed by garbled output on Windows (it's a readline bug).
3302 Just press enter and type -- (and press enter again) and the block
3302 Just press enter and type -- (and press enter again) and the block
3303 will be what was just pasted.
3303 will be what was just pasted.
3304
3304
3305 IPython statements (magics, shell escapes) are not supported (yet).
3305 IPython statements (magics, shell escapes) are not supported (yet).
3306
3306
3307 See also
3307 See also
3308 --------
3308 --------
3309 paste: automatically pull code from clipboard.
3309 paste: automatically pull code from clipboard.
3310 """
3310 """
3311
3311
3312 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3312 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3313 par = args.strip()
3313 par = args.strip()
3314 if opts.has_key('r'):
3314 if opts.has_key('r'):
3315 self._rerun_pasted()
3315 self._rerun_pasted()
3316 return
3316 return
3317
3317
3318 sentinel = opts.get('s','--')
3318 sentinel = opts.get('s','--')
3319
3319
3320 block = self._strip_pasted_lines_for_code(
3320 block = self._strip_pasted_lines_for_code(
3321 self._get_pasted_lines(sentinel))
3321 self._get_pasted_lines(sentinel))
3322
3322
3323 self._execute_block(block, par)
3323 self._execute_block(block, par)
3324
3324
3325 def magic_paste(self, parameter_s=''):
3325 def magic_paste(self, parameter_s=''):
3326 """Allows you to paste & execute a pre-formatted code block from clipboard.
3326 """Allows you to paste & execute a pre-formatted code block from clipboard.
3327
3327
3328 The text is pulled directly from the clipboard without user
3328 The text is pulled directly from the clipboard without user
3329 intervention and printed back on the screen before execution (unless
3329 intervention and printed back on the screen before execution (unless
3330 the -q flag is given to force quiet mode).
3330 the -q flag is given to force quiet mode).
3331
3331
3332 The block is dedented prior to execution to enable execution of method
3332 The block is dedented prior to execution to enable execution of method
3333 definitions. '>' and '+' characters at the beginning of a line are
3333 definitions. '>' and '+' characters at the beginning of a line are
3334 ignored, to allow pasting directly from e-mails, diff files and
3334 ignored, to allow pasting directly from e-mails, diff files and
3335 doctests (the '...' continuation prompt is also stripped). The
3335 doctests (the '...' continuation prompt is also stripped). The
3336 executed block is also assigned to variable named 'pasted_block' for
3336 executed block is also assigned to variable named 'pasted_block' for
3337 later editing with '%edit pasted_block'.
3337 later editing with '%edit pasted_block'.
3338
3338
3339 You can also pass a variable name as an argument, e.g. '%paste foo'.
3339 You can also pass a variable name as an argument, e.g. '%paste foo'.
3340 This assigns the pasted block to variable 'foo' as string, without
3340 This assigns the pasted block to variable 'foo' as string, without
3341 dedenting or executing it (preceding >>> and + is still stripped)
3341 dedenting or executing it (preceding >>> and + is still stripped)
3342
3342
3343 Options
3343 Options
3344 -------
3344 -------
3345
3345
3346 -r: re-executes the block previously entered by cpaste.
3346 -r: re-executes the block previously entered by cpaste.
3347
3347
3348 -q: quiet mode: do not echo the pasted text back to the terminal.
3348 -q: quiet mode: do not echo the pasted text back to the terminal.
3349
3349
3350 IPython statements (magics, shell escapes) are not supported (yet).
3350 IPython statements (magics, shell escapes) are not supported (yet).
3351
3351
3352 See also
3352 See also
3353 --------
3353 --------
3354 cpaste: manually paste code into terminal until you mark its end.
3354 cpaste: manually paste code into terminal until you mark its end.
3355 """
3355 """
3356 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3356 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3357 par = args.strip()
3357 par = args.strip()
3358 if opts.has_key('r'):
3358 if opts.has_key('r'):
3359 self._rerun_pasted()
3359 self._rerun_pasted()
3360 return
3360 return
3361
3361
3362 text = self.shell.hooks.clipboard_get()
3362 text = self.shell.hooks.clipboard_get()
3363 block = self._strip_pasted_lines_for_code(text.splitlines())
3363 block = self._strip_pasted_lines_for_code(text.splitlines())
3364
3364
3365 # By default, echo back to terminal unless quiet mode is requested
3365 # By default, echo back to terminal unless quiet mode is requested
3366 if not opts.has_key('q'):
3366 if not opts.has_key('q'):
3367 write = self.shell.write
3367 write = self.shell.write
3368 write(block)
3368 write(block)
3369 if not block.endswith('\n'):
3369 if not block.endswith('\n'):
3370 write('\n')
3370 write('\n')
3371 write("## -- End pasted text --\n")
3371 write("## -- End pasted text --\n")
3372
3372
3373 self._execute_block(block, par)
3373 self._execute_block(block, par)
3374
3374
3375 def magic_quickref(self,arg):
3375 def magic_quickref(self,arg):
3376 """ Show a quick reference sheet """
3376 """ Show a quick reference sheet """
3377 import IPython.core.usage
3377 import IPython.core.usage
3378 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3378 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3379
3379
3380 page(qr)
3380 page(qr)
3381
3382 def magic_upgrade(self,arg):
3383 """ Upgrade your IPython installation
3384
3385 This will copy the config files that don't yet exist in your
3386 ipython dir from the system config dir. Use this after upgrading
3387 IPython if you don't wish to delete your .ipython dir.
3388
3389 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3390 new users)
3391
3392 """
3393 ip = self.getapi()
3394 ipinstallation = path(IPython.__file__).dirname()
3395 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3396 src_config = ipinstallation / 'config' / 'userconfig'
3397 userdir = path(ip.config.IPYTHONDIR)
3398 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3399 print ">",cmd
3400 shell(cmd)
3401 if arg == '-nolegacy':
3402 legacy = userdir.files('ipythonrc*')
3403 print "Nuking legacy files:",legacy
3404
3405 [p.remove() for p in legacy]
3406 suffix = (sys.platform == 'win32' and '.ini' or '')
3407 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3408
3409
3381
3410 def magic_doctest_mode(self,parameter_s=''):
3382 def magic_doctest_mode(self,parameter_s=''):
3411 """Toggle doctest mode on and off.
3383 """Toggle doctest mode on and off.
3412
3384
3413 This mode allows you to toggle the prompt behavior between normal
3385 This mode allows you to toggle the prompt behavior between normal
3414 IPython prompts and ones that are as similar to the default IPython
3386 IPython prompts and ones that are as similar to the default IPython
3415 interpreter as possible.
3387 interpreter as possible.
3416
3388
3417 It also supports the pasting of code snippets that have leading '>>>'
3389 It also supports the pasting of code snippets that have leading '>>>'
3418 and '...' prompts in them. This means that you can paste doctests from
3390 and '...' prompts in them. This means that you can paste doctests from
3419 files or docstrings (even if they have leading whitespace), and the
3391 files or docstrings (even if they have leading whitespace), and the
3420 code will execute correctly. You can then use '%history -tn' to see
3392 code will execute correctly. You can then use '%history -tn' to see
3421 the translated history without line numbers; this will give you the
3393 the translated history without line numbers; this will give you the
3422 input after removal of all the leading prompts and whitespace, which
3394 input after removal of all the leading prompts and whitespace, which
3423 can be pasted back into an editor.
3395 can be pasted back into an editor.
3424
3396
3425 With these features, you can switch into this mode easily whenever you
3397 With these features, you can switch into this mode easily whenever you
3426 need to do testing and changes to doctests, without having to leave
3398 need to do testing and changes to doctests, without having to leave
3427 your existing IPython session.
3399 your existing IPython session.
3428 """
3400 """
3429
3401
3430 # XXX - Fix this to have cleaner activate/deactivate calls.
3402 # XXX - Fix this to have cleaner activate/deactivate calls.
3431 from IPython.extensions import InterpreterPasteInput as ipaste
3403 from IPython.extensions import InterpreterPasteInput as ipaste
3432 from IPython.utils.ipstruct import Struct
3404 from IPython.utils.ipstruct import Struct
3433
3405
3434 # Shorthands
3406 # Shorthands
3435 shell = self.shell
3407 shell = self.shell
3436 oc = shell.outputcache
3408 oc = shell.outputcache
3437 meta = shell.meta
3409 meta = shell.meta
3438 # dstore is a data store kept in the instance metadata bag to track any
3410 # dstore is a data store kept in the instance metadata bag to track any
3439 # changes we make, so we can undo them later.
3411 # changes we make, so we can undo them later.
3440 dstore = meta.setdefault('doctest_mode',Struct())
3412 dstore = meta.setdefault('doctest_mode',Struct())
3441 save_dstore = dstore.setdefault
3413 save_dstore = dstore.setdefault
3442
3414
3443 # save a few values we'll need to recover later
3415 # save a few values we'll need to recover later
3444 mode = save_dstore('mode',False)
3416 mode = save_dstore('mode',False)
3445 save_dstore('rc_pprint',shell.pprint)
3417 save_dstore('rc_pprint',shell.pprint)
3446 save_dstore('xmode',shell.InteractiveTB.mode)
3418 save_dstore('xmode',shell.InteractiveTB.mode)
3447 save_dstore('rc_separate_out',shell.separate_out)
3419 save_dstore('rc_separate_out',shell.separate_out)
3448 save_dstore('rc_separate_out2',shell.separate_out2)
3420 save_dstore('rc_separate_out2',shell.separate_out2)
3449 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3421 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3450 save_dstore('rc_separate_in',shell.separate_in)
3422 save_dstore('rc_separate_in',shell.separate_in)
3451
3423
3452 if mode == False:
3424 if mode == False:
3453 # turn on
3425 # turn on
3454 ipaste.activate_prefilter()
3426 ipaste.activate_prefilter()
3455
3427
3456 oc.prompt1.p_template = '>>> '
3428 oc.prompt1.p_template = '>>> '
3457 oc.prompt2.p_template = '... '
3429 oc.prompt2.p_template = '... '
3458 oc.prompt_out.p_template = ''
3430 oc.prompt_out.p_template = ''
3459
3431
3460 # Prompt separators like plain python
3432 # Prompt separators like plain python
3461 oc.input_sep = oc.prompt1.sep = ''
3433 oc.input_sep = oc.prompt1.sep = ''
3462 oc.output_sep = ''
3434 oc.output_sep = ''
3463 oc.output_sep2 = ''
3435 oc.output_sep2 = ''
3464
3436
3465 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3437 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3466 oc.prompt_out.pad_left = False
3438 oc.prompt_out.pad_left = False
3467
3439
3468 shell.pprint = False
3440 shell.pprint = False
3469
3441
3470 shell.magic_xmode('Plain')
3442 shell.magic_xmode('Plain')
3471
3443
3472 else:
3444 else:
3473 # turn off
3445 # turn off
3474 ipaste.deactivate_prefilter()
3446 ipaste.deactivate_prefilter()
3475
3447
3476 oc.prompt1.p_template = shell.prompt_in1
3448 oc.prompt1.p_template = shell.prompt_in1
3477 oc.prompt2.p_template = shell.prompt_in2
3449 oc.prompt2.p_template = shell.prompt_in2
3478 oc.prompt_out.p_template = shell.prompt_out
3450 oc.prompt_out.p_template = shell.prompt_out
3479
3451
3480 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3452 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3481
3453
3482 oc.output_sep = dstore.rc_separate_out
3454 oc.output_sep = dstore.rc_separate_out
3483 oc.output_sep2 = dstore.rc_separate_out2
3455 oc.output_sep2 = dstore.rc_separate_out2
3484
3456
3485 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3457 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3486 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3458 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3487
3459
3488 rc.pprint = dstore.rc_pprint
3460 rc.pprint = dstore.rc_pprint
3489
3461
3490 shell.magic_xmode(dstore.xmode)
3462 shell.magic_xmode(dstore.xmode)
3491
3463
3492 # Store new mode and inform
3464 # Store new mode and inform
3493 dstore.mode = bool(1-int(mode))
3465 dstore.mode = bool(1-int(mode))
3494 print 'Doctest mode is:',
3466 print 'Doctest mode is:',
3495 print ['OFF','ON'][dstore.mode]
3467 print ['OFF','ON'][dstore.mode]
3496
3468
3497 def magic_gui(self, parameter_s=''):
3469 def magic_gui(self, parameter_s=''):
3498 """Enable or disable IPython GUI event loop integration.
3470 """Enable or disable IPython GUI event loop integration.
3499
3471
3500 %gui [-a] [GUINAME]
3472 %gui [-a] [GUINAME]
3501
3473
3502 This magic replaces IPython's threaded shells that were activated
3474 This magic replaces IPython's threaded shells that were activated
3503 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3475 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3504 can now be enabled, disabled and swtiched at runtime and keyboard
3476 can now be enabled, disabled and swtiched at runtime and keyboard
3505 interrupts should work without any problems. The following toolkits
3477 interrupts should work without any problems. The following toolkits
3506 are supports: wxPython, PyQt4, PyGTK, and Tk::
3478 are supports: wxPython, PyQt4, PyGTK, and Tk::
3507
3479
3508 %gui wx # enable wxPython event loop integration
3480 %gui wx # enable wxPython event loop integration
3509 %gui qt4|qt # enable PyQt4 event loop integration
3481 %gui qt4|qt # enable PyQt4 event loop integration
3510 %gui gtk # enable PyGTK event loop integration
3482 %gui gtk # enable PyGTK event loop integration
3511 %gui tk # enable Tk event loop integration
3483 %gui tk # enable Tk event loop integration
3512 %gui # disable all event loop integration
3484 %gui # disable all event loop integration
3513
3485
3514 WARNING: after any of these has been called you can simply create
3486 WARNING: after any of these has been called you can simply create
3515 an application object, but DO NOT start the event loop yourself, as
3487 an application object, but DO NOT start the event loop yourself, as
3516 we have already handled that.
3488 we have already handled that.
3517
3489
3518 If you want us to create an appropriate application object add the
3490 If you want us to create an appropriate application object add the
3519 "-a" flag to your command::
3491 "-a" flag to your command::
3520
3492
3521 %gui -a wx
3493 %gui -a wx
3522
3494
3523 This is highly recommended for most users.
3495 This is highly recommended for most users.
3524 """
3496 """
3525 from IPython.lib import inputhook
3497 from IPython.lib import inputhook
3526 if "-a" in parameter_s:
3498 if "-a" in parameter_s:
3527 app = True
3499 app = True
3528 else:
3500 else:
3529 app = False
3501 app = False
3530 if not parameter_s:
3502 if not parameter_s:
3531 inputhook.clear_inputhook()
3503 inputhook.clear_inputhook()
3532 elif 'wx' in parameter_s:
3504 elif 'wx' in parameter_s:
3533 return inputhook.enable_wx(app)
3505 return inputhook.enable_wx(app)
3534 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3506 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3535 return inputhook.enable_qt4(app)
3507 return inputhook.enable_qt4(app)
3536 elif 'gtk' in parameter_s:
3508 elif 'gtk' in parameter_s:
3537 return inputhook.enable_gtk(app)
3509 return inputhook.enable_gtk(app)
3538 elif 'tk' in parameter_s:
3510 elif 'tk' in parameter_s:
3539 return inputhook.enable_tk(app)
3511 return inputhook.enable_tk(app)
3540
3512
3541 def magic_load_ext(self, module_str):
3513 def magic_load_ext(self, module_str):
3542 """Load an IPython extension by its module name."""
3514 """Load an IPython extension by its module name."""
3543 self.load_extension(module_str)
3515 self.load_extension(module_str)
3544
3516
3545 def magic_unload_ext(self, module_str):
3517 def magic_unload_ext(self, module_str):
3546 """Unload an IPython extension by its module name."""
3518 """Unload an IPython extension by its module name."""
3547 self.unload_extension(module_str)
3519 self.unload_extension(module_str)
3548
3520
3549 def magic_reload_ext(self, module_str):
3521 def magic_reload_ext(self, module_str):
3550 """Reload an IPython extension by its module name."""
3522 """Reload an IPython extension by its module name."""
3551 self.reload_extension(module_str)
3523 self.reload_extension(module_str)
3552
3524
3553 def magic_install_profiles(self, s):
3525 def magic_install_profiles(self, s):
3554 """Install the default IPython profiles into the .ipython dir.
3526 """Install the default IPython profiles into the .ipython dir.
3555
3527
3556 If the default profiles have already been installed, they will not
3528 If the default profiles have already been installed, they will not
3557 be overwritten. You can force overwriting them by using the ``-o``
3529 be overwritten. You can force overwriting them by using the ``-o``
3558 option::
3530 option::
3559
3531
3560 In [1]: %install_profiles -o
3532 In [1]: %install_profiles -o
3561 """
3533 """
3562 if '-o' in s:
3534 if '-o' in s:
3563 overwrite = True
3535 overwrite = True
3564 else:
3536 else:
3565 overwrite = False
3537 overwrite = False
3566 from IPython.config import profile
3538 from IPython.config import profile
3567 profile_dir = os.path.split(profile.__file__)[0]
3539 profile_dir = os.path.split(profile.__file__)[0]
3568 ipythondir = self.ipythondir
3540 ipython_dir = self.ipython_dir
3569 files = os.listdir(profile_dir)
3541 files = os.listdir(profile_dir)
3570
3542
3571 to_install = []
3543 to_install = []
3572 for f in files:
3544 for f in files:
3573 if f.startswith('ipython_config'):
3545 if f.startswith('ipython_config'):
3574 src = os.path.join(profile_dir, f)
3546 src = os.path.join(profile_dir, f)
3575 dst = os.path.join(ipythondir, f)
3547 dst = os.path.join(ipython_dir, f)
3576 if (not os.path.isfile(dst)) or overwrite:
3548 if (not os.path.isfile(dst)) or overwrite:
3577 to_install.append((f, src, dst))
3549 to_install.append((f, src, dst))
3578 if len(to_install)>0:
3550 if len(to_install)>0:
3579 print "Installing profiles to: ", ipythondir
3551 print "Installing profiles to: ", ipython_dir
3580 for (f, src, dst) in to_install:
3552 for (f, src, dst) in to_install:
3581 shutil.copy(src, dst)
3553 shutil.copy(src, dst)
3582 print " %s" % f
3554 print " %s" % f
3583
3555
3584 def magic_install_default_config(self, s):
3556 def magic_install_default_config(self, s):
3585 """Install IPython's default config file into the .ipython dir.
3557 """Install IPython's default config file into the .ipython dir.
3586
3558
3587 If the default config file (:file:`ipython_config.py`) is already
3559 If the default config file (:file:`ipython_config.py`) is already
3588 installed, it will not be overwritten. You can force overwriting
3560 installed, it will not be overwritten. You can force overwriting
3589 by using the ``-o`` option::
3561 by using the ``-o`` option::
3590
3562
3591 In [1]: %install_default_config
3563 In [1]: %install_default_config
3592 """
3564 """
3593 if '-o' in s:
3565 if '-o' in s:
3594 overwrite = True
3566 overwrite = True
3595 else:
3567 else:
3596 overwrite = False
3568 overwrite = False
3597 from IPython.config import default
3569 from IPython.config import default
3598 config_dir = os.path.split(default.__file__)[0]
3570 config_dir = os.path.split(default.__file__)[0]
3599 ipythondir = self.ipythondir
3571 ipython_dir = self.ipython_dir
3600 default_config_file_name = 'ipython_config.py'
3572 default_config_file_name = 'ipython_config.py'
3601 src = os.path.join(config_dir, default_config_file_name)
3573 src = os.path.join(config_dir, default_config_file_name)
3602 dst = os.path.join(ipythondir, default_config_file_name)
3574 dst = os.path.join(ipython_dir, default_config_file_name)
3603 if (not os.path.isfile(dst)) or overwrite:
3575 if (not os.path.isfile(dst)) or overwrite:
3604 shutil.copy(src, dst)
3576 shutil.copy(src, dst)
3605 print "Installing default config file: %s" % dst
3577 print "Installing default config file: %s" % dst
3606
3578
3607
3579
3608 # end Magic
3580 # end Magic
@@ -1,80 +1,57 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
1 """Tests for the key iplib module, where the main ipython class is defined.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import shutil
9 import shutil
10 import tempfile
10 import tempfile
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.core import iplib
16 from IPython.core import iplib
17 from IPython.core import ipapi
17 from IPython.core import ipapi
18 from IPython.core.oldusersetup import user_setup
18
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Globals
21 # Globals
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 # Useful global ipapi object and main IPython one. Unfortunately we have a
24 # Useful global ipapi object and main IPython one. Unfortunately we have a
25 # long precedent of carrying the 'ipapi' global object which is injected into
25 # long precedent of carrying the 'ipapi' global object which is injected into
26 # the system namespace as _ip, but that keeps a pointer to the actual IPython
26 # the system namespace as _ip, but that keeps a pointer to the actual IPython
27 # InteractiveShell instance, which is named IP. Since in testing we do need
27 # InteractiveShell instance, which is named IP. Since in testing we do need
28 # access to the real thing (we want to probe beyond what ipapi exposes), make
28 # access to the real thing (we want to probe beyond what ipapi exposes), make
29 # here a global reference to each. In general, things that are exposed by the
29 # here a global reference to each. In general, things that are exposed by the
30 # ipapi instance should be read from there, but we also will often need to use
30 # ipapi instance should be read from there, but we also will often need to use
31 # the actual IPython one.
31 # the actual IPython one.
32
32
33 # Get the public instance of IPython, and if it's None, make one so we can use
33 # Get the public instance of IPython, and if it's None, make one so we can use
34 # it for testing
34 # it for testing
35 ip = ipapi.get()
35 ip = ipapi.get()
36 if ip is None:
36 if ip is None:
37 # IPython not running yet, make one from the testing machinery for
37 # IPython not running yet, make one from the testing machinery for
38 # consistency when the test suite is being run via iptest
38 # consistency when the test suite is being run via iptest
39 from IPython.testing.plugin import ipdoctest
39 from IPython.testing.plugin import ipdoctest
40 ip = ipapi.get()
40 ip = ipapi.get()
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Test functions
43 # Test functions
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 def test_reset():
46 def test_reset():
47 """reset must clear most namespaces."""
47 """reset must clear most namespaces."""
48 ip.reset() # first, it should run without error
48 ip.reset() # first, it should run without error
49 # Then, check that most namespaces end up empty
49 # Then, check that most namespaces end up empty
50 for ns in ip.ns_refs_table:
50 for ns in ip.ns_refs_table:
51 if ns is ip.user_ns:
51 if ns is ip.user_ns:
52 # The user namespace is reset with some data, so we can't check for
52 # The user namespace is reset with some data, so we can't check for
53 # it being empty
53 # it being empty
54 continue
54 continue
55 nt.assert_equals(len(ns),0)
55 nt.assert_equals(len(ns),0)
56
56
57
58 # make sure that user_setup can be run re-entrantly in 'install' mode.
59 def test_user_setup():
60 # use a lambda to pass kwargs to the generator
61 user_setup = lambda a,k: user_setup(*a,**k)
62 kw = dict(mode='install', interactive=False)
63
64 # Call the user setup and verify that the directory exists
65 yield user_setup, (ip.config.IPYTHONDIR,''), kw
66 yield os.path.isdir, ip.config.IPYTHONDIR
67
68 # Now repeat the operation with a non-existent directory. Check both that
69 # the call succeeds and that the directory is created.
70 tmpdir = tempfile.mktemp(prefix='ipython-test-')
71 # Use a try with an empty except because try/finally doesn't work with a
72 # yield in Python 2.4.
73 try:
74 yield user_setup, (tmpdir,''), kw
75 yield os.path.isdir, tmpdir
76 except:
77 pass
78 # Clean up the temp dir once done
79 shutil.rmtree(tmpdir)
80 No newline at end of file
57
@@ -1,588 +1,588 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
4 #
4 #
5 # Distributed under the terms of the BSD License. The full license is in
5 # Distributed under the terms of the BSD License. The full license is in
6 # the file COPYING, distributed as part of this software.
6 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
7 #*****************************************************************************
8
8
9 import sys
9 import sys
10 from IPython.core import release
10 from IPython.core import release
11
11
12 __doc__ = """
12 __doc__ = """
13 IPython -- An enhanced Interactive Python
13 IPython -- An enhanced Interactive Python
14 =========================================
14 =========================================
15
15
16 A Python shell with automatic history (input and output), dynamic object
16 A Python shell with automatic history (input and output), dynamic object
17 introspection, easier configuration, command completion, access to the system
17 introspection, easier configuration, command completion, access to the system
18 shell and more.
18 shell and more.
19
19
20 IPython can also be embedded in running programs. See EMBEDDING below.
20 IPython can also be embedded in running programs. See EMBEDDING below.
21
21
22
22
23 USAGE
23 USAGE
24 ipython [options] files
24 ipython [options] files
25
25
26 If invoked with no options, it executes all the files listed in
26 If invoked with no options, it executes all the files listed in
27 sequence and drops you into the interpreter while still acknowledging
27 sequence and drops you into the interpreter while still acknowledging
28 any options you may have set in your ipythonrc file. This behavior is
28 any options you may have set in your ipythonrc file. This behavior is
29 different from standard Python, which when called as python -i will
29 different from standard Python, which when called as python -i will
30 only execute one file and will ignore your configuration setup.
30 only execute one file and will ignore your configuration setup.
31
31
32 Please note that some of the configuration options are not available at
32 Please note that some of the configuration options are not available at
33 the command line, simply because they are not practical here. Look into
33 the command line, simply because they are not practical here. Look into
34 your ipythonrc configuration file for details on those. This file
34 your ipythonrc configuration file for details on those. This file
35 typically installed in the $HOME/.ipython directory.
35 typically installed in the $HOME/.ipython directory.
36
36
37 For Windows users, $HOME resolves to C:\\Documents and
37 For Windows users, $HOME resolves to C:\\Documents and
38 Settings\\YourUserName in most instances, and _ipython is used instead
38 Settings\\YourUserName in most instances, and _ipython is used instead
39 of .ipython, since some Win32 programs have problems with dotted names
39 of .ipython, since some Win32 programs have problems with dotted names
40 in directories.
40 in directories.
41
41
42 In the rest of this text, we will refer to this directory as
42 In the rest of this text, we will refer to this directory as
43 IPYTHONDIR.
43 IPYTHON_DIR.
44
44
45 REGULAR OPTIONS
45 REGULAR OPTIONS
46 After the above threading options have been given, regular options can
46 After the above threading options have been given, regular options can
47 follow in any order. All options can be abbreviated to their shortest
47 follow in any order. All options can be abbreviated to their shortest
48 non-ambiguous form and are case-sensitive. One or two dashes can be
48 non-ambiguous form and are case-sensitive. One or two dashes can be
49 used. Some options have an alternate short form, indicated after a |.
49 used. Some options have an alternate short form, indicated after a |.
50
50
51 Most options can also be set from your ipythonrc configuration file.
51 Most options can also be set from your ipythonrc configuration file.
52 See the provided examples for assistance. Options given on the comman-
52 See the provided examples for assistance. Options given on the comman-
53 dline override the values set in the ipythonrc file.
53 dline override the values set in the ipythonrc file.
54
54
55 All options with a [no] prepended can be specified in negated form
55 All options with a [no] prepended can be specified in negated form
56 (using -nooption instead of -option) to turn the feature off.
56 (using -nooption instead of -option) to turn the feature off.
57
57
58 -h, --help
58 -h, --help
59 Show summary of options.
59 Show summary of options.
60
60
61 -autocall <val>
61 -autocall <val>
62 Make IPython automatically call any callable object even if you
62 Make IPython automatically call any callable object even if you
63 didn't type explicit parentheses. For example, 'str 43' becomes
63 didn't type explicit parentheses. For example, 'str 43' becomes
64 'str(43)' automatically. The value can be '0' to disable the
64 'str(43)' automatically. The value can be '0' to disable the
65 feature, '1' for 'smart' autocall, where it is not applied if
65 feature, '1' for 'smart' autocall, where it is not applied if
66 there are no more arguments on the line, and '2' for 'full'
66 there are no more arguments on the line, and '2' for 'full'
67 autocall, where all callable objects are automatically called
67 autocall, where all callable objects are automatically called
68 (even if no arguments are present). The default is '1'.
68 (even if no arguments are present). The default is '1'.
69
69
70 -[no]autoindent
70 -[no]autoindent
71 Turn automatic indentation on/off.
71 Turn automatic indentation on/off.
72
72
73 -[no]automagic
73 -[no]automagic
74 Make magic commands automatic (without needing their first char-
74 Make magic commands automatic (without needing their first char-
75 acter to be %). Type %magic at the IPython prompt for more
75 acter to be %). Type %magic at the IPython prompt for more
76 information.
76 information.
77
77
78 -[no]autoedit_syntax
78 -[no]autoedit_syntax
79 When a syntax error occurs after editing a file, automatically
79 When a syntax error occurs after editing a file, automatically
80 open the file to the trouble causing line for convenient fixing.
80 open the file to the trouble causing line for convenient fixing.
81
81
82 -[no]banner
82 -[no]banner
83 Print the intial information banner (default on).
83 Print the intial information banner (default on).
84
84
85 -c <command>
85 -c <command>
86 Execute the given command string, and set sys.argv to ['c'].
86 Execute the given command string, and set sys.argv to ['c'].
87 This is similar to the -c option in the normal Python inter-
87 This is similar to the -c option in the normal Python inter-
88 preter.
88 preter.
89
89
90 -cache_size|cs <n>
90 -cache_size|cs <n>
91 Size of the output cache (maximum number of entries to hold in
91 Size of the output cache (maximum number of entries to hold in
92 memory). The default is 1000, you can change it permanently in
92 memory). The default is 1000, you can change it permanently in
93 your config file. Setting it to 0 completely disables the
93 your config file. Setting it to 0 completely disables the
94 caching system, and the minimum value accepted is 20 (if you
94 caching system, and the minimum value accepted is 20 (if you
95 provide a value less than 20, it is reset to 0 and a warning is
95 provide a value less than 20, it is reset to 0 and a warning is
96 issued). This limit is defined because otherwise you'll spend
96 issued). This limit is defined because otherwise you'll spend
97 more time re-flushing a too small cache than working.
97 more time re-flushing a too small cache than working.
98
98
99 -classic|cl
99 -classic|cl
100 Gives IPython a similar feel to the classic Python prompt.
100 Gives IPython a similar feel to the classic Python prompt.
101
101
102 -colors <scheme>
102 -colors <scheme>
103 Color scheme for prompts and exception reporting. Currently
103 Color scheme for prompts and exception reporting. Currently
104 implemented: NoColor, Linux, and LightBG.
104 implemented: NoColor, Linux, and LightBG.
105
105
106 -[no]color_info
106 -[no]color_info
107 IPython can display information about objects via a set of func-
107 IPython can display information about objects via a set of func-
108 tions, and optionally can use colors for this, syntax highlight-
108 tions, and optionally can use colors for this, syntax highlight-
109 ing source code and various other elements. However, because
109 ing source code and various other elements. However, because
110 this information is passed through a pager (like 'less') and
110 this information is passed through a pager (like 'less') and
111 many pagers get confused with color codes, this option is off by
111 many pagers get confused with color codes, this option is off by
112 default. You can test it and turn it on permanently in your
112 default. You can test it and turn it on permanently in your
113 ipythonrc file if it works for you. As a reference, the 'less'
113 ipythonrc file if it works for you. As a reference, the 'less'
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
115 7.2 doesn't.
115 7.2 doesn't.
116
116
117 Test it and turn it on permanently if it works with your system.
117 Test it and turn it on permanently if it works with your system.
118 The magic function @color_info allows you to toggle this inter-
118 The magic function @color_info allows you to toggle this inter-
119 actively for testing.
119 actively for testing.
120
120
121 -[no]confirm_exit
121 -[no]confirm_exit
122 Set to confirm when you try to exit IPython with an EOF (Con-
122 Set to confirm when you try to exit IPython with an EOF (Con-
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
124 magic functions @Exit or @Quit you can force a direct exit,
124 magic functions @Exit or @Quit you can force a direct exit,
125 bypassing any confirmation.
125 bypassing any confirmation.
126
126
127 -[no]debug
127 -[no]debug
128 Show information about the loading process. Very useful to pin
128 Show information about the loading process. Very useful to pin
129 down problems with your configuration files or to get details
129 down problems with your configuration files or to get details
130 about session restores.
130 about session restores.
131
131
132 -[no]deep_reload
132 -[no]deep_reload
133 IPython can use the deep_reload module which reloads changes in
133 IPython can use the deep_reload module which reloads changes in
134 modules recursively (it replaces the reload() function, so you
134 modules recursively (it replaces the reload() function, so you
135 don't need to change anything to use it). deep_reload() forces a
135 don't need to change anything to use it). deep_reload() forces a
136 full reload of modules whose code may have changed, which the
136 full reload of modules whose code may have changed, which the
137 default reload() function does not.
137 default reload() function does not.
138
138
139 When deep_reload is off, IPython will use the normal reload(),
139 When deep_reload is off, IPython will use the normal reload(),
140 but deep_reload will still be available as dreload(). This fea-
140 but deep_reload will still be available as dreload(). This fea-
141 ture is off by default [which means that you have both normal
141 ture is off by default [which means that you have both normal
142 reload() and dreload()].
142 reload() and dreload()].
143
143
144 -editor <name>
144 -editor <name>
145 Which editor to use with the @edit command. By default, IPython
145 Which editor to use with the @edit command. By default, IPython
146 will honor your EDITOR environment variable (if not set, vi is
146 will honor your EDITOR environment variable (if not set, vi is
147 the Unix default and notepad the Windows one). Since this editor
147 the Unix default and notepad the Windows one). Since this editor
148 is invoked on the fly by IPython and is meant for editing small
148 is invoked on the fly by IPython and is meant for editing small
149 code snippets, you may want to use a small, lightweight editor
149 code snippets, you may want to use a small, lightweight editor
150 here (in case your default EDITOR is something like Emacs).
150 here (in case your default EDITOR is something like Emacs).
151
151
152 -ipythondir <name>
152 -ipythondir <name>
153 The name of your IPython configuration directory IPYTHONDIR.
153 The name of your IPython configuration directory IPYTHON_DIR.
154 This can also be specified through the environment variable
154 This can also be specified through the environment variable
155 IPYTHONDIR.
155 IPYTHON_DIR.
156
156
157 -log|l Generate a log file of all input. The file is named
157 -log|l Generate a log file of all input. The file is named
158 ipython_log.py in your current directory (which prevents logs
158 ipython_log.py in your current directory (which prevents logs
159 from multiple IPython sessions from trampling each other). You
159 from multiple IPython sessions from trampling each other). You
160 can use this to later restore a session by loading your logfile
160 can use this to later restore a session by loading your logfile
161 as a file to be executed with option -logplay (see below).
161 as a file to be executed with option -logplay (see below).
162
162
163 -logfile|lf
163 -logfile|lf
164 Specify the name of your logfile.
164 Specify the name of your logfile.
165
165
166 -logplay|lp
166 -logplay|lp
167 Replay a previous log. For restoring a session as close as pos-
167 Replay a previous log. For restoring a session as close as pos-
168 sible to the state you left it in, use this option (don't just
168 sible to the state you left it in, use this option (don't just
169 run the logfile). With -logplay, IPython will try to reconstruct
169 run the logfile). With -logplay, IPython will try to reconstruct
170 the previous working environment in full, not just execute the
170 the previous working environment in full, not just execute the
171 commands in the logfile.
171 commands in the logfile.
172 When a session is restored, logging is automatically turned on
172 When a session is restored, logging is automatically turned on
173 again with the name of the logfile it was invoked with (it is
173 again with the name of the logfile it was invoked with (it is
174 read from the log header). So once you've turned logging on for
174 read from the log header). So once you've turned logging on for
175 a session, you can quit IPython and reload it as many times as
175 a session, you can quit IPython and reload it as many times as
176 you want and it will continue to log its history and restore
176 you want and it will continue to log its history and restore
177 from the beginning every time.
177 from the beginning every time.
178
178
179 Caveats: there are limitations in this option. The history vari-
179 Caveats: there are limitations in this option. The history vari-
180 ables _i*,_* and _dh don't get restored properly. In the future
180 ables _i*,_* and _dh don't get restored properly. In the future
181 we will try to implement full session saving by writing and
181 we will try to implement full session saving by writing and
182 retrieving a failed because of inherent limitations of Python's
182 retrieving a failed because of inherent limitations of Python's
183 Pickle module, so this may have to wait.
183 Pickle module, so this may have to wait.
184
184
185 -[no]messages
185 -[no]messages
186 Print messages which IPython collects about its startup process
186 Print messages which IPython collects about its startup process
187 (default on).
187 (default on).
188
188
189 -[no]pdb
189 -[no]pdb
190 Automatically call the pdb debugger after every uncaught excep-
190 Automatically call the pdb debugger after every uncaught excep-
191 tion. If you are used to debugging using pdb, this puts you
191 tion. If you are used to debugging using pdb, this puts you
192 automatically inside of it after any call (either in IPython or
192 automatically inside of it after any call (either in IPython or
193 in code called by it) which triggers an exception which goes
193 in code called by it) which triggers an exception which goes
194 uncaught.
194 uncaught.
195
195
196 -[no]pprint
196 -[no]pprint
197 IPython can optionally use the pprint (pretty printer) module
197 IPython can optionally use the pprint (pretty printer) module
198 for displaying results. pprint tends to give a nicer display of
198 for displaying results. pprint tends to give a nicer display of
199 nested data structures. If you like it, you can turn it on per-
199 nested data structures. If you like it, you can turn it on per-
200 manently in your config file (default off).
200 manently in your config file (default off).
201
201
202 -profile|p <name>
202 -profile|p <name>
203 Assume that your config file is ipythonrc-<name> (looks in cur-
203 Assume that your config file is ipythonrc-<name> (looks in cur-
204 rent dir first, then in IPYTHONDIR). This is a quick way to keep
204 rent dir first, then in IPYTHON_DIR). This is a quick way to keep
205 and load multiple config files for different tasks, especially
205 and load multiple config files for different tasks, especially
206 if you use the include option of config files. You can keep a
206 if you use the include option of config files. You can keep a
207 basic IPYTHONDIR/ipythonrc file and then have other 'profiles'
207 basic IPYTHON_DIR/ipythonrc file and then have other 'profiles'
208 which include this one and load extra things for particular
208 which include this one and load extra things for particular
209 tasks. For example:
209 tasks. For example:
210
210
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
213 related modules.
213 related modules.
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
215 plotting modules.
215 plotting modules.
216
216
217 Since it is possible to create an endless loop by having circu-
217 Since it is possible to create an endless loop by having circu-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
219 sive inclusions.
219 sive inclusions.
220
220
221 -prompt_in1|pi1 <string>
221 -prompt_in1|pi1 <string>
222 Specify the string used for input prompts. Note that if you are
222 Specify the string used for input prompts. Note that if you are
223 using numbered prompts, the number is represented with a '\#' in
223 using numbered prompts, the number is represented with a '\#' in
224 the string. Don't forget to quote strings with spaces embedded
224 the string. Don't forget to quote strings with spaces embedded
225 in them. Default: 'In [\#]: '.
225 in them. Default: 'In [\#]: '.
226
226
227 Most bash-like escapes can be used to customize IPython's
227 Most bash-like escapes can be used to customize IPython's
228 prompts, as well as a few additional ones which are IPython-spe-
228 prompts, as well as a few additional ones which are IPython-spe-
229 cific. All valid prompt escapes are described in detail in the
229 cific. All valid prompt escapes are described in detail in the
230 Customization section of the IPython HTML/PDF manual.
230 Customization section of the IPython HTML/PDF manual.
231
231
232 -prompt_in2|pi2 <string>
232 -prompt_in2|pi2 <string>
233 Similar to the previous option, but used for the continuation
233 Similar to the previous option, but used for the continuation
234 prompts. The special sequence '\D' is similar to '\#', but with
234 prompts. The special sequence '\D' is similar to '\#', but with
235 all digits replaced dots (so you can have your continuation
235 all digits replaced dots (so you can have your continuation
236 prompt aligned with your input prompt). Default: ' .\D.: '
236 prompt aligned with your input prompt). Default: ' .\D.: '
237 (note three spaces at the start for alignment with 'In [\#]').
237 (note three spaces at the start for alignment with 'In [\#]').
238
238
239 -prompt_out|po <string>
239 -prompt_out|po <string>
240 String used for output prompts, also uses numbers like
240 String used for output prompts, also uses numbers like
241 prompt_in1. Default: 'Out[\#]:'.
241 prompt_in1. Default: 'Out[\#]:'.
242
242
243 -quick Start in bare bones mode (no config file loaded).
243 -quick Start in bare bones mode (no config file loaded).
244
244
245 -rcfile <name>
245 -rcfile <name>
246 Name of your IPython resource configuration file. normally
246 Name of your IPython resource configuration file. normally
247 IPython loads ipythonrc (from current directory) or
247 IPython loads ipythonrc (from current directory) or
248 IPYTHONDIR/ipythonrc. If the loading of your config file fails,
248 IPYTHON_DIR/ipythonrc. If the loading of your config file fails,
249 IPython starts with a bare bones configuration (no modules
249 IPython starts with a bare bones configuration (no modules
250 loaded at all).
250 loaded at all).
251
251
252 -[no]readline
252 -[no]readline
253 Use the readline library, which is needed to support name com-
253 Use the readline library, which is needed to support name com-
254 pletion and command history, among other things. It is enabled
254 pletion and command history, among other things. It is enabled
255 by default, but may cause problems for users of X/Emacs in
255 by default, but may cause problems for users of X/Emacs in
256 Python comint or shell buffers.
256 Python comint or shell buffers.
257
257
258 Note that emacs 'eterm' buffers (opened with M-x term) support
258 Note that emacs 'eterm' buffers (opened with M-x term) support
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
260 shell and C-c !) buffers do not.
260 shell and C-c !) buffers do not.
261
261
262 -screen_length|sl <n>
262 -screen_length|sl <n>
263 Number of lines of your screen. This is used to control print-
263 Number of lines of your screen. This is used to control print-
264 ing of very long strings. Strings longer than this number of
264 ing of very long strings. Strings longer than this number of
265 lines will be sent through a pager instead of directly printed.
265 lines will be sent through a pager instead of directly printed.
266
266
267 The default value for this is 0, which means IPython will auto-
267 The default value for this is 0, which means IPython will auto-
268 detect your screen size every time it needs to print certain
268 detect your screen size every time it needs to print certain
269 potentially long strings (this doesn't change the behavior of
269 potentially long strings (this doesn't change the behavior of
270 the 'print' keyword, it's only triggered internally). If for
270 the 'print' keyword, it's only triggered internally). If for
271 some reason this isn't working well (it needs curses support),
271 some reason this isn't working well (it needs curses support),
272 specify it yourself. Otherwise don't change the default.
272 specify it yourself. Otherwise don't change the default.
273
273
274 -separate_in|si <string>
274 -separate_in|si <string>
275 Separator before input prompts. Default '0.
275 Separator before input prompts. Default '0.
276
276
277 -separate_out|so <string>
277 -separate_out|so <string>
278 Separator before output prompts. Default: 0 (nothing).
278 Separator before output prompts. Default: 0 (nothing).
279
279
280 -separate_out2|so2 <string>
280 -separate_out2|so2 <string>
281 Separator after output prompts. Default: 0 (nothing).
281 Separator after output prompts. Default: 0 (nothing).
282
282
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
284 Simply removes all input/output separators.
284 Simply removes all input/output separators.
285
285
286 -upgrade
286 -upgrade
287 Allows you to upgrade your IPYTHONDIR configuration when you
287 Allows you to upgrade your IPYTHON_DIR configuration when you
288 install a new version of IPython. Since new versions may
288 install a new version of IPython. Since new versions may
289 include new command lines options or example files, this copies
289 include new command lines options or example files, this copies
290 updated ipythonrc-type files. However, it backs up (with a .old
290 updated ipythonrc-type files. However, it backs up (with a .old
291 extension) all files which it overwrites so that you can merge
291 extension) all files which it overwrites so that you can merge
292 back any custimizations you might have in your personal files.
292 back any custimizations you might have in your personal files.
293
293
294 -Version
294 -Version
295 Print version information and exit.
295 Print version information and exit.
296
296
297 -wxversion <string>
297 -wxversion <string>
298 Select a specific version of wxPython (used in conjunction with
298 Select a specific version of wxPython (used in conjunction with
299 -wthread). Requires the wxversion module, part of recent
299 -wthread). Requires the wxversion module, part of recent
300 wxPython distributions.
300 wxPython distributions.
301
301
302 -xmode <modename>
302 -xmode <modename>
303 Mode for exception reporting. The valid modes are Plain, Con-
303 Mode for exception reporting. The valid modes are Plain, Con-
304 text, and Verbose.
304 text, and Verbose.
305
305
306 - Plain: similar to python's normal traceback printing.
306 - Plain: similar to python's normal traceback printing.
307
307
308 - Context: prints 5 lines of context source code around each
308 - Context: prints 5 lines of context source code around each
309 line in the traceback.
309 line in the traceback.
310
310
311 - Verbose: similar to Context, but additionally prints the vari-
311 - Verbose: similar to Context, but additionally prints the vari-
312 ables currently visible where the exception happened (shortening
312 ables currently visible where the exception happened (shortening
313 their strings if too long). This can potentially be very slow,
313 their strings if too long). This can potentially be very slow,
314 if you happen to have a huge data structure whose string repre-
314 if you happen to have a huge data structure whose string repre-
315 sentation is complex to compute. Your computer may appear to
315 sentation is complex to compute. Your computer may appear to
316 freeze for a while with cpu usage at 100%. If this occurs, you
316 freeze for a while with cpu usage at 100%. If this occurs, you
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
318 once).
318 once).
319
319
320
320
321 EMBEDDING
321 EMBEDDING
322 It is possible to start an IPython instance inside your own Python pro-
322 It is possible to start an IPython instance inside your own Python pro-
323 grams. In the documentation example files there are some illustrations
323 grams. In the documentation example files there are some illustrations
324 on how to do this.
324 on how to do this.
325
325
326 This feature allows you to evalutate dynamically the state of your
326 This feature allows you to evalutate dynamically the state of your
327 code, operate with your variables, analyze them, etc. Note however
327 code, operate with your variables, analyze them, etc. Note however
328 that any changes you make to values while in the shell do NOT propagate
328 that any changes you make to values while in the shell do NOT propagate
329 back to the running code, so it is safe to modify your values because
329 back to the running code, so it is safe to modify your values because
330 you won't break your code in bizarre ways by doing so.
330 you won't break your code in bizarre ways by doing so.
331 """
331 """
332
332
333 cmd_line_usage = __doc__
333 cmd_line_usage = __doc__
334
334
335 #---------------------------------------------------------------------------
335 #---------------------------------------------------------------------------
336 interactive_usage = """
336 interactive_usage = """
337 IPython -- An enhanced Interactive Python
337 IPython -- An enhanced Interactive Python
338 =========================================
338 =========================================
339
339
340 IPython offers a combination of convenient shell features, special commands
340 IPython offers a combination of convenient shell features, special commands
341 and a history mechanism for both input (command history) and output (results
341 and a history mechanism for both input (command history) and output (results
342 caching, similar to Mathematica). It is intended to be a fully compatible
342 caching, similar to Mathematica). It is intended to be a fully compatible
343 replacement for the standard Python interpreter, while offering vastly
343 replacement for the standard Python interpreter, while offering vastly
344 improved functionality and flexibility.
344 improved functionality and flexibility.
345
345
346 At your system command line, type 'ipython -help' to see the command line
346 At your system command line, type 'ipython -help' to see the command line
347 options available. This document only describes interactive features.
347 options available. This document only describes interactive features.
348
348
349 Warning: IPython relies on the existence of a global variable called __IP which
349 Warning: IPython relies on the existence of a global variable called __IP which
350 controls the shell itself. If you redefine __IP to anything, bizarre behavior
350 controls the shell itself. If you redefine __IP to anything, bizarre behavior
351 will quickly occur.
351 will quickly occur.
352
352
353 MAIN FEATURES
353 MAIN FEATURES
354
354
355 * Access to the standard Python help. As of Python 2.1, a help system is
355 * Access to the standard Python help. As of Python 2.1, a help system is
356 available with access to object docstrings and the Python manuals. Simply
356 available with access to object docstrings and the Python manuals. Simply
357 type 'help' (no quotes) to access it.
357 type 'help' (no quotes) to access it.
358
358
359 * Magic commands: type %magic for information on the magic subsystem.
359 * Magic commands: type %magic for information on the magic subsystem.
360
360
361 * System command aliases, via the %alias command or the ipythonrc config file.
361 * System command aliases, via the %alias command or the ipythonrc config file.
362
362
363 * Dynamic object information:
363 * Dynamic object information:
364
364
365 Typing ?word or word? prints detailed information about an object. If
365 Typing ?word or word? prints detailed information about an object. If
366 certain strings in the object are too long (docstrings, code, etc.) they get
366 certain strings in the object are too long (docstrings, code, etc.) they get
367 snipped in the center for brevity.
367 snipped in the center for brevity.
368
368
369 Typing ??word or word?? gives access to the full information without
369 Typing ??word or word?? gives access to the full information without
370 snipping long strings. Long strings are sent to the screen through the less
370 snipping long strings. Long strings are sent to the screen through the less
371 pager if longer than the screen, printed otherwise.
371 pager if longer than the screen, printed otherwise.
372
372
373 The ?/?? system gives access to the full source code for any object (if
373 The ?/?? system gives access to the full source code for any object (if
374 available), shows function prototypes and other useful information.
374 available), shows function prototypes and other useful information.
375
375
376 If you just want to see an object's docstring, type '%pdoc object' (without
376 If you just want to see an object's docstring, type '%pdoc object' (without
377 quotes, and without % if you have automagic on).
377 quotes, and without % if you have automagic on).
378
378
379 Both %pdoc and ?/?? give you access to documentation even on things which are
379 Both %pdoc and ?/?? give you access to documentation even on things which are
380 not explicitely defined. Try for example typing {}.get? or after import os,
380 not explicitely defined. Try for example typing {}.get? or after import os,
381 type os.path.abspath??. The magic functions %pdef, %source and %file operate
381 type os.path.abspath??. The magic functions %pdef, %source and %file operate
382 similarly.
382 similarly.
383
383
384 * Completion in the local namespace, by typing TAB at the prompt.
384 * Completion in the local namespace, by typing TAB at the prompt.
385
385
386 At any time, hitting tab will complete any available python commands or
386 At any time, hitting tab will complete any available python commands or
387 variable names, and show you a list of the possible completions if there's
387 variable names, and show you a list of the possible completions if there's
388 no unambiguous one. It will also complete filenames in the current directory.
388 no unambiguous one. It will also complete filenames in the current directory.
389
389
390 This feature requires the readline and rlcomplete modules, so it won't work
390 This feature requires the readline and rlcomplete modules, so it won't work
391 if your Python lacks readline support (such as under Windows).
391 if your Python lacks readline support (such as under Windows).
392
392
393 * Search previous command history in two ways (also requires readline):
393 * Search previous command history in two ways (also requires readline):
394
394
395 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
395 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
396 search through only the history items that match what you've typed so
396 search through only the history items that match what you've typed so
397 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
397 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
398 normal arrow keys.
398 normal arrow keys.
399
399
400 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
400 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
401 your history for lines that match what you've typed so far, completing as
401 your history for lines that match what you've typed so far, completing as
402 much as it can.
402 much as it can.
403
403
404 * Persistent command history across sessions (readline required).
404 * Persistent command history across sessions (readline required).
405
405
406 * Logging of input with the ability to save and restore a working session.
406 * Logging of input with the ability to save and restore a working session.
407
407
408 * System escape with !. Typing !ls will run 'ls' in the current directory.
408 * System escape with !. Typing !ls will run 'ls' in the current directory.
409
409
410 * The reload command does a 'deep' reload of a module: changes made to the
410 * The reload command does a 'deep' reload of a module: changes made to the
411 module since you imported will actually be available without having to exit.
411 module since you imported will actually be available without having to exit.
412
412
413 * Verbose and colored exception traceback printouts. See the magic xmode and
413 * Verbose and colored exception traceback printouts. See the magic xmode and
414 xcolor functions for details (just type %magic).
414 xcolor functions for details (just type %magic).
415
415
416 * Input caching system:
416 * Input caching system:
417
417
418 IPython offers numbered prompts (In/Out) with input and output caching. All
418 IPython offers numbered prompts (In/Out) with input and output caching. All
419 input is saved and can be retrieved as variables (besides the usual arrow
419 input is saved and can be retrieved as variables (besides the usual arrow
420 key recall).
420 key recall).
421
421
422 The following GLOBAL variables always exist (so don't overwrite them!):
422 The following GLOBAL variables always exist (so don't overwrite them!):
423 _i: stores previous input.
423 _i: stores previous input.
424 _ii: next previous.
424 _ii: next previous.
425 _iii: next-next previous.
425 _iii: next-next previous.
426 _ih : a list of all input _ih[n] is the input from line n.
426 _ih : a list of all input _ih[n] is the input from line n.
427
427
428 Additionally, global variables named _i<n> are dynamically created (<n>
428 Additionally, global variables named _i<n> are dynamically created (<n>
429 being the prompt counter), such that _i<n> == _ih[<n>]
429 being the prompt counter), such that _i<n> == _ih[<n>]
430
430
431 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
431 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
432
432
433 You can create macros which contain multiple input lines from this history,
433 You can create macros which contain multiple input lines from this history,
434 for later re-execution, with the %macro function.
434 for later re-execution, with the %macro function.
435
435
436 The history function %hist allows you to see any part of your input history
436 The history function %hist allows you to see any part of your input history
437 by printing a range of the _i variables. Note that inputs which contain
437 by printing a range of the _i variables. Note that inputs which contain
438 magic functions (%) appear in the history with a prepended comment. This is
438 magic functions (%) appear in the history with a prepended comment. This is
439 because they aren't really valid Python code, so you can't exec them.
439 because they aren't really valid Python code, so you can't exec them.
440
440
441 * Output caching system:
441 * Output caching system:
442
442
443 For output that is returned from actions, a system similar to the input
443 For output that is returned from actions, a system similar to the input
444 cache exists but using _ instead of _i. Only actions that produce a result
444 cache exists but using _ instead of _i. Only actions that produce a result
445 (NOT assignments, for example) are cached. If you are familiar with
445 (NOT assignments, for example) are cached. If you are familiar with
446 Mathematica, IPython's _ variables behave exactly like Mathematica's %
446 Mathematica, IPython's _ variables behave exactly like Mathematica's %
447 variables.
447 variables.
448
448
449 The following GLOBAL variables always exist (so don't overwrite them!):
449 The following GLOBAL variables always exist (so don't overwrite them!):
450 _ (one underscore): previous output.
450 _ (one underscore): previous output.
451 __ (two underscores): next previous.
451 __ (two underscores): next previous.
452 ___ (three underscores): next-next previous.
452 ___ (three underscores): next-next previous.
453
453
454 Global variables named _<n> are dynamically created (<n> being the prompt
454 Global variables named _<n> are dynamically created (<n> being the prompt
455 counter), such that the result of output <n> is always available as _<n>.
455 counter), such that the result of output <n> is always available as _<n>.
456
456
457 Finally, a global dictionary named _oh exists with entries for all lines
457 Finally, a global dictionary named _oh exists with entries for all lines
458 which generated output.
458 which generated output.
459
459
460 * Directory history:
460 * Directory history:
461
461
462 Your history of visited directories is kept in the global list _dh, and the
462 Your history of visited directories is kept in the global list _dh, and the
463 magic %cd command can be used to go to any entry in that list.
463 magic %cd command can be used to go to any entry in that list.
464
464
465 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
465 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
466
466
467 1. Auto-parentheses
467 1. Auto-parentheses
468 Callable objects (i.e. functions, methods, etc) can be invoked like
468 Callable objects (i.e. functions, methods, etc) can be invoked like
469 this (notice the commas between the arguments):
469 this (notice the commas between the arguments):
470 >>> callable_ob arg1, arg2, arg3
470 >>> callable_ob arg1, arg2, arg3
471 and the input will be translated to this:
471 and the input will be translated to this:
472 --> callable_ob(arg1, arg2, arg3)
472 --> callable_ob(arg1, arg2, arg3)
473 You can force auto-parentheses by using '/' as the first character
473 You can force auto-parentheses by using '/' as the first character
474 of a line. For example:
474 of a line. For example:
475 >>> /globals # becomes 'globals()'
475 >>> /globals # becomes 'globals()'
476 Note that the '/' MUST be the first character on the line! This
476 Note that the '/' MUST be the first character on the line! This
477 won't work:
477 won't work:
478 >>> print /globals # syntax error
478 >>> print /globals # syntax error
479
479
480 In most cases the automatic algorithm should work, so you should
480 In most cases the automatic algorithm should work, so you should
481 rarely need to explicitly invoke /. One notable exception is if you
481 rarely need to explicitly invoke /. One notable exception is if you
482 are trying to call a function with a list of tuples as arguments (the
482 are trying to call a function with a list of tuples as arguments (the
483 parenthesis will confuse IPython):
483 parenthesis will confuse IPython):
484 In [1]: zip (1,2,3),(4,5,6) # won't work
484 In [1]: zip (1,2,3),(4,5,6) # won't work
485 but this will work:
485 but this will work:
486 In [2]: /zip (1,2,3),(4,5,6)
486 In [2]: /zip (1,2,3),(4,5,6)
487 ------> zip ((1,2,3),(4,5,6))
487 ------> zip ((1,2,3),(4,5,6))
488 Out[2]= [(1, 4), (2, 5), (3, 6)]
488 Out[2]= [(1, 4), (2, 5), (3, 6)]
489
489
490 IPython tells you that it has altered your command line by
490 IPython tells you that it has altered your command line by
491 displaying the new command line preceded by -->. e.g.:
491 displaying the new command line preceded by -->. e.g.:
492 In [18]: callable list
492 In [18]: callable list
493 -------> callable (list)
493 -------> callable (list)
494
494
495 2. Auto-Quoting
495 2. Auto-Quoting
496 You can force auto-quoting of a function's arguments by using ',' as
496 You can force auto-quoting of a function's arguments by using ',' as
497 the first character of a line. For example:
497 the first character of a line. For example:
498 >>> ,my_function /home/me # becomes my_function("/home/me")
498 >>> ,my_function /home/me # becomes my_function("/home/me")
499
499
500 If you use ';' instead, the whole argument is quoted as a single
500 If you use ';' instead, the whole argument is quoted as a single
501 string (while ',' splits on whitespace):
501 string (while ',' splits on whitespace):
502 >>> ,my_function a b c # becomes my_function("a","b","c")
502 >>> ,my_function a b c # becomes my_function("a","b","c")
503 >>> ;my_function a b c # becomes my_function("a b c")
503 >>> ;my_function a b c # becomes my_function("a b c")
504
504
505 Note that the ',' MUST be the first character on the line! This
505 Note that the ',' MUST be the first character on the line! This
506 won't work:
506 won't work:
507 >>> x = ,my_function /home/me # syntax error
507 >>> x = ,my_function /home/me # syntax error
508 """
508 """
509
509
510 interactive_usage_min = """\
510 interactive_usage_min = """\
511 An enhanced console for Python.
511 An enhanced console for Python.
512 Some of its features are:
512 Some of its features are:
513 - Readline support if the readline library is present.
513 - Readline support if the readline library is present.
514 - Tab completion in the local namespace.
514 - Tab completion in the local namespace.
515 - Logging of input, see command-line options.
515 - Logging of input, see command-line options.
516 - System shell escape via ! , eg !ls.
516 - System shell escape via ! , eg !ls.
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
517 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
518 - Keeps track of locally defined variables via %who, %whos.
518 - Keeps track of locally defined variables via %who, %whos.
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
519 - Show object information with a ? eg ?x or x? (use ?? for more info).
520 """
520 """
521
521
522 quick_reference = r"""
522 quick_reference = r"""
523 IPython -- An enhanced Interactive Python - Quick Reference Card
523 IPython -- An enhanced Interactive Python - Quick Reference Card
524 ================================================================
524 ================================================================
525
525
526 obj?, obj?? : Get help, or more help for object (also works as
526 obj?, obj?? : Get help, or more help for object (also works as
527 ?obj, ??obj).
527 ?obj, ??obj).
528 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
528 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
529 %magic : Information about IPython's 'magic' % functions.
529 %magic : Information about IPython's 'magic' % functions.
530
530
531 Magic functions are prefixed by %, and typically take their arguments without
531 Magic functions are prefixed by %, and typically take their arguments without
532 parentheses, quotes or even commas for convenience.
532 parentheses, quotes or even commas for convenience.
533
533
534 Example magic function calls:
534 Example magic function calls:
535
535
536 %alias d ls -F : 'd' is now an alias for 'ls -F'
536 %alias d ls -F : 'd' is now an alias for 'ls -F'
537 alias d ls -F : Works if 'alias' not a python name
537 alias d ls -F : Works if 'alias' not a python name
538 alist = %alias : Get list of aliases to 'alist'
538 alist = %alias : Get list of aliases to 'alist'
539 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
539 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
540 %cd?? : See help AND source for magic %cd
540 %cd?? : See help AND source for magic %cd
541
541
542 System commands:
542 System commands:
543
543
544 !cp a.txt b/ : System command escape, calls os.system()
544 !cp a.txt b/ : System command escape, calls os.system()
545 cp a.txt b/ : after %rehashx, most system commands work without !
545 cp a.txt b/ : after %rehashx, most system commands work without !
546 cp ${f}.txt $bar : Variable expansion in magics and system commands
546 cp ${f}.txt $bar : Variable expansion in magics and system commands
547 files = !ls /usr : Capture sytem command output
547 files = !ls /usr : Capture sytem command output
548 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
548 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
549
549
550 History:
550 History:
551
551
552 _i, _ii, _iii : Previous, next previous, next next previous input
552 _i, _ii, _iii : Previous, next previous, next next previous input
553 _i4, _ih[2:5] : Input history line 4, lines 2-4
553 _i4, _ih[2:5] : Input history line 4, lines 2-4
554 exec _i81 : Execute input history line #81 again
554 exec _i81 : Execute input history line #81 again
555 %rep 81 : Edit input history line #81
555 %rep 81 : Edit input history line #81
556 _, __, ___ : previous, next previous, next next previous output
556 _, __, ___ : previous, next previous, next next previous output
557 _dh : Directory history
557 _dh : Directory history
558 _oh : Output history
558 _oh : Output history
559 %hist : Command history. '%hist -g foo' search history for 'foo'
559 %hist : Command history. '%hist -g foo' search history for 'foo'
560
560
561 Autocall:
561 Autocall:
562
562
563 f 1,2 : f(1,2)
563 f 1,2 : f(1,2)
564 /f 1,2 : f(1,2) (forced autoparen)
564 /f 1,2 : f(1,2) (forced autoparen)
565 ,f 1 2 : f("1","2")
565 ,f 1 2 : f("1","2")
566 ;f 1 2 : f("1 2")
566 ;f 1 2 : f("1 2")
567
567
568 Remember: TAB completion works in many contexts, not just file names
568 Remember: TAB completion works in many contexts, not just file names
569 or python names.
569 or python names.
570
570
571 The following magic functions are currently available:
571 The following magic functions are currently available:
572
572
573 """
573 """
574
574
575 quick_guide = """\
575 quick_guide = """\
576 ? -> Introduction and overview of IPython's features.
576 ? -> Introduction and overview of IPython's features.
577 %quickref -> Quick reference.
577 %quickref -> Quick reference.
578 help -> Python's own help system.
578 help -> Python's own help system.
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
579 object? -> Details about 'object'. ?object also works, ?? prints more."""
580
580
581 default_banner_parts = [
581 default_banner_parts = [
582 'Python %s' % (sys.version.split('\n')[0],),
582 'Python %s' % (sys.version.split('\n')[0],),
583 'Type "copyright", "credits" or "license" for more information.\n',
583 'Type "copyright", "credits" or "license" for more information.\n',
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
584 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 quick_guide
585 quick_guide
586 ]
586 ]
587
587
588 default_banner = '\n'.join(default_banner_parts)
588 default_banner = '\n'.join(default_banner_parts)
@@ -1,266 +1,266 b''
1 #!/usr/bin/python
1 #!/usr/bin/python
2 # -*- coding: iso-8859-15 -*-
2 # -*- coding: iso-8859-15 -*-
3
3
4 import wx.aui
4 import wx.aui
5 import sys
5 import sys
6 #used for about dialog
6 #used for about dialog
7 from wx.lib.wordwrap import wordwrap
7 from wx.lib.wordwrap import wordwrap
8
8
9 #used for ipython GUI objects
9 #used for ipython GUI objects
10 from IPython.gui.wx.ipython_view import IPShellWidget
10 from IPython.gui.wx.ipython_view import IPShellWidget
11 from IPython.gui.wx.ipython_history import IPythonHistoryPanel
11 from IPython.gui.wx.ipython_history import IPythonHistoryPanel
12
12
13 #used to invoke ipython1 wx implementation
13 #used to invoke ipython1 wx implementation
14 ### FIXME ### temporary disabled due to interference with 'show_in_pager' hook
14 ### FIXME ### temporary disabled due to interference with 'show_in_pager' hook
15 is_sync_frontend_ok = False
15 is_sync_frontend_ok = False
16 try:
16 try:
17 from IPython.frontend.wx.ipythonx import IPythonXController
17 from IPython.frontend.wx.ipythonx import IPythonXController
18 except ImportError:
18 except ImportError:
19 is_sync_frontend_ok = False
19 is_sync_frontend_ok = False
20
20
21 #used to create options.conf file in user directory
21 #used to create options.conf file in user directory
22 from IPython.core.ipapi import get
22 from IPython.core.ipapi import get
23
23
24 __version__ = 0.91
24 __version__ = 0.91
25 __author__ = "Laurent Dufrechou"
25 __author__ = "Laurent Dufrechou"
26 __email__ = "laurent.dufrechou _at_ gmail.com"
26 __email__ = "laurent.dufrechou _at_ gmail.com"
27 __license__ = "BSD"
27 __license__ = "BSD"
28
28
29 #-----------------------------------------
29 #-----------------------------------------
30 # Creating one main frame for our
30 # Creating one main frame for our
31 # application with movables windows
31 # application with movables windows
32 #-----------------------------------------
32 #-----------------------------------------
33 class MyFrame(wx.Frame):
33 class MyFrame(wx.Frame):
34 """Creating one main frame for our
34 """Creating one main frame for our
35 application with movables windows"""
35 application with movables windows"""
36 def __init__(self, parent=None, id=-1, title="WxIPython",
36 def __init__(self, parent=None, id=-1, title="WxIPython",
37 pos=wx.DefaultPosition,
37 pos=wx.DefaultPosition,
38 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE, sync_ok=False):
38 size=(800, 600), style=wx.DEFAULT_FRAME_STYLE, sync_ok=False):
39 wx.Frame.__init__(self, parent, id, title, pos, size, style)
39 wx.Frame.__init__(self, parent, id, title, pos, size, style)
40 self._mgr = wx.aui.AuiManager()
40 self._mgr = wx.aui.AuiManager()
41
41
42 # notify PyAUI which frame to use
42 # notify PyAUI which frame to use
43 self._mgr.SetManagedWindow(self)
43 self._mgr.SetManagedWindow(self)
44
44
45 #create differents panels and make them persistant
45 #create differents panels and make them persistant
46 self.history_panel = IPythonHistoryPanel(self)
46 self.history_panel = IPythonHistoryPanel(self)
47
47
48 self.history_panel.setOptionTrackerHook(self.optionSave)
48 self.history_panel.setOptionTrackerHook(self.optionSave)
49
49
50 self.ipython_panel = IPShellWidget(self,background_color = "BLACK")
50 self.ipython_panel = IPShellWidget(self,background_color = "BLACK")
51 #self.ipython_panel = IPShellWidget(self,background_color = "WHITE")
51 #self.ipython_panel = IPShellWidget(self,background_color = "WHITE")
52 if(sync_ok):
52 if(sync_ok):
53 self.ipython_panel2 = IPythonXController(self)
53 self.ipython_panel2 = IPythonXController(self)
54 else:
54 else:
55 self.ipython_panel2 = None
55 self.ipython_panel2 = None
56 self.ipython_panel.setHistoryTrackerHook(self.history_panel.write)
56 self.ipython_panel.setHistoryTrackerHook(self.history_panel.write)
57 self.ipython_panel.setStatusTrackerHook(self.updateStatus)
57 self.ipython_panel.setStatusTrackerHook(self.updateStatus)
58 self.ipython_panel.setAskExitHandler(self.OnExitDlg)
58 self.ipython_panel.setAskExitHandler(self.OnExitDlg)
59 self.ipython_panel.setOptionTrackerHook(self.optionSave)
59 self.ipython_panel.setOptionTrackerHook(self.optionSave)
60
60
61 #Create a notebook to display different IPython shell implementations
61 #Create a notebook to display different IPython shell implementations
62 self.nb = wx.aui.AuiNotebook(self)
62 self.nb = wx.aui.AuiNotebook(self)
63
63
64 self.optionLoad()
64 self.optionLoad()
65
65
66 self.statusbar = self.createStatus()
66 self.statusbar = self.createStatus()
67 self.createMenu()
67 self.createMenu()
68
68
69 ########################################################################
69 ########################################################################
70 ### add the panes to the manager
70 ### add the panes to the manager
71 # main panels
71 # main panels
72 self._mgr.AddPane(self.nb , wx.CENTER, "IPython Shells")
72 self._mgr.AddPane(self.nb , wx.CENTER, "IPython Shells")
73 self.nb.AddPage(self.ipython_panel , "IPython0 Shell")
73 self.nb.AddPage(self.ipython_panel , "IPython0 Shell")
74 if(sync_ok):
74 if(sync_ok):
75 self.nb.AddPage(self.ipython_panel2, "IPython1 Synchroneous Shell")
75 self.nb.AddPage(self.ipython_panel2, "IPython1 Synchroneous Shell")
76
76
77 self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history")
77 self._mgr.AddPane(self.history_panel , wx.RIGHT, "IPython history")
78
78
79 # now we specify some panel characteristics
79 # now we specify some panel characteristics
80 self._mgr.GetPane(self.ipython_panel).CaptionVisible(True);
80 self._mgr.GetPane(self.ipython_panel).CaptionVisible(True);
81 self._mgr.GetPane(self.history_panel).CaptionVisible(True);
81 self._mgr.GetPane(self.history_panel).CaptionVisible(True);
82 self._mgr.GetPane(self.history_panel).MinSize((200,400));
82 self._mgr.GetPane(self.history_panel).MinSize((200,400));
83
83
84 # tell the manager to "commit" all the changes just made
84 # tell the manager to "commit" all the changes just made
85 self._mgr.Update()
85 self._mgr.Update()
86
86
87 #global event handling
87 #global event handling
88 self.Bind(wx.EVT_CLOSE, self.OnClose)
88 self.Bind(wx.EVT_CLOSE, self.OnClose)
89 self.Bind(wx.EVT_MENU, self.OnClose,id=wx.ID_EXIT)
89 self.Bind(wx.EVT_MENU, self.OnClose,id=wx.ID_EXIT)
90 self.Bind(wx.EVT_MENU, self.OnShowIPythonPanel,id=wx.ID_HIGHEST+1)
90 self.Bind(wx.EVT_MENU, self.OnShowIPythonPanel,id=wx.ID_HIGHEST+1)
91 self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2)
91 self.Bind(wx.EVT_MENU, self.OnShowHistoryPanel,id=wx.ID_HIGHEST+2)
92 self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3)
92 self.Bind(wx.EVT_MENU, self.OnShowAbout, id=wx.ID_HIGHEST+3)
93 self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6)
93 self.Bind(wx.EVT_MENU, self.OnShowAllPanel,id=wx.ID_HIGHEST+6)
94
94
95 warn_text = 'Hello from IPython and wxPython.\n'
95 warn_text = 'Hello from IPython and wxPython.\n'
96 warn_text +='Please Note that this work is still EXPERIMENTAL\n'
96 warn_text +='Please Note that this work is still EXPERIMENTAL\n'
97 warn_text +='It does NOT emulate currently all the IPython functions.\n'
97 warn_text +='It does NOT emulate currently all the IPython functions.\n'
98 warn_text +="\nIf you use MATPLOTLIB with show() you'll need to deactivate the THREADING option.\n"
98 warn_text +="\nIf you use MATPLOTLIB with show() you'll need to deactivate the THREADING option.\n"
99 if(not sync_ok):
99 if(not sync_ok):
100 warn_text +="\n->No twisted package detected, IPython1 example deactivated."
100 warn_text +="\n->No twisted package detected, IPython1 example deactivated."
101
101
102 dlg = wx.MessageDialog(self,
102 dlg = wx.MessageDialog(self,
103 warn_text,
103 warn_text,
104 'Warning Box',
104 'Warning Box',
105 wx.OK | wx.ICON_INFORMATION
105 wx.OK | wx.ICON_INFORMATION
106 )
106 )
107 dlg.ShowModal()
107 dlg.ShowModal()
108 dlg.Destroy()
108 dlg.Destroy()
109
109
110 def optionSave(self, name, value):
110 def optionSave(self, name, value):
111 ip = get()
111 ip = get()
112 path = ip.config.IPYTHONDIR
112 path = ip.ipython_dir
113 opt = open(path + '/options.conf','w')
113 opt = open(path + '/options.conf','w')
114
114
115 try:
115 try:
116 options_ipython_panel = self.ipython_panel.getOptions()
116 options_ipython_panel = self.ipython_panel.getOptions()
117 options_history_panel = self.history_panel.getOptions()
117 options_history_panel = self.history_panel.getOptions()
118
118
119 for key in options_ipython_panel.keys():
119 for key in options_ipython_panel.keys():
120 opt.write(key + '=' + options_ipython_panel[key]['value']+'\n')
120 opt.write(key + '=' + options_ipython_panel[key]['value']+'\n')
121 for key in options_history_panel.keys():
121 for key in options_history_panel.keys():
122 opt.write(key + '=' + options_history_panel[key]['value']+'\n')
122 opt.write(key + '=' + options_history_panel[key]['value']+'\n')
123 finally:
123 finally:
124 opt.close()
124 opt.close()
125
125
126 def optionLoad(self):
126 def optionLoad(self):
127 try:
127 try:
128 ip = get()
128 ip = get()
129 path = ip.config.IPYTHONDIR
129 path = ip.ipython_dir
130 opt = open(path + '/options.conf','r')
130 opt = open(path + '/options.conf','r')
131 lines = opt.readlines()
131 lines = opt.readlines()
132 opt.close()
132 opt.close()
133
133
134 options_ipython_panel = self.ipython_panel.getOptions()
134 options_ipython_panel = self.ipython_panel.getOptions()
135 options_history_panel = self.history_panel.getOptions()
135 options_history_panel = self.history_panel.getOptions()
136
136
137 for line in lines:
137 for line in lines:
138 key = line.split('=')[0]
138 key = line.split('=')[0]
139 value = line.split('=')[1].replace('\n','').replace('\r','')
139 value = line.split('=')[1].replace('\n','').replace('\r','')
140 if key in options_ipython_panel.keys():
140 if key in options_ipython_panel.keys():
141 options_ipython_panel[key]['value'] = value
141 options_ipython_panel[key]['value'] = value
142 elif key in options_history_panel.keys():
142 elif key in options_history_panel.keys():
143 options_history_panel[key]['value'] = value
143 options_history_panel[key]['value'] = value
144 else:
144 else:
145 print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf"
145 print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf"
146 self.ipython_panel.reloadOptions(options_ipython_panel)
146 self.ipython_panel.reloadOptions(options_ipython_panel)
147 self.history_panel.reloadOptions(options_history_panel)
147 self.history_panel.reloadOptions(options_history_panel)
148
148
149 except IOError:
149 except IOError:
150 print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values."
150 print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values."
151
151
152
152
153 def createMenu(self):
153 def createMenu(self):
154 """local method used to create one menu bar"""
154 """local method used to create one menu bar"""
155
155
156 mb = wx.MenuBar()
156 mb = wx.MenuBar()
157
157
158 file_menu = wx.Menu()
158 file_menu = wx.Menu()
159 file_menu.Append(wx.ID_EXIT, "Exit")
159 file_menu.Append(wx.ID_EXIT, "Exit")
160
160
161 view_menu = wx.Menu()
161 view_menu = wx.Menu()
162 view_menu.Append(wx.ID_HIGHEST+1, "Show IPython Panel")
162 view_menu.Append(wx.ID_HIGHEST+1, "Show IPython Panel")
163 view_menu.Append(wx.ID_HIGHEST+2, "Show History Panel")
163 view_menu.Append(wx.ID_HIGHEST+2, "Show History Panel")
164 view_menu.AppendSeparator()
164 view_menu.AppendSeparator()
165 view_menu.Append(wx.ID_HIGHEST+6, "Show All")
165 view_menu.Append(wx.ID_HIGHEST+6, "Show All")
166
166
167 about_menu = wx.Menu()
167 about_menu = wx.Menu()
168 about_menu.Append(wx.ID_HIGHEST+3, "About")
168 about_menu.Append(wx.ID_HIGHEST+3, "About")
169
169
170 mb.Append(file_menu, "File")
170 mb.Append(file_menu, "File")
171 mb.Append(view_menu, "View")
171 mb.Append(view_menu, "View")
172 mb.Append(about_menu, "About")
172 mb.Append(about_menu, "About")
173 #mb.Append(options_menu, "Options")
173 #mb.Append(options_menu, "Options")
174
174
175 self.SetMenuBar(mb)
175 self.SetMenuBar(mb)
176
176
177 def createStatus(self):
177 def createStatus(self):
178 statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
178 statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
179 statusbar.SetStatusWidths([-2, -3])
179 statusbar.SetStatusWidths([-2, -3])
180 statusbar.SetStatusText("Ready", 0)
180 statusbar.SetStatusText("Ready", 0)
181 statusbar.SetStatusText("WxIPython "+str(__version__), 1)
181 statusbar.SetStatusText("WxIPython "+str(__version__), 1)
182 return statusbar
182 return statusbar
183
183
184 def updateStatus(self,text):
184 def updateStatus(self,text):
185 states = {'IDLE':'Idle',
185 states = {'IDLE':'Idle',
186 'DO_EXECUTE_LINE':'Send command',
186 'DO_EXECUTE_LINE':'Send command',
187 'WAIT_END_OF_EXECUTION':'Running command',
187 'WAIT_END_OF_EXECUTION':'Running command',
188 'WAITING_USER_INPUT':'Waiting user input',
188 'WAITING_USER_INPUT':'Waiting user input',
189 'SHOW_DOC':'Showing doc',
189 'SHOW_DOC':'Showing doc',
190 'SHOW_PROMPT':'Showing prompt'}
190 'SHOW_PROMPT':'Showing prompt'}
191 self.statusbar.SetStatusText(states[text], 0)
191 self.statusbar.SetStatusText(states[text], 0)
192
192
193 def OnClose(self, event):
193 def OnClose(self, event):
194 """#event used to close program """
194 """#event used to close program """
195 # deinitialize the frame manager
195 # deinitialize the frame manager
196 self._mgr.UnInit()
196 self._mgr.UnInit()
197 self.Destroy()
197 self.Destroy()
198 event.Skip()
198 event.Skip()
199
199
200 def OnExitDlg(self, event):
200 def OnExitDlg(self, event):
201 dlg = wx.MessageDialog(self, 'Are you sure you want to quit WxIPython',
201 dlg = wx.MessageDialog(self, 'Are you sure you want to quit WxIPython',
202 'WxIPython exit',
202 'WxIPython exit',
203 wx.ICON_QUESTION |
203 wx.ICON_QUESTION |
204 wx.YES_NO | wx.NO_DEFAULT
204 wx.YES_NO | wx.NO_DEFAULT
205 )
205 )
206 if dlg.ShowModal() == wx.ID_YES:
206 if dlg.ShowModal() == wx.ID_YES:
207 dlg.Destroy()
207 dlg.Destroy()
208 self._mgr.UnInit()
208 self._mgr.UnInit()
209 self.Destroy()
209 self.Destroy()
210 dlg.Destroy()
210 dlg.Destroy()
211
211
212 #event to display IPython pannel
212 #event to display IPython pannel
213 def OnShowIPythonPanel(self,event):
213 def OnShowIPythonPanel(self,event):
214 """ #event to display Boxpannel """
214 """ #event to display Boxpannel """
215 self._mgr.GetPane(self.ipython_panel).Show(True)
215 self._mgr.GetPane(self.ipython_panel).Show(True)
216 self._mgr.Update()
216 self._mgr.Update()
217 #event to display History pannel
217 #event to display History pannel
218 def OnShowHistoryPanel(self,event):
218 def OnShowHistoryPanel(self,event):
219 self._mgr.GetPane(self.history_panel).Show(True)
219 self._mgr.GetPane(self.history_panel).Show(True)
220 self._mgr.Update()
220 self._mgr.Update()
221
221
222 def OnShowAllPanel(self,event):
222 def OnShowAllPanel(self,event):
223 """#event to display all Pannels"""
223 """#event to display all Pannels"""
224 self._mgr.GetPane(self.ipython_panel).Show(True)
224 self._mgr.GetPane(self.ipython_panel).Show(True)
225 self._mgr.GetPane(self.history_panel).Show(True)
225 self._mgr.GetPane(self.history_panel).Show(True)
226 self._mgr.Update()
226 self._mgr.Update()
227
227
228 def OnShowAbout(self, event):
228 def OnShowAbout(self, event):
229 # First we create and fill the info object
229 # First we create and fill the info object
230 info = wx.AboutDialogInfo()
230 info = wx.AboutDialogInfo()
231 info.Name = "WxIPython"
231 info.Name = "WxIPython"
232 info.Version = str(__version__)
232 info.Version = str(__version__)
233 info.Copyright = "(C) 2007 Laurent Dufrechou"
233 info.Copyright = "(C) 2007 Laurent Dufrechou"
234 info.Description = wordwrap(
234 info.Description = wordwrap(
235 "A Gui that embbed a multithreaded IPython Shell",
235 "A Gui that embbed a multithreaded IPython Shell",
236 350, wx.ClientDC(self))
236 350, wx.ClientDC(self))
237 info.WebSite = ("http://ipython.scipy.org/", "IPython home page")
237 info.WebSite = ("http://ipython.scipy.org/", "IPython home page")
238 info.Developers = [ "Laurent Dufrechou" ]
238 info.Developers = [ "Laurent Dufrechou" ]
239 licenseText="BSD License.\nAll rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.php"
239 licenseText="BSD License.\nAll rights reserved. This program and the accompanying materials are made available under the terms of the BSD which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.php"
240 info.License = wordwrap(licenseText, 500, wx.ClientDC(self))
240 info.License = wordwrap(licenseText, 500, wx.ClientDC(self))
241
241
242 # Then we call wx.AboutBox giving it that info object
242 # Then we call wx.AboutBox giving it that info object
243 wx.AboutBox(info)
243 wx.AboutBox(info)
244
244
245 #-----------------------------------------
245 #-----------------------------------------
246 #Creating our application
246 #Creating our application
247 #-----------------------------------------
247 #-----------------------------------------
248 class MyApp(wx.PySimpleApp):
248 class MyApp(wx.PySimpleApp):
249 """Creating our application"""
249 """Creating our application"""
250 def __init__(self, sync_ok=False):
250 def __init__(self, sync_ok=False):
251 wx.PySimpleApp.__init__(self)
251 wx.PySimpleApp.__init__(self)
252
252
253 self.frame = MyFrame(sync_ok=sync_ok)
253 self.frame = MyFrame(sync_ok=sync_ok)
254 self.frame.Show()
254 self.frame.Show()
255
255
256 #-----------------------------------------
256 #-----------------------------------------
257 #Main loop
257 #Main loop
258 #-----------------------------------------
258 #-----------------------------------------
259 def main():
259 def main():
260 app = MyApp(is_sync_frontend_ok)
260 app = MyApp(is_sync_frontend_ok)
261 app.SetTopWindow(app.frame)
261 app.SetTopWindow(app.frame)
262 app.MainLoop()
262 app.MainLoop()
263
263
264 #if launched as main program run this
264 #if launched as main program run this
265 if __name__ == '__main__':
265 if __name__ == '__main__':
266 main()
266 main()
@@ -1,766 +1,766 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3
3
4 """Facilities for handling client connections to the controller."""
4 """Facilities for handling client connections to the controller."""
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 import os
18 import os
19
19
20 from IPython.kernel.fcutil import (
20 from IPython.kernel.fcutil import (
21 Tub,
21 Tub,
22 find_furl,
22 find_furl,
23 is_valid_furl_or_file,
23 is_valid_furl_or_file,
24 validate_furl_or_file,
24 validate_furl_or_file,
25 FURLError
25 FURLError
26 )
26 )
27 from IPython.kernel.clusterdir import ClusterDir, ClusterDirError
27 from IPython.kernel.clusterdir import ClusterDir, ClusterDirError
28 from IPython.kernel.launcher import IPClusterLauncher
28 from IPython.kernel.launcher import IPClusterLauncher
29 from IPython.kernel.twistedutil import (
29 from IPython.kernel.twistedutil import (
30 gatherBoth,
30 gatherBoth,
31 make_deferred,
31 make_deferred,
32 blockingCallFromThread,
32 blockingCallFromThread,
33 sleep_deferred
33 sleep_deferred
34 )
34 )
35 from IPython.utils.importstring import import_item
35 from IPython.utils.importstring import import_item
36 from IPython.utils.genutils import get_ipython_dir
36 from IPython.utils.genutils import get_ipython_dir
37
37
38 from twisted.internet import defer
38 from twisted.internet import defer
39 from twisted.internet.defer import inlineCallbacks, returnValue
39 from twisted.internet.defer import inlineCallbacks, returnValue
40 from twisted.python import failure, log
40 from twisted.python import failure, log
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # The ClientConnector class
43 # The ClientConnector class
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 DELAY = 0.2
46 DELAY = 0.2
47 MAX_TRIES = 9
47 MAX_TRIES = 9
48
48
49
49
50 class ClientConnectorError(Exception):
50 class ClientConnectorError(Exception):
51 pass
51 pass
52
52
53
53
54 class AsyncClientConnector(object):
54 class AsyncClientConnector(object):
55 """A class for getting remote references and clients from furls.
55 """A class for getting remote references and clients from furls.
56
56
57 This start a single :class:`Tub` for all remote reference and caches
57 This start a single :class:`Tub` for all remote reference and caches
58 references.
58 references.
59 """
59 """
60
60
61 def __init__(self):
61 def __init__(self):
62 self._remote_refs = {}
62 self._remote_refs = {}
63 self.tub = Tub()
63 self.tub = Tub()
64 self.tub.startService()
64 self.tub.startService()
65
65
66 def _find_furl(self, profile='default', cluster_dir=None,
66 def _find_furl(self, profile='default', cluster_dir=None,
67 furl_or_file=None, furl_file_name=None,
67 furl_or_file=None, furl_file_name=None,
68 ipythondir=None):
68 ipython_dir=None):
69 """Find a FURL file by profile+ipythondir or cluster dir.
69 """Find a FURL file by profile+ipython_dir or cluster dir.
70
70
71 This raises an :exc:`~IPython.kernel.fcutil.FURLError` exception
71 This raises an :exc:`~IPython.kernel.fcutil.FURLError` exception
72 if a FURL file can't be found.
72 if a FURL file can't be found.
73 """
73 """
74 # Try by furl_or_file
74 # Try by furl_or_file
75 if furl_or_file is not None:
75 if furl_or_file is not None:
76 validate_furl_or_file(furl_or_file)
76 validate_furl_or_file(furl_or_file)
77 return furl_or_file
77 return furl_or_file
78
78
79 if furl_file_name is None:
79 if furl_file_name is None:
80 raise FURLError('A furl_file_name must be provided')
80 raise FURLError('A furl_file_name must be provided')
81
81
82 # Try by cluster_dir
82 # Try by cluster_dir
83 if cluster_dir is not None:
83 if cluster_dir is not None:
84 cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
84 cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
85 sdir = cluster_dir_obj.security_dir
85 sdir = cluster_dir_obj.security_dir
86 furl_file = os.path.join(sdir, furl_file_name)
86 furl_file = os.path.join(sdir, furl_file_name)
87 validate_furl_or_file(furl_file)
87 validate_furl_or_file(furl_file)
88 return furl_file
88 return furl_file
89
89
90 # Try by profile
90 # Try by profile
91 if ipythondir is None:
91 if ipython_dir is None:
92 ipythondir = get_ipython_dir()
92 ipython_dir = get_ipython_dir()
93 if profile is not None:
93 if profile is not None:
94 cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
94 cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
95 ipythondir, profile)
95 ipython_dir, profile)
96 sdir = cluster_dir_obj.security_dir
96 sdir = cluster_dir_obj.security_dir
97 furl_file = os.path.join(sdir, furl_file_name)
97 furl_file = os.path.join(sdir, furl_file_name)
98 validate_furl_or_file(furl_file)
98 validate_furl_or_file(furl_file)
99 return furl_file
99 return furl_file
100
100
101 raise FURLError('Could not find a valid FURL file.')
101 raise FURLError('Could not find a valid FURL file.')
102
102
103 def get_reference(self, furl_or_file):
103 def get_reference(self, furl_or_file):
104 """Get a remote reference using a furl or a file containing a furl.
104 """Get a remote reference using a furl or a file containing a furl.
105
105
106 Remote references are cached locally so once a remote reference
106 Remote references are cached locally so once a remote reference
107 has been retrieved for a given furl, the cached version is
107 has been retrieved for a given furl, the cached version is
108 returned.
108 returned.
109
109
110 Parameters
110 Parameters
111 ----------
111 ----------
112 furl_or_file : str
112 furl_or_file : str
113 A furl or a filename containing a furl. This should already be
113 A furl or a filename containing a furl. This should already be
114 validated, but might not yet exist.
114 validated, but might not yet exist.
115
115
116 Returns
116 Returns
117 -------
117 -------
118 A deferred to a remote reference
118 A deferred to a remote reference
119 """
119 """
120 furl = furl_or_file
120 furl = furl_or_file
121 if furl in self._remote_refs:
121 if furl in self._remote_refs:
122 d = defer.succeed(self._remote_refs[furl])
122 d = defer.succeed(self._remote_refs[furl])
123 else:
123 else:
124 d = self.tub.getReference(furl)
124 d = self.tub.getReference(furl)
125 d.addCallback(self._save_ref, furl)
125 d.addCallback(self._save_ref, furl)
126 return d
126 return d
127
127
128 def _save_ref(self, ref, furl):
128 def _save_ref(self, ref, furl):
129 """Cache a remote reference by its furl."""
129 """Cache a remote reference by its furl."""
130 self._remote_refs[furl] = ref
130 self._remote_refs[furl] = ref
131 return ref
131 return ref
132
132
133 def get_task_client(self, profile='default', cluster_dir=None,
133 def get_task_client(self, profile='default', cluster_dir=None,
134 furl_or_file=None, ipythondir=None,
134 furl_or_file=None, ipython_dir=None,
135 delay=DELAY, max_tries=MAX_TRIES):
135 delay=DELAY, max_tries=MAX_TRIES):
136 """Get the task controller client.
136 """Get the task controller client.
137
137
138 This method is a simple wrapper around `get_client` that passes in
138 This method is a simple wrapper around `get_client` that passes in
139 the default name of the task client FURL file. Usually only
139 the default name of the task client FURL file. Usually only
140 the ``profile`` option will be needed. If a FURL file can't be
140 the ``profile`` option will be needed. If a FURL file can't be
141 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
141 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
142
142
143 Parameters
143 Parameters
144 ----------
144 ----------
145 profile : str
145 profile : str
146 The name of a cluster directory profile (default="default"). The
146 The name of a cluster directory profile (default="default"). The
147 cluster directory "cluster_<profile>" will be searched for
147 cluster directory "cluster_<profile>" will be searched for
148 in ``os.getcwd()``, the ipythondir and then in the directories
148 in ``os.getcwd()``, the ipython_dir and then in the directories
149 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
149 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
150 cluster_dir : str
150 cluster_dir : str
151 The full path to a cluster directory. This is useful if profiles
151 The full path to a cluster directory. This is useful if profiles
152 are not being used.
152 are not being used.
153 furl_or_file : str
153 furl_or_file : str
154 A furl or a filename containing a FURLK. This is useful if you
154 A furl or a filename containing a FURLK. This is useful if you
155 simply know the location of the FURL file.
155 simply know the location of the FURL file.
156 ipythondir : str
156 ipython_dir : str
157 The location of the ipythondir if different from the default.
157 The location of the ipython_dir if different from the default.
158 This is used if the cluster directory is being found by profile.
158 This is used if the cluster directory is being found by profile.
159 delay : float
159 delay : float
160 The initial delay between re-connection attempts. Susequent delays
160 The initial delay between re-connection attempts. Susequent delays
161 get longer according to ``delay[i] = 1.5*delay[i-1]``.
161 get longer according to ``delay[i] = 1.5*delay[i-1]``.
162 max_tries : int
162 max_tries : int
163 The max number of re-connection attempts.
163 The max number of re-connection attempts.
164
164
165 Returns
165 Returns
166 -------
166 -------
167 A deferred to the actual client class.
167 A deferred to the actual client class.
168 """
168 """
169 return self.get_client(
169 return self.get_client(
170 profile, cluster_dir, furl_or_file,
170 profile, cluster_dir, furl_or_file,
171 'ipcontroller-tc.furl', ipythondir,
171 'ipcontroller-tc.furl', ipython_dir,
172 delay, max_tries
172 delay, max_tries
173 )
173 )
174
174
175 def get_multiengine_client(self, profile='default', cluster_dir=None,
175 def get_multiengine_client(self, profile='default', cluster_dir=None,
176 furl_or_file=None, ipythondir=None,
176 furl_or_file=None, ipython_dir=None,
177 delay=DELAY, max_tries=MAX_TRIES):
177 delay=DELAY, max_tries=MAX_TRIES):
178 """Get the multiengine controller client.
178 """Get the multiengine controller client.
179
179
180 This method is a simple wrapper around `get_client` that passes in
180 This method is a simple wrapper around `get_client` that passes in
181 the default name of the task client FURL file. Usually only
181 the default name of the task client FURL file. Usually only
182 the ``profile`` option will be needed. If a FURL file can't be
182 the ``profile`` option will be needed. If a FURL file can't be
183 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
183 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
184
184
185 Parameters
185 Parameters
186 ----------
186 ----------
187 profile : str
187 profile : str
188 The name of a cluster directory profile (default="default"). The
188 The name of a cluster directory profile (default="default"). The
189 cluster directory "cluster_<profile>" will be searched for
189 cluster directory "cluster_<profile>" will be searched for
190 in ``os.getcwd()``, the ipythondir and then in the directories
190 in ``os.getcwd()``, the ipython_dir and then in the directories
191 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
191 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
192 cluster_dir : str
192 cluster_dir : str
193 The full path to a cluster directory. This is useful if profiles
193 The full path to a cluster directory. This is useful if profiles
194 are not being used.
194 are not being used.
195 furl_or_file : str
195 furl_or_file : str
196 A furl or a filename containing a FURLK. This is useful if you
196 A furl or a filename containing a FURLK. This is useful if you
197 simply know the location of the FURL file.
197 simply know the location of the FURL file.
198 ipythondir : str
198 ipython_dir : str
199 The location of the ipythondir if different from the default.
199 The location of the ipython_dir if different from the default.
200 This is used if the cluster directory is being found by profile.
200 This is used if the cluster directory is being found by profile.
201 delay : float
201 delay : float
202 The initial delay between re-connection attempts. Susequent delays
202 The initial delay between re-connection attempts. Susequent delays
203 get longer according to ``delay[i] = 1.5*delay[i-1]``.
203 get longer according to ``delay[i] = 1.5*delay[i-1]``.
204 max_tries : int
204 max_tries : int
205 The max number of re-connection attempts.
205 The max number of re-connection attempts.
206
206
207 Returns
207 Returns
208 -------
208 -------
209 A deferred to the actual client class.
209 A deferred to the actual client class.
210 """
210 """
211 return self.get_client(
211 return self.get_client(
212 profile, cluster_dir, furl_or_file,
212 profile, cluster_dir, furl_or_file,
213 'ipcontroller-mec.furl', ipythondir,
213 'ipcontroller-mec.furl', ipython_dir,
214 delay, max_tries
214 delay, max_tries
215 )
215 )
216
216
217 def get_client(self, profile='default', cluster_dir=None,
217 def get_client(self, profile='default', cluster_dir=None,
218 furl_or_file=None, furl_file_name=None, ipythondir=None,
218 furl_or_file=None, furl_file_name=None, ipython_dir=None,
219 delay=DELAY, max_tries=MAX_TRIES):
219 delay=DELAY, max_tries=MAX_TRIES):
220 """Get a remote reference and wrap it in a client by furl.
220 """Get a remote reference and wrap it in a client by furl.
221
221
222 This method is a simple wrapper around `get_client` that passes in
222 This method is a simple wrapper around `get_client` that passes in
223 the default name of the task client FURL file. Usually only
223 the default name of the task client FURL file. Usually only
224 the ``profile`` option will be needed. If a FURL file can't be
224 the ``profile`` option will be needed. If a FURL file can't be
225 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
225 found by its profile, use ``cluster_dir`` or ``furl_or_file``.
226
226
227 Parameters
227 Parameters
228 ----------
228 ----------
229 profile : str
229 profile : str
230 The name of a cluster directory profile (default="default"). The
230 The name of a cluster directory profile (default="default"). The
231 cluster directory "cluster_<profile>" will be searched for
231 cluster directory "cluster_<profile>" will be searched for
232 in ``os.getcwd()``, the ipythondir and then in the directories
232 in ``os.getcwd()``, the ipython_dir and then in the directories
233 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
233 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
234 cluster_dir : str
234 cluster_dir : str
235 The full path to a cluster directory. This is useful if profiles
235 The full path to a cluster directory. This is useful if profiles
236 are not being used.
236 are not being used.
237 furl_or_file : str
237 furl_or_file : str
238 A furl or a filename containing a FURL. This is useful if you
238 A furl or a filename containing a FURL. This is useful if you
239 simply know the location of the FURL file.
239 simply know the location of the FURL file.
240 furl_file_name : str
240 furl_file_name : str
241 The filename (not the full path) of the FURL. This must be
241 The filename (not the full path) of the FURL. This must be
242 provided if ``furl_or_file`` is not.
242 provided if ``furl_or_file`` is not.
243 ipythondir : str
243 ipython_dir : str
244 The location of the ipythondir if different from the default.
244 The location of the ipython_dir if different from the default.
245 This is used if the cluster directory is being found by profile.
245 This is used if the cluster directory is being found by profile.
246 delay : float
246 delay : float
247 The initial delay between re-connection attempts. Susequent delays
247 The initial delay between re-connection attempts. Susequent delays
248 get longer according to ``delay[i] = 1.5*delay[i-1]``.
248 get longer according to ``delay[i] = 1.5*delay[i-1]``.
249 max_tries : int
249 max_tries : int
250 The max number of re-connection attempts.
250 The max number of re-connection attempts.
251
251
252 Returns
252 Returns
253 -------
253 -------
254 A deferred to the actual client class. Or a failure to a
254 A deferred to the actual client class. Or a failure to a
255 :exc:`FURLError`.
255 :exc:`FURLError`.
256 """
256 """
257 try:
257 try:
258 furl_file = self._find_furl(
258 furl_file = self._find_furl(
259 profile, cluster_dir, furl_or_file,
259 profile, cluster_dir, furl_or_file,
260 furl_file_name, ipythondir
260 furl_file_name, ipython_dir
261 )
261 )
262 except FURLError:
262 except FURLError:
263 return defer.fail(failure.Failure())
263 return defer.fail(failure.Failure())
264
264
265 def _wrap_remote_reference(rr):
265 def _wrap_remote_reference(rr):
266 d = rr.callRemote('get_client_name')
266 d = rr.callRemote('get_client_name')
267 d.addCallback(lambda name: import_item(name))
267 d.addCallback(lambda name: import_item(name))
268 def adapt(client_interface):
268 def adapt(client_interface):
269 client = client_interface(rr)
269 client = client_interface(rr)
270 client.tub = self.tub
270 client.tub = self.tub
271 return client
271 return client
272 d.addCallback(adapt)
272 d.addCallback(adapt)
273
273
274 return d
274 return d
275
275
276 d = self._try_to_connect(furl_file, delay, max_tries, attempt=0)
276 d = self._try_to_connect(furl_file, delay, max_tries, attempt=0)
277 d.addCallback(_wrap_remote_reference)
277 d.addCallback(_wrap_remote_reference)
278 return d
278 return d
279
279
280 @inlineCallbacks
280 @inlineCallbacks
281 def _try_to_connect(self, furl_or_file, delay, max_tries, attempt):
281 def _try_to_connect(self, furl_or_file, delay, max_tries, attempt):
282 """Try to connect to the controller with retry logic."""
282 """Try to connect to the controller with retry logic."""
283 if attempt < max_tries:
283 if attempt < max_tries:
284 log.msg("Connecting to controller [%r]: %s" % \
284 log.msg("Connecting to controller [%r]: %s" % \
285 (attempt, furl_or_file))
285 (attempt, furl_or_file))
286 try:
286 try:
287 self.furl = find_furl(furl_or_file)
287 self.furl = find_furl(furl_or_file)
288 # Uncomment this to see the FURL being tried.
288 # Uncomment this to see the FURL being tried.
289 # log.msg("FURL: %s" % self.furl)
289 # log.msg("FURL: %s" % self.furl)
290 rr = yield self.get_reference(self.furl)
290 rr = yield self.get_reference(self.furl)
291 except:
291 except:
292 if attempt==max_tries-1:
292 if attempt==max_tries-1:
293 # This will propagate the exception all the way to the top
293 # This will propagate the exception all the way to the top
294 # where it can be handled.
294 # where it can be handled.
295 raise
295 raise
296 else:
296 else:
297 yield sleep_deferred(delay)
297 yield sleep_deferred(delay)
298 rr = yield self._try_to_connect(
298 rr = yield self._try_to_connect(
299 furl_or_file, 1.5*delay, max_tries, attempt+1
299 furl_or_file, 1.5*delay, max_tries, attempt+1
300 )
300 )
301 returnValue(rr)
301 returnValue(rr)
302 else:
302 else:
303 returnValue(rr)
303 returnValue(rr)
304 else:
304 else:
305 raise ClientConnectorError(
305 raise ClientConnectorError(
306 'Could not connect to controller, max_tries (%r) exceeded. '
306 'Could not connect to controller, max_tries (%r) exceeded. '
307 'This usually means that i) the controller was not started, '
307 'This usually means that i) the controller was not started, '
308 'or ii) a firewall was blocking the client from connecting '
308 'or ii) a firewall was blocking the client from connecting '
309 'to the controller.' % max_tries
309 'to the controller.' % max_tries
310 )
310 )
311
311
312
312
313 class ClientConnector(object):
313 class ClientConnector(object):
314 """A blocking version of a client connector.
314 """A blocking version of a client connector.
315
315
316 This class creates a single :class:`Tub` instance and allows remote
316 This class creates a single :class:`Tub` instance and allows remote
317 references and client to be retrieved by their FURLs. Remote references
317 references and client to be retrieved by their FURLs. Remote references
318 are cached locally and FURL files can be found using profiles and cluster
318 are cached locally and FURL files can be found using profiles and cluster
319 directories.
319 directories.
320 """
320 """
321
321
322 def __init__(self):
322 def __init__(self):
323 self.async_cc = AsyncClientConnector()
323 self.async_cc = AsyncClientConnector()
324
324
325 def get_task_client(self, profile='default', cluster_dir=None,
325 def get_task_client(self, profile='default', cluster_dir=None,
326 furl_or_file=None, ipythondir=None,
326 furl_or_file=None, ipython_dir=None,
327 delay=DELAY, max_tries=MAX_TRIES):
327 delay=DELAY, max_tries=MAX_TRIES):
328 """Get the task client.
328 """Get the task client.
329
329
330 Usually only the ``profile`` option will be needed. If a FURL file
330 Usually only the ``profile`` option will be needed. If a FURL file
331 can't be found by its profile, use ``cluster_dir`` or
331 can't be found by its profile, use ``cluster_dir`` or
332 ``furl_or_file``.
332 ``furl_or_file``.
333
333
334 Parameters
334 Parameters
335 ----------
335 ----------
336 profile : str
336 profile : str
337 The name of a cluster directory profile (default="default"). The
337 The name of a cluster directory profile (default="default"). The
338 cluster directory "cluster_<profile>" will be searched for
338 cluster directory "cluster_<profile>" will be searched for
339 in ``os.getcwd()``, the ipythondir and then in the directories
339 in ``os.getcwd()``, the ipython_dir and then in the directories
340 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
340 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
341 cluster_dir : str
341 cluster_dir : str
342 The full path to a cluster directory. This is useful if profiles
342 The full path to a cluster directory. This is useful if profiles
343 are not being used.
343 are not being used.
344 furl_or_file : str
344 furl_or_file : str
345 A furl or a filename containing a FURLK. This is useful if you
345 A furl or a filename containing a FURLK. This is useful if you
346 simply know the location of the FURL file.
346 simply know the location of the FURL file.
347 ipythondir : str
347 ipython_dir : str
348 The location of the ipythondir if different from the default.
348 The location of the ipython_dir if different from the default.
349 This is used if the cluster directory is being found by profile.
349 This is used if the cluster directory is being found by profile.
350 delay : float
350 delay : float
351 The initial delay between re-connection attempts. Susequent delays
351 The initial delay between re-connection attempts. Susequent delays
352 get longer according to ``delay[i] = 1.5*delay[i-1]``.
352 get longer according to ``delay[i] = 1.5*delay[i-1]``.
353 max_tries : int
353 max_tries : int
354 The max number of re-connection attempts.
354 The max number of re-connection attempts.
355
355
356 Returns
356 Returns
357 -------
357 -------
358 The task client instance.
358 The task client instance.
359 """
359 """
360 client = blockingCallFromThread(
360 client = blockingCallFromThread(
361 self.async_cc.get_task_client, profile, cluster_dir,
361 self.async_cc.get_task_client, profile, cluster_dir,
362 furl_or_file, ipythondir, delay, max_tries
362 furl_or_file, ipython_dir, delay, max_tries
363 )
363 )
364 return client.adapt_to_blocking_client()
364 return client.adapt_to_blocking_client()
365
365
366 def get_multiengine_client(self, profile='default', cluster_dir=None,
366 def get_multiengine_client(self, profile='default', cluster_dir=None,
367 furl_or_file=None, ipythondir=None,
367 furl_or_file=None, ipython_dir=None,
368 delay=DELAY, max_tries=MAX_TRIES):
368 delay=DELAY, max_tries=MAX_TRIES):
369 """Get the multiengine client.
369 """Get the multiengine client.
370
370
371 Usually only the ``profile`` option will be needed. If a FURL file
371 Usually only the ``profile`` option will be needed. If a FURL file
372 can't be found by its profile, use ``cluster_dir`` or
372 can't be found by its profile, use ``cluster_dir`` or
373 ``furl_or_file``.
373 ``furl_or_file``.
374
374
375 Parameters
375 Parameters
376 ----------
376 ----------
377 profile : str
377 profile : str
378 The name of a cluster directory profile (default="default"). The
378 The name of a cluster directory profile (default="default"). The
379 cluster directory "cluster_<profile>" will be searched for
379 cluster directory "cluster_<profile>" will be searched for
380 in ``os.getcwd()``, the ipythondir and then in the directories
380 in ``os.getcwd()``, the ipython_dir and then in the directories
381 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
381 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
382 cluster_dir : str
382 cluster_dir : str
383 The full path to a cluster directory. This is useful if profiles
383 The full path to a cluster directory. This is useful if profiles
384 are not being used.
384 are not being used.
385 furl_or_file : str
385 furl_or_file : str
386 A furl or a filename containing a FURLK. This is useful if you
386 A furl or a filename containing a FURLK. This is useful if you
387 simply know the location of the FURL file.
387 simply know the location of the FURL file.
388 ipythondir : str
388 ipython_dir : str
389 The location of the ipythondir if different from the default.
389 The location of the ipython_dir if different from the default.
390 This is used if the cluster directory is being found by profile.
390 This is used if the cluster directory is being found by profile.
391 delay : float
391 delay : float
392 The initial delay between re-connection attempts. Susequent delays
392 The initial delay between re-connection attempts. Susequent delays
393 get longer according to ``delay[i] = 1.5*delay[i-1]``.
393 get longer according to ``delay[i] = 1.5*delay[i-1]``.
394 max_tries : int
394 max_tries : int
395 The max number of re-connection attempts.
395 The max number of re-connection attempts.
396
396
397 Returns
397 Returns
398 -------
398 -------
399 The multiengine client instance.
399 The multiengine client instance.
400 """
400 """
401 client = blockingCallFromThread(
401 client = blockingCallFromThread(
402 self.async_cc.get_multiengine_client, profile, cluster_dir,
402 self.async_cc.get_multiengine_client, profile, cluster_dir,
403 furl_or_file, ipythondir, delay, max_tries
403 furl_or_file, ipython_dir, delay, max_tries
404 )
404 )
405 return client.adapt_to_blocking_client()
405 return client.adapt_to_blocking_client()
406
406
407 def get_client(self, profile='default', cluster_dir=None,
407 def get_client(self, profile='default', cluster_dir=None,
408 furl_or_file=None, ipythondir=None,
408 furl_or_file=None, ipython_dir=None,
409 delay=DELAY, max_tries=MAX_TRIES):
409 delay=DELAY, max_tries=MAX_TRIES):
410 client = blockingCallFromThread(
410 client = blockingCallFromThread(
411 self.async_cc.get_client, profile, cluster_dir,
411 self.async_cc.get_client, profile, cluster_dir,
412 furl_or_file, ipythondir,
412 furl_or_file, ipython_dir,
413 delay, max_tries
413 delay, max_tries
414 )
414 )
415 return client.adapt_to_blocking_client()
415 return client.adapt_to_blocking_client()
416
416
417
417
418 class ClusterStateError(Exception):
418 class ClusterStateError(Exception):
419 pass
419 pass
420
420
421
421
422 class AsyncCluster(object):
422 class AsyncCluster(object):
423 """An class that wraps the :command:`ipcluster` script."""
423 """An class that wraps the :command:`ipcluster` script."""
424
424
425 def __init__(self, profile='default', cluster_dir=None, ipythondir=None,
425 def __init__(self, profile='default', cluster_dir=None, ipython_dir=None,
426 auto_create=False, auto_stop=True):
426 auto_create=False, auto_stop=True):
427 """Create a class to manage an IPython cluster.
427 """Create a class to manage an IPython cluster.
428
428
429 This class calls the :command:`ipcluster` command with the right
429 This class calls the :command:`ipcluster` command with the right
430 options to start an IPython cluster. Typically a cluster directory
430 options to start an IPython cluster. Typically a cluster directory
431 must be created (:command:`ipcluster create`) and configured before
431 must be created (:command:`ipcluster create`) and configured before
432 using this class. Configuration is done by editing the
432 using this class. Configuration is done by editing the
433 configuration files in the top level of the cluster directory.
433 configuration files in the top level of the cluster directory.
434
434
435 Parameters
435 Parameters
436 ----------
436 ----------
437 profile : str
437 profile : str
438 The name of a cluster directory profile (default="default"). The
438 The name of a cluster directory profile (default="default"). The
439 cluster directory "cluster_<profile>" will be searched for
439 cluster directory "cluster_<profile>" will be searched for
440 in ``os.getcwd()``, the ipythondir and then in the directories
440 in ``os.getcwd()``, the ipython_dir and then in the directories
441 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
441 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
442 cluster_dir : str
442 cluster_dir : str
443 The full path to a cluster directory. This is useful if profiles
443 The full path to a cluster directory. This is useful if profiles
444 are not being used.
444 are not being used.
445 ipythondir : str
445 ipython_dir : str
446 The location of the ipythondir if different from the default.
446 The location of the ipython_dir if different from the default.
447 This is used if the cluster directory is being found by profile.
447 This is used if the cluster directory is being found by profile.
448 auto_create : bool
448 auto_create : bool
449 Automatically create the cluster directory it is dones't exist.
449 Automatically create the cluster directory it is dones't exist.
450 This will usually only make sense if using a local cluster
450 This will usually only make sense if using a local cluster
451 (default=False).
451 (default=False).
452 auto_stop : bool
452 auto_stop : bool
453 Automatically stop the cluster when this instance is garbage
453 Automatically stop the cluster when this instance is garbage
454 collected (default=True). This is useful if you want the cluster
454 collected (default=True). This is useful if you want the cluster
455 to live beyond your current process. There is also an instance
455 to live beyond your current process. There is also an instance
456 attribute ``auto_stop`` to change this behavior.
456 attribute ``auto_stop`` to change this behavior.
457 """
457 """
458 self._setup_cluster_dir(profile, cluster_dir, ipythondir, auto_create)
458 self._setup_cluster_dir(profile, cluster_dir, ipython_dir, auto_create)
459 self.state = 'before'
459 self.state = 'before'
460 self.launcher = None
460 self.launcher = None
461 self.client_connector = None
461 self.client_connector = None
462 self.auto_stop = auto_stop
462 self.auto_stop = auto_stop
463
463
464 def __del__(self):
464 def __del__(self):
465 if self.auto_stop and self.state=='running':
465 if self.auto_stop and self.state=='running':
466 print "Auto stopping the cluster..."
466 print "Auto stopping the cluster..."
467 self.stop()
467 self.stop()
468
468
469 @property
469 @property
470 def location(self):
470 def location(self):
471 if hasattr(self, 'cluster_dir_obj'):
471 if hasattr(self, 'cluster_dir_obj'):
472 return self.cluster_dir_obj.location
472 return self.cluster_dir_obj.location
473 else:
473 else:
474 return ''
474 return ''
475
475
476 @property
476 @property
477 def running(self):
477 def running(self):
478 if self.state=='running':
478 if self.state=='running':
479 return True
479 return True
480 else:
480 else:
481 return False
481 return False
482
482
483 def _setup_cluster_dir(self, profile, cluster_dir, ipythondir, auto_create):
483 def _setup_cluster_dir(self, profile, cluster_dir, ipython_dir, auto_create):
484 if ipythondir is None:
484 if ipython_dir is None:
485 ipythondir = get_ipython_dir()
485 ipython_dir = get_ipython_dir()
486 if cluster_dir is not None:
486 if cluster_dir is not None:
487 try:
487 try:
488 self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
488 self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
489 except ClusterDirError:
489 except ClusterDirError:
490 pass
490 pass
491 if profile is not None:
491 if profile is not None:
492 try:
492 try:
493 self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
493 self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
494 ipythondir, profile)
494 ipython_dir, profile)
495 except ClusterDirError:
495 except ClusterDirError:
496 pass
496 pass
497 if auto_create or profile=='default':
497 if auto_create or profile=='default':
498 # This should call 'ipcluster create --profile default
498 # This should call 'ipcluster create --profile default
499 self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile(
499 self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile(
500 ipythondir, profile)
500 ipython_dir, profile)
501 else:
501 else:
502 raise ClusterDirError('Cluster dir not found.')
502 raise ClusterDirError('Cluster dir not found.')
503
503
504 @make_deferred
504 @make_deferred
505 def start(self, n=2):
505 def start(self, n=2):
506 """Start the IPython cluster with n engines.
506 """Start the IPython cluster with n engines.
507
507
508 Parameters
508 Parameters
509 ----------
509 ----------
510 n : int
510 n : int
511 The number of engine to start.
511 The number of engine to start.
512 """
512 """
513 # We might want to add logic to test if the cluster has started
513 # We might want to add logic to test if the cluster has started
514 # by another process....
514 # by another process....
515 if not self.state=='running':
515 if not self.state=='running':
516 self.launcher = IPClusterLauncher(os.getcwd())
516 self.launcher = IPClusterLauncher(os.getcwd())
517 self.launcher.ipcluster_n = n
517 self.launcher.ipcluster_n = n
518 self.launcher.ipcluster_subcommand = 'start'
518 self.launcher.ipcluster_subcommand = 'start'
519 d = self.launcher.start()
519 d = self.launcher.start()
520 d.addCallback(self._handle_start)
520 d.addCallback(self._handle_start)
521 return d
521 return d
522 else:
522 else:
523 raise ClusterStateError('Cluster is already running')
523 raise ClusterStateError('Cluster is already running')
524
524
525 @make_deferred
525 @make_deferred
526 def stop(self):
526 def stop(self):
527 """Stop the IPython cluster if it is running."""
527 """Stop the IPython cluster if it is running."""
528 if self.state=='running':
528 if self.state=='running':
529 d1 = self.launcher.observe_stop()
529 d1 = self.launcher.observe_stop()
530 d1.addCallback(self._handle_stop)
530 d1.addCallback(self._handle_stop)
531 d2 = self.launcher.stop()
531 d2 = self.launcher.stop()
532 return gatherBoth([d1, d2], consumeErrors=True)
532 return gatherBoth([d1, d2], consumeErrors=True)
533 else:
533 else:
534 raise ClusterStateError("Cluster not running")
534 raise ClusterStateError("Cluster not running")
535
535
536 def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES):
536 def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES):
537 """Get the multiengine client for the running cluster.
537 """Get the multiengine client for the running cluster.
538
538
539 If this fails, it means that the cluster has not finished starting.
539 If this fails, it means that the cluster has not finished starting.
540 Usually waiting a few seconds are re-trying will solve this.
540 Usually waiting a few seconds are re-trying will solve this.
541 """
541 """
542 if self.client_connector is None:
542 if self.client_connector is None:
543 self.client_connector = AsyncClientConnector()
543 self.client_connector = AsyncClientConnector()
544 return self.client_connector.get_multiengine_client(
544 return self.client_connector.get_multiengine_client(
545 cluster_dir=self.cluster_dir_obj.location,
545 cluster_dir=self.cluster_dir_obj.location,
546 delay=delay, max_tries=max_tries
546 delay=delay, max_tries=max_tries
547 )
547 )
548
548
549 def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES):
549 def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES):
550 """Get the task client for the running cluster.
550 """Get the task client for the running cluster.
551
551
552 If this fails, it means that the cluster has not finished starting.
552 If this fails, it means that the cluster has not finished starting.
553 Usually waiting a few seconds are re-trying will solve this.
553 Usually waiting a few seconds are re-trying will solve this.
554 """
554 """
555 if self.client_connector is None:
555 if self.client_connector is None:
556 self.client_connector = AsyncClientConnector()
556 self.client_connector = AsyncClientConnector()
557 return self.client_connector.get_task_client(
557 return self.client_connector.get_task_client(
558 cluster_dir=self.cluster_dir_obj.location,
558 cluster_dir=self.cluster_dir_obj.location,
559 delay=delay, max_tries=max_tries
559 delay=delay, max_tries=max_tries
560 )
560 )
561
561
562 def get_ipengine_logs(self):
562 def get_ipengine_logs(self):
563 return self.get_logs_by_name('ipengine')
563 return self.get_logs_by_name('ipengine')
564
564
565 def get_ipcontroller_logs(self):
565 def get_ipcontroller_logs(self):
566 return self.get_logs_by_name('ipcontroller')
566 return self.get_logs_by_name('ipcontroller')
567
567
568 def get_ipcluster_logs(self):
568 def get_ipcluster_logs(self):
569 return self.get_logs_by_name('ipcluster')
569 return self.get_logs_by_name('ipcluster')
570
570
571 def get_logs_by_name(self, name='ipcluster'):
571 def get_logs_by_name(self, name='ipcluster'):
572 log_dir = self.cluster_dir_obj.log_dir
572 log_dir = self.cluster_dir_obj.log_dir
573 logs = {}
573 logs = {}
574 for log in os.listdir(log_dir):
574 for log in os.listdir(log_dir):
575 if log.startswith(name + '-') and log.endswith('.log'):
575 if log.startswith(name + '-') and log.endswith('.log'):
576 with open(os.path.join(log_dir, log), 'r') as f:
576 with open(os.path.join(log_dir, log), 'r') as f:
577 logs[log] = f.read()
577 logs[log] = f.read()
578 return logs
578 return logs
579
579
580 def get_logs(self):
580 def get_logs(self):
581 d = self.get_ipcluster_logs()
581 d = self.get_ipcluster_logs()
582 d.update(self.get_ipengine_logs())
582 d.update(self.get_ipengine_logs())
583 d.update(self.get_ipcontroller_logs())
583 d.update(self.get_ipcontroller_logs())
584 return d
584 return d
585
585
586 def _handle_start(self, r):
586 def _handle_start(self, r):
587 self.state = 'running'
587 self.state = 'running'
588
588
589 def _handle_stop(self, r):
589 def _handle_stop(self, r):
590 self.state = 'after'
590 self.state = 'after'
591
591
592
592
593 class Cluster(object):
593 class Cluster(object):
594
594
595
595
596 def __init__(self, profile='default', cluster_dir=None, ipythondir=None,
596 def __init__(self, profile='default', cluster_dir=None, ipython_dir=None,
597 auto_create=False, auto_stop=True):
597 auto_create=False, auto_stop=True):
598 """Create a class to manage an IPython cluster.
598 """Create a class to manage an IPython cluster.
599
599
600 This class calls the :command:`ipcluster` command with the right
600 This class calls the :command:`ipcluster` command with the right
601 options to start an IPython cluster. Typically a cluster directory
601 options to start an IPython cluster. Typically a cluster directory
602 must be created (:command:`ipcluster create`) and configured before
602 must be created (:command:`ipcluster create`) and configured before
603 using this class. Configuration is done by editing the
603 using this class. Configuration is done by editing the
604 configuration files in the top level of the cluster directory.
604 configuration files in the top level of the cluster directory.
605
605
606 Parameters
606 Parameters
607 ----------
607 ----------
608 profile : str
608 profile : str
609 The name of a cluster directory profile (default="default"). The
609 The name of a cluster directory profile (default="default"). The
610 cluster directory "cluster_<profile>" will be searched for
610 cluster directory "cluster_<profile>" will be searched for
611 in ``os.getcwd()``, the ipythondir and then in the directories
611 in ``os.getcwd()``, the ipython_dir and then in the directories
612 listed in the :env:`IPCLUSTERDIR_PATH` environment variable.
612 listed in the :env:`IPCLUSTER_DIR_PATH` environment variable.
613 cluster_dir : str
613 cluster_dir : str
614 The full path to a cluster directory. This is useful if profiles
614 The full path to a cluster directory. This is useful if profiles
615 are not being used.
615 are not being used.
616 ipythondir : str
616 ipython_dir : str
617 The location of the ipythondir if different from the default.
617 The location of the ipython_dir if different from the default.
618 This is used if the cluster directory is being found by profile.
618 This is used if the cluster directory is being found by profile.
619 auto_create : bool
619 auto_create : bool
620 Automatically create the cluster directory it is dones't exist.
620 Automatically create the cluster directory it is dones't exist.
621 This will usually only make sense if using a local cluster
621 This will usually only make sense if using a local cluster
622 (default=False).
622 (default=False).
623 auto_stop : bool
623 auto_stop : bool
624 Automatically stop the cluster when this instance is garbage
624 Automatically stop the cluster when this instance is garbage
625 collected (default=True). This is useful if you want the cluster
625 collected (default=True). This is useful if you want the cluster
626 to live beyond your current process. There is also an instance
626 to live beyond your current process. There is also an instance
627 attribute ``auto_stop`` to change this behavior.
627 attribute ``auto_stop`` to change this behavior.
628 """
628 """
629 self.async_cluster = AsyncCluster(
629 self.async_cluster = AsyncCluster(
630 profile, cluster_dir, ipythondir, auto_create, auto_stop
630 profile, cluster_dir, ipython_dir, auto_create, auto_stop
631 )
631 )
632 self.cluster_dir_obj = self.async_cluster.cluster_dir_obj
632 self.cluster_dir_obj = self.async_cluster.cluster_dir_obj
633 self.client_connector = None
633 self.client_connector = None
634
634
635 def _set_auto_stop(self, value):
635 def _set_auto_stop(self, value):
636 self.async_cluster.auto_stop = value
636 self.async_cluster.auto_stop = value
637
637
638 def _get_auto_stop(self):
638 def _get_auto_stop(self):
639 return self.async_cluster.auto_stop
639 return self.async_cluster.auto_stop
640
640
641 auto_stop = property(_get_auto_stop, _set_auto_stop)
641 auto_stop = property(_get_auto_stop, _set_auto_stop)
642
642
643 @property
643 @property
644 def location(self):
644 def location(self):
645 return self.async_cluster.location
645 return self.async_cluster.location
646
646
647 @property
647 @property
648 def running(self):
648 def running(self):
649 return self.async_cluster.running
649 return self.async_cluster.running
650
650
651 def start(self, n=2):
651 def start(self, n=2):
652 """Start the IPython cluster with n engines.
652 """Start the IPython cluster with n engines.
653
653
654 Parameters
654 Parameters
655 ----------
655 ----------
656 n : int
656 n : int
657 The number of engine to start.
657 The number of engine to start.
658 """
658 """
659 return blockingCallFromThread(self.async_cluster.start, n)
659 return blockingCallFromThread(self.async_cluster.start, n)
660
660
661 def stop(self):
661 def stop(self):
662 """Stop the IPython cluster if it is running."""
662 """Stop the IPython cluster if it is running."""
663 return blockingCallFromThread(self.async_cluster.stop)
663 return blockingCallFromThread(self.async_cluster.stop)
664
664
665 def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES):
665 def get_multiengine_client(self, delay=DELAY, max_tries=MAX_TRIES):
666 """Get the multiengine client for the running cluster.
666 """Get the multiengine client for the running cluster.
667
667
668 This will try to attempt to the controller multiple times. If this
668 This will try to attempt to the controller multiple times. If this
669 fails altogether, try looking at the following:
669 fails altogether, try looking at the following:
670 * Make sure the controller is starting properly by looking at its
670 * Make sure the controller is starting properly by looking at its
671 log files.
671 log files.
672 * Make sure the controller is writing its FURL file in the location
672 * Make sure the controller is writing its FURL file in the location
673 expected by the client.
673 expected by the client.
674 * Make sure a firewall on the controller's host is not blocking the
674 * Make sure a firewall on the controller's host is not blocking the
675 client from connecting.
675 client from connecting.
676
676
677 Parameters
677 Parameters
678 ----------
678 ----------
679 delay : float
679 delay : float
680 The initial delay between re-connection attempts. Susequent delays
680 The initial delay between re-connection attempts. Susequent delays
681 get longer according to ``delay[i] = 1.5*delay[i-1]``.
681 get longer according to ``delay[i] = 1.5*delay[i-1]``.
682 max_tries : int
682 max_tries : int
683 The max number of re-connection attempts.
683 The max number of re-connection attempts.
684 """
684 """
685 if self.client_connector is None:
685 if self.client_connector is None:
686 self.client_connector = ClientConnector()
686 self.client_connector = ClientConnector()
687 return self.client_connector.get_multiengine_client(
687 return self.client_connector.get_multiengine_client(
688 cluster_dir=self.cluster_dir_obj.location,
688 cluster_dir=self.cluster_dir_obj.location,
689 delay=delay, max_tries=max_tries
689 delay=delay, max_tries=max_tries
690 )
690 )
691
691
692 def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES):
692 def get_task_client(self, delay=DELAY, max_tries=MAX_TRIES):
693 """Get the task client for the running cluster.
693 """Get the task client for the running cluster.
694
694
695 This will try to attempt to the controller multiple times. If this
695 This will try to attempt to the controller multiple times. If this
696 fails altogether, try looking at the following:
696 fails altogether, try looking at the following:
697 * Make sure the controller is starting properly by looking at its
697 * Make sure the controller is starting properly by looking at its
698 log files.
698 log files.
699 * Make sure the controller is writing its FURL file in the location
699 * Make sure the controller is writing its FURL file in the location
700 expected by the client.
700 expected by the client.
701 * Make sure a firewall on the controller's host is not blocking the
701 * Make sure a firewall on the controller's host is not blocking the
702 client from connecting.
702 client from connecting.
703
703
704 Parameters
704 Parameters
705 ----------
705 ----------
706 delay : float
706 delay : float
707 The initial delay between re-connection attempts. Susequent delays
707 The initial delay between re-connection attempts. Susequent delays
708 get longer according to ``delay[i] = 1.5*delay[i-1]``.
708 get longer according to ``delay[i] = 1.5*delay[i-1]``.
709 max_tries : int
709 max_tries : int
710 The max number of re-connection attempts.
710 The max number of re-connection attempts.
711 """
711 """
712 if self.client_connector is None:
712 if self.client_connector is None:
713 self.client_connector = ClientConnector()
713 self.client_connector = ClientConnector()
714 return self.client_connector.get_task_client(
714 return self.client_connector.get_task_client(
715 cluster_dir=self.cluster_dir_obj.location,
715 cluster_dir=self.cluster_dir_obj.location,
716 delay=delay, max_tries=max_tries
716 delay=delay, max_tries=max_tries
717 )
717 )
718
718
719 def __repr__(self):
719 def __repr__(self):
720 s = "<Cluster(running=%r, location=%s)" % (self.running, self.location)
720 s = "<Cluster(running=%r, location=%s)" % (self.running, self.location)
721 return s
721 return s
722
722
723 def get_logs_by_name(self, name='ipcluter'):
723 def get_logs_by_name(self, name='ipcluter'):
724 """Get a dict of logs by process name (ipcluster, ipengine, etc.)"""
724 """Get a dict of logs by process name (ipcluster, ipengine, etc.)"""
725 return self.async_cluster.get_logs_by_name(name)
725 return self.async_cluster.get_logs_by_name(name)
726
726
727 def get_ipengine_logs(self):
727 def get_ipengine_logs(self):
728 """Get a dict of logs for all engines in this cluster."""
728 """Get a dict of logs for all engines in this cluster."""
729 return self.async_cluster.get_ipengine_logs()
729 return self.async_cluster.get_ipengine_logs()
730
730
731 def get_ipcontroller_logs(self):
731 def get_ipcontroller_logs(self):
732 """Get a dict of logs for the controller in this cluster."""
732 """Get a dict of logs for the controller in this cluster."""
733 return self.async_cluster.get_ipcontroller_logs()
733 return self.async_cluster.get_ipcontroller_logs()
734
734
735 def get_ipcluster_logs(self):
735 def get_ipcluster_logs(self):
736 """Get a dict of the ipcluster logs for this cluster."""
736 """Get a dict of the ipcluster logs for this cluster."""
737 return self.async_cluster.get_ipcluster_logs()
737 return self.async_cluster.get_ipcluster_logs()
738
738
739 def get_logs(self):
739 def get_logs(self):
740 """Get a dict of all logs for this cluster."""
740 """Get a dict of all logs for this cluster."""
741 return self.async_cluster.get_logs()
741 return self.async_cluster.get_logs()
742
742
743 def _print_logs(self, logs):
743 def _print_logs(self, logs):
744 for k, v in logs.iteritems():
744 for k, v in logs.iteritems():
745 print "==================================="
745 print "==================================="
746 print "Logfile: %s" % k
746 print "Logfile: %s" % k
747 print "==================================="
747 print "==================================="
748 print v
748 print v
749 print
749 print
750
750
751 def print_ipengine_logs(self):
751 def print_ipengine_logs(self):
752 """Print the ipengine logs for this cluster to stdout."""
752 """Print the ipengine logs for this cluster to stdout."""
753 self._print_logs(self.get_ipengine_logs())
753 self._print_logs(self.get_ipengine_logs())
754
754
755 def print_ipcontroller_logs(self):
755 def print_ipcontroller_logs(self):
756 """Print the ipcontroller logs for this cluster to stdout."""
756 """Print the ipcontroller logs for this cluster to stdout."""
757 self._print_logs(self.get_ipcontroller_logs())
757 self._print_logs(self.get_ipcontroller_logs())
758
758
759 def print_ipcluster_logs(self):
759 def print_ipcluster_logs(self):
760 """Print the ipcluster logs for this cluster to stdout."""
760 """Print the ipcluster logs for this cluster to stdout."""
761 self._print_logs(self.get_ipcluster_logs())
761 self._print_logs(self.get_ipcluster_logs())
762
762
763 def print_logs(self):
763 def print_logs(self):
764 """Print all the logs for this cluster to stdout."""
764 """Print all the logs for this cluster to stdout."""
765 self._print_logs(self.get_logs())
765 self._print_logs(self.get_logs())
766
766
@@ -1,461 +1,461 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The IPython cluster directory
4 The IPython cluster directory
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from __future__ import with_statement
18 from __future__ import with_statement
19
19
20 import os
20 import os
21 import shutil
21 import shutil
22 import sys
22 import sys
23
23
24 from twisted.python import log
24 from twisted.python import log
25
25
26 from IPython.core import release
26 from IPython.core import release
27 from IPython.config.loader import PyFileConfigLoader
27 from IPython.config.loader import PyFileConfigLoader
28 from IPython.core.application import Application
28 from IPython.core.application import Application
29 from IPython.core.component import Component
29 from IPython.core.component import Component
30 from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault
30 from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault
31 from IPython.utils.traitlets import Unicode, Bool
31 from IPython.utils.traitlets import Unicode, Bool
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Imports
34 # Imports
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 class ClusterDirError(Exception):
38 class ClusterDirError(Exception):
39 pass
39 pass
40
40
41
41
42 class PIDFileError(Exception):
42 class PIDFileError(Exception):
43 pass
43 pass
44
44
45
45
46 class ClusterDir(Component):
46 class ClusterDir(Component):
47 """An object to manage the cluster directory and its resources.
47 """An object to manage the cluster directory and its resources.
48
48
49 The cluster directory is used by :command:`ipcontroller`,
49 The cluster directory is used by :command:`ipcontroller`,
50 :command:`ipcontroller` and :command:`ipcontroller` to manage the
50 :command:`ipcontroller` and :command:`ipcontroller` to manage the
51 configuration, logging and security of these applications.
51 configuration, logging and security of these applications.
52
52
53 This object knows how to find, create and manage these directories. This
53 This object knows how to find, create and manage these directories. This
54 should be used by any code that want's to handle cluster directories.
54 should be used by any code that want's to handle cluster directories.
55 """
55 """
56
56
57 security_dir_name = Unicode('security')
57 security_dir_name = Unicode('security')
58 log_dir_name = Unicode('log')
58 log_dir_name = Unicode('log')
59 pid_dir_name = Unicode('pid')
59 pid_dir_name = Unicode('pid')
60 security_dir = Unicode(u'')
60 security_dir = Unicode(u'')
61 log_dir = Unicode(u'')
61 log_dir = Unicode(u'')
62 pid_dir = Unicode(u'')
62 pid_dir = Unicode(u'')
63 location = Unicode(u'')
63 location = Unicode(u'')
64
64
65 def __init__(self, location):
65 def __init__(self, location):
66 super(ClusterDir, self).__init__(None)
66 super(ClusterDir, self).__init__(None)
67 self.location = location
67 self.location = location
68
68
69 def _location_changed(self, name, old, new):
69 def _location_changed(self, name, old, new):
70 if not os.path.isdir(new):
70 if not os.path.isdir(new):
71 os.makedirs(new, mode=0777)
71 os.makedirs(new, mode=0777)
72 else:
72 else:
73 os.chmod(new, 0777)
73 os.chmod(new, 0777)
74 self.security_dir = os.path.join(new, self.security_dir_name)
74 self.security_dir = os.path.join(new, self.security_dir_name)
75 self.log_dir = os.path.join(new, self.log_dir_name)
75 self.log_dir = os.path.join(new, self.log_dir_name)
76 self.pid_dir = os.path.join(new, self.pid_dir_name)
76 self.pid_dir = os.path.join(new, self.pid_dir_name)
77 self.check_dirs()
77 self.check_dirs()
78
78
79 def _log_dir_changed(self, name, old, new):
79 def _log_dir_changed(self, name, old, new):
80 self.check_log_dir()
80 self.check_log_dir()
81
81
82 def check_log_dir(self):
82 def check_log_dir(self):
83 if not os.path.isdir(self.log_dir):
83 if not os.path.isdir(self.log_dir):
84 os.mkdir(self.log_dir, 0777)
84 os.mkdir(self.log_dir, 0777)
85 else:
85 else:
86 os.chmod(self.log_dir, 0777)
86 os.chmod(self.log_dir, 0777)
87
87
88 def _security_dir_changed(self, name, old, new):
88 def _security_dir_changed(self, name, old, new):
89 self.check_security_dir()
89 self.check_security_dir()
90
90
91 def check_security_dir(self):
91 def check_security_dir(self):
92 if not os.path.isdir(self.security_dir):
92 if not os.path.isdir(self.security_dir):
93 os.mkdir(self.security_dir, 0700)
93 os.mkdir(self.security_dir, 0700)
94 else:
94 else:
95 os.chmod(self.security_dir, 0700)
95 os.chmod(self.security_dir, 0700)
96
96
97 def _pid_dir_changed(self, name, old, new):
97 def _pid_dir_changed(self, name, old, new):
98 self.check_pid_dir()
98 self.check_pid_dir()
99
99
100 def check_pid_dir(self):
100 def check_pid_dir(self):
101 if not os.path.isdir(self.pid_dir):
101 if not os.path.isdir(self.pid_dir):
102 os.mkdir(self.pid_dir, 0700)
102 os.mkdir(self.pid_dir, 0700)
103 else:
103 else:
104 os.chmod(self.pid_dir, 0700)
104 os.chmod(self.pid_dir, 0700)
105
105
106 def check_dirs(self):
106 def check_dirs(self):
107 self.check_security_dir()
107 self.check_security_dir()
108 self.check_log_dir()
108 self.check_log_dir()
109 self.check_pid_dir()
109 self.check_pid_dir()
110
110
111 def load_config_file(self, filename):
111 def load_config_file(self, filename):
112 """Load a config file from the top level of the cluster dir.
112 """Load a config file from the top level of the cluster dir.
113
113
114 Parameters
114 Parameters
115 ----------
115 ----------
116 filename : unicode or str
116 filename : unicode or str
117 The filename only of the config file that must be located in
117 The filename only of the config file that must be located in
118 the top-level of the cluster directory.
118 the top-level of the cluster directory.
119 """
119 """
120 loader = PyFileConfigLoader(filename, self.location)
120 loader = PyFileConfigLoader(filename, self.location)
121 return loader.load_config()
121 return loader.load_config()
122
122
123 def copy_config_file(self, config_file, path=None, overwrite=False):
123 def copy_config_file(self, config_file, path=None, overwrite=False):
124 """Copy a default config file into the active cluster directory.
124 """Copy a default config file into the active cluster directory.
125
125
126 Default configuration files are kept in :mod:`IPython.config.default`.
126 Default configuration files are kept in :mod:`IPython.config.default`.
127 This function moves these from that location to the working cluster
127 This function moves these from that location to the working cluster
128 directory.
128 directory.
129 """
129 """
130 if path is None:
130 if path is None:
131 import IPython.config.default
131 import IPython.config.default
132 path = IPython.config.default.__file__.split(os.path.sep)[:-1]
132 path = IPython.config.default.__file__.split(os.path.sep)[:-1]
133 path = os.path.sep.join(path)
133 path = os.path.sep.join(path)
134 src = os.path.join(path, config_file)
134 src = os.path.join(path, config_file)
135 dst = os.path.join(self.location, config_file)
135 dst = os.path.join(self.location, config_file)
136 if not os.path.isfile(dst) or overwrite:
136 if not os.path.isfile(dst) or overwrite:
137 shutil.copy(src, dst)
137 shutil.copy(src, dst)
138
138
139 def copy_all_config_files(self, path=None, overwrite=False):
139 def copy_all_config_files(self, path=None, overwrite=False):
140 """Copy all config files into the active cluster directory."""
140 """Copy all config files into the active cluster directory."""
141 for f in ['ipcontroller_config.py', 'ipengine_config.py',
141 for f in ['ipcontroller_config.py', 'ipengine_config.py',
142 'ipcluster_config.py']:
142 'ipcluster_config.py']:
143 self.copy_config_file(f, path=path, overwrite=overwrite)
143 self.copy_config_file(f, path=path, overwrite=overwrite)
144
144
145 @classmethod
145 @classmethod
146 def create_cluster_dir(csl, cluster_dir):
146 def create_cluster_dir(csl, cluster_dir):
147 """Create a new cluster directory given a full path.
147 """Create a new cluster directory given a full path.
148
148
149 Parameters
149 Parameters
150 ----------
150 ----------
151 cluster_dir : str
151 cluster_dir : str
152 The full path to the cluster directory. If it does exist, it will
152 The full path to the cluster directory. If it does exist, it will
153 be used. If not, it will be created.
153 be used. If not, it will be created.
154 """
154 """
155 return ClusterDir(cluster_dir)
155 return ClusterDir(cluster_dir)
156
156
157 @classmethod
157 @classmethod
158 def create_cluster_dir_by_profile(cls, path, profile='default'):
158 def create_cluster_dir_by_profile(cls, path, profile='default'):
159 """Create a cluster dir by profile name and path.
159 """Create a cluster dir by profile name and path.
160
160
161 Parameters
161 Parameters
162 ----------
162 ----------
163 path : str
163 path : str
164 The path (directory) to put the cluster directory in.
164 The path (directory) to put the cluster directory in.
165 profile : str
165 profile : str
166 The name of the profile. The name of the cluster directory will
166 The name of the profile. The name of the cluster directory will
167 be "cluster_<profile>".
167 be "cluster_<profile>".
168 """
168 """
169 if not os.path.isdir(path):
169 if not os.path.isdir(path):
170 raise ClusterDirError('Directory not found: %s' % path)
170 raise ClusterDirError('Directory not found: %s' % path)
171 cluster_dir = os.path.join(path, 'cluster_' + profile)
171 cluster_dir = os.path.join(path, 'cluster_' + profile)
172 return ClusterDir(cluster_dir)
172 return ClusterDir(cluster_dir)
173
173
174 @classmethod
174 @classmethod
175 def find_cluster_dir_by_profile(cls, ipythondir, profile='default'):
175 def find_cluster_dir_by_profile(cls, ipython_dir, profile='default'):
176 """Find an existing cluster dir by profile name, return its ClusterDir.
176 """Find an existing cluster dir by profile name, return its ClusterDir.
177
177
178 This searches through a sequence of paths for a cluster dir. If it
178 This searches through a sequence of paths for a cluster dir. If it
179 is not found, a :class:`ClusterDirError` exception will be raised.
179 is not found, a :class:`ClusterDirError` exception will be raised.
180
180
181 The search path algorithm is:
181 The search path algorithm is:
182 1. ``os.getcwd()``
182 1. ``os.getcwd()``
183 2. ``ipythondir``
183 2. ``ipython_dir``
184 3. The directories found in the ":" separated
184 3. The directories found in the ":" separated
185 :env:`IPCLUSTERDIR_PATH` environment variable.
185 :env:`IPCLUSTER_DIR_PATH` environment variable.
186
186
187 Parameters
187 Parameters
188 ----------
188 ----------
189 ipythondir : unicode or str
189 ipython_dir : unicode or str
190 The IPython directory to use.
190 The IPython directory to use.
191 profile : unicode or str
191 profile : unicode or str
192 The name of the profile. The name of the cluster directory
192 The name of the profile. The name of the cluster directory
193 will be "cluster_<profile>".
193 will be "cluster_<profile>".
194 """
194 """
195 dirname = 'cluster_' + profile
195 dirname = 'cluster_' + profile
196 cluster_dir_paths = os.environ.get('IPCLUSTERDIR_PATH','')
196 cluster_dir_paths = os.environ.get('IPCLUSTER_DIR_PATH','')
197 if cluster_dir_paths:
197 if cluster_dir_paths:
198 cluster_dir_paths = cluster_dir_paths.split(':')
198 cluster_dir_paths = cluster_dir_paths.split(':')
199 else:
199 else:
200 cluster_dir_paths = []
200 cluster_dir_paths = []
201 paths = [os.getcwd(), ipythondir] + cluster_dir_paths
201 paths = [os.getcwd(), ipython_dir] + cluster_dir_paths
202 for p in paths:
202 for p in paths:
203 cluster_dir = os.path.join(p, dirname)
203 cluster_dir = os.path.join(p, dirname)
204 if os.path.isdir(cluster_dir):
204 if os.path.isdir(cluster_dir):
205 return ClusterDir(cluster_dir)
205 return ClusterDir(cluster_dir)
206 else:
206 else:
207 raise ClusterDirError('Cluster directory not found in paths: %s' % dirname)
207 raise ClusterDirError('Cluster directory not found in paths: %s' % dirname)
208
208
209 @classmethod
209 @classmethod
210 def find_cluster_dir(cls, cluster_dir):
210 def find_cluster_dir(cls, cluster_dir):
211 """Find/create a cluster dir and return its ClusterDir.
211 """Find/create a cluster dir and return its ClusterDir.
212
212
213 This will create the cluster directory if it doesn't exist.
213 This will create the cluster directory if it doesn't exist.
214
214
215 Parameters
215 Parameters
216 ----------
216 ----------
217 cluster_dir : unicode or str
217 cluster_dir : unicode or str
218 The path of the cluster directory. This is expanded using
218 The path of the cluster directory. This is expanded using
219 :func:`os.path.expandvars` and :func:`os.path.expanduser`.
219 :func:`os.path.expandvars` and :func:`os.path.expanduser`.
220 """
220 """
221 cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir))
221 cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir))
222 if not os.path.isdir(cluster_dir):
222 if not os.path.isdir(cluster_dir):
223 raise ClusterDirError('Cluster directory not found: %s' % cluster_dir)
223 raise ClusterDirError('Cluster directory not found: %s' % cluster_dir)
224 return ClusterDir(cluster_dir)
224 return ClusterDir(cluster_dir)
225
225
226
226
227 class AppWithClusterDirArgParseConfigLoader(ArgParseConfigLoader):
227 class AppWithClusterDirArgParseConfigLoader(ArgParseConfigLoader):
228 """Default command line options for IPython cluster applications."""
228 """Default command line options for IPython cluster applications."""
229
229
230 def _add_other_arguments(self):
230 def _add_other_arguments(self):
231 self.parser.add_argument('--ipython-dir',
231 self.parser.add_argument('--ipython-dir',
232 dest='Global.ipythondir',type=str,
232 dest='Global.ipython_dir',type=str,
233 help='Set to override default location of Global.ipythondir.',
233 help='Set to override default location of Global.ipython_dir.',
234 default=NoConfigDefault,
234 default=NoConfigDefault,
235 metavar='Global.ipythondir'
235 metavar='Global.ipython_dir'
236 )
236 )
237 self.parser.add_argument('-p', '--profile',
237 self.parser.add_argument('-p', '--profile',
238 dest='Global.profile',type=str,
238 dest='Global.profile',type=str,
239 help='The string name of the profile to be used. This determines '
239 help='The string name of the profile to be used. This determines '
240 'the name of the cluster dir as: cluster_<profile>. The default profile '
240 'the name of the cluster dir as: cluster_<profile>. The default profile '
241 'is named "default". The cluster directory is resolve this way '
241 'is named "default". The cluster directory is resolve this way '
242 'if the --cluster-dir option is not used.',
242 'if the --cluster-dir option is not used.',
243 default=NoConfigDefault,
243 default=NoConfigDefault,
244 metavar='Global.profile'
244 metavar='Global.profile'
245 )
245 )
246 self.parser.add_argument('--log-level',
246 self.parser.add_argument('--log-level',
247 dest="Global.log_level",type=int,
247 dest="Global.log_level",type=int,
248 help='Set the log level (0,10,20,30,40,50). Default is 30.',
248 help='Set the log level (0,10,20,30,40,50). Default is 30.',
249 default=NoConfigDefault,
249 default=NoConfigDefault,
250 metavar="Global.log_level"
250 metavar="Global.log_level"
251 )
251 )
252 self.parser.add_argument('--cluster-dir',
252 self.parser.add_argument('--cluster-dir',
253 dest='Global.cluster_dir',type=str,
253 dest='Global.cluster_dir',type=str,
254 help='Set the cluster dir. This overrides the logic used by the '
254 help='Set the cluster dir. This overrides the logic used by the '
255 '--profile option.',
255 '--profile option.',
256 default=NoConfigDefault,
256 default=NoConfigDefault,
257 metavar='Global.cluster_dir'
257 metavar='Global.cluster_dir'
258 )
258 )
259 self.parser.add_argument('--clean-logs',
259 self.parser.add_argument('--clean-logs',
260 dest='Global.clean_logs', action='store_true',
260 dest='Global.clean_logs', action='store_true',
261 help='Delete old log flies before starting.',
261 help='Delete old log flies before starting.',
262 default=NoConfigDefault
262 default=NoConfigDefault
263 )
263 )
264 self.parser.add_argument('--no-clean-logs',
264 self.parser.add_argument('--no-clean-logs',
265 dest='Global.clean_logs', action='store_false',
265 dest='Global.clean_logs', action='store_false',
266 help="Don't Delete old log flies before starting.",
266 help="Don't Delete old log flies before starting.",
267 default=NoConfigDefault
267 default=NoConfigDefault
268 )
268 )
269
269
270 class ApplicationWithClusterDir(Application):
270 class ApplicationWithClusterDir(Application):
271 """An application that puts everything into a cluster directory.
271 """An application that puts everything into a cluster directory.
272
272
273 Instead of looking for things in the ipythondir, this type of application
273 Instead of looking for things in the ipython_dir, this type of application
274 will use its own private directory called the "cluster directory"
274 will use its own private directory called the "cluster directory"
275 for things like config files, log files, etc.
275 for things like config files, log files, etc.
276
276
277 The cluster directory is resolved as follows:
277 The cluster directory is resolved as follows:
278
278
279 * If the ``--cluster-dir`` option is given, it is used.
279 * If the ``--cluster-dir`` option is given, it is used.
280 * If ``--cluster-dir`` is not given, the application directory is
280 * If ``--cluster-dir`` is not given, the application directory is
281 resolve using the profile name as ``cluster_<profile>``. The search
281 resolve using the profile name as ``cluster_<profile>``. The search
282 path for this directory is then i) cwd if it is found there
282 path for this directory is then i) cwd if it is found there
283 and ii) in ipythondir otherwise.
283 and ii) in ipython_dir otherwise.
284
284
285 The config file for the application is to be put in the cluster
285 The config file for the application is to be put in the cluster
286 dir and named the value of the ``config_file_name`` class attribute.
286 dir and named the value of the ``config_file_name`` class attribute.
287 """
287 """
288
288
289 auto_create_cluster_dir = True
289 auto_create_cluster_dir = True
290
290
291 def create_default_config(self):
291 def create_default_config(self):
292 super(ApplicationWithClusterDir, self).create_default_config()
292 super(ApplicationWithClusterDir, self).create_default_config()
293 self.default_config.Global.profile = 'default'
293 self.default_config.Global.profile = 'default'
294 self.default_config.Global.cluster_dir = ''
294 self.default_config.Global.cluster_dir = ''
295 self.default_config.Global.log_to_file = False
295 self.default_config.Global.log_to_file = False
296 self.default_config.Global.clean_logs = False
296 self.default_config.Global.clean_logs = False
297
297
298 def create_command_line_config(self):
298 def create_command_line_config(self):
299 """Create and return a command line config loader."""
299 """Create and return a command line config loader."""
300 return AppWithClusterDirArgParseConfigLoader(
300 return AppWithClusterDirArgParseConfigLoader(
301 description=self.description,
301 description=self.description,
302 version=release.version
302 version=release.version
303 )
303 )
304
304
305 def find_resources(self):
305 def find_resources(self):
306 """This resolves the cluster directory.
306 """This resolves the cluster directory.
307
307
308 This tries to find the cluster directory and if successful, it will
308 This tries to find the cluster directory and if successful, it will
309 have done:
309 have done:
310 * Sets ``self.cluster_dir_obj`` to the :class:`ClusterDir` object for
310 * Sets ``self.cluster_dir_obj`` to the :class:`ClusterDir` object for
311 the application.
311 the application.
312 * Sets ``self.cluster_dir`` attribute of the application and config
312 * Sets ``self.cluster_dir`` attribute of the application and config
313 objects.
313 objects.
314
314
315 The algorithm used for this is as follows:
315 The algorithm used for this is as follows:
316 1. Try ``Global.cluster_dir``.
316 1. Try ``Global.cluster_dir``.
317 2. Try using ``Global.profile``.
317 2. Try using ``Global.profile``.
318 3. If both of these fail and ``self.auto_create_cluster_dir`` is
318 3. If both of these fail and ``self.auto_create_cluster_dir`` is
319 ``True``, then create the new cluster dir in the IPython directory.
319 ``True``, then create the new cluster dir in the IPython directory.
320 4. If all fails, then raise :class:`ClusterDirError`.
320 4. If all fails, then raise :class:`ClusterDirError`.
321 """
321 """
322
322
323 try:
323 try:
324 cluster_dir = self.command_line_config.Global.cluster_dir
324 cluster_dir = self.command_line_config.Global.cluster_dir
325 except AttributeError:
325 except AttributeError:
326 cluster_dir = self.default_config.Global.cluster_dir
326 cluster_dir = self.default_config.Global.cluster_dir
327 cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir))
327 cluster_dir = os.path.expandvars(os.path.expanduser(cluster_dir))
328 try:
328 try:
329 self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
329 self.cluster_dir_obj = ClusterDir.find_cluster_dir(cluster_dir)
330 except ClusterDirError:
330 except ClusterDirError:
331 pass
331 pass
332 else:
332 else:
333 self.log.info('Using existing cluster dir: %s' % \
333 self.log.info('Using existing cluster dir: %s' % \
334 self.cluster_dir_obj.location
334 self.cluster_dir_obj.location
335 )
335 )
336 self.finish_cluster_dir()
336 self.finish_cluster_dir()
337 return
337 return
338
338
339 try:
339 try:
340 self.profile = self.command_line_config.Global.profile
340 self.profile = self.command_line_config.Global.profile
341 except AttributeError:
341 except AttributeError:
342 self.profile = self.default_config.Global.profile
342 self.profile = self.default_config.Global.profile
343 try:
343 try:
344 self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
344 self.cluster_dir_obj = ClusterDir.find_cluster_dir_by_profile(
345 self.ipythondir, self.profile)
345 self.ipython_dir, self.profile)
346 except ClusterDirError:
346 except ClusterDirError:
347 pass
347 pass
348 else:
348 else:
349 self.log.info('Using existing cluster dir: %s' % \
349 self.log.info('Using existing cluster dir: %s' % \
350 self.cluster_dir_obj.location
350 self.cluster_dir_obj.location
351 )
351 )
352 self.finish_cluster_dir()
352 self.finish_cluster_dir()
353 return
353 return
354
354
355 if self.auto_create_cluster_dir:
355 if self.auto_create_cluster_dir:
356 self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile(
356 self.cluster_dir_obj = ClusterDir.create_cluster_dir_by_profile(
357 self.ipythondir, self.profile
357 self.ipython_dir, self.profile
358 )
358 )
359 self.log.info('Creating new cluster dir: %s' % \
359 self.log.info('Creating new cluster dir: %s' % \
360 self.cluster_dir_obj.location
360 self.cluster_dir_obj.location
361 )
361 )
362 self.finish_cluster_dir()
362 self.finish_cluster_dir()
363 else:
363 else:
364 raise ClusterDirError('Could not find a valid cluster directory.')
364 raise ClusterDirError('Could not find a valid cluster directory.')
365
365
366 def finish_cluster_dir(self):
366 def finish_cluster_dir(self):
367 # Set the cluster directory
367 # Set the cluster directory
368 self.cluster_dir = self.cluster_dir_obj.location
368 self.cluster_dir = self.cluster_dir_obj.location
369
369
370 # These have to be set because they could be different from the one
370 # These have to be set because they could be different from the one
371 # that we just computed. Because command line has the highest
371 # that we just computed. Because command line has the highest
372 # priority, this will always end up in the master_config.
372 # priority, this will always end up in the master_config.
373 self.default_config.Global.cluster_dir = self.cluster_dir
373 self.default_config.Global.cluster_dir = self.cluster_dir
374 self.command_line_config.Global.cluster_dir = self.cluster_dir
374 self.command_line_config.Global.cluster_dir = self.cluster_dir
375
375
376 # Set the search path to the cluster directory
376 # Set the search path to the cluster directory
377 self.config_file_paths = (self.cluster_dir,)
377 self.config_file_paths = (self.cluster_dir,)
378
378
379 def find_config_file_name(self):
379 def find_config_file_name(self):
380 """Find the config file name for this application."""
380 """Find the config file name for this application."""
381 # For this type of Application it should be set as a class attribute.
381 # For this type of Application it should be set as a class attribute.
382 if not hasattr(self, 'config_file_name'):
382 if not hasattr(self, 'config_file_name'):
383 self.log.critical("No config filename found")
383 self.log.critical("No config filename found")
384
384
385 def find_config_file_paths(self):
385 def find_config_file_paths(self):
386 # Set the search path to the cluster directory
386 # Set the search path to the cluster directory
387 self.config_file_paths = (self.cluster_dir,)
387 self.config_file_paths = (self.cluster_dir,)
388
388
389 def pre_construct(self):
389 def pre_construct(self):
390 # The log and security dirs were set earlier, but here we put them
390 # The log and security dirs were set earlier, but here we put them
391 # into the config and log them.
391 # into the config and log them.
392 config = self.master_config
392 config = self.master_config
393 sdir = self.cluster_dir_obj.security_dir
393 sdir = self.cluster_dir_obj.security_dir
394 self.security_dir = config.Global.security_dir = sdir
394 self.security_dir = config.Global.security_dir = sdir
395 ldir = self.cluster_dir_obj.log_dir
395 ldir = self.cluster_dir_obj.log_dir
396 self.log_dir = config.Global.log_dir = ldir
396 self.log_dir = config.Global.log_dir = ldir
397 pdir = self.cluster_dir_obj.pid_dir
397 pdir = self.cluster_dir_obj.pid_dir
398 self.pid_dir = config.Global.pid_dir = pdir
398 self.pid_dir = config.Global.pid_dir = pdir
399 self.log.info("Cluster directory set to: %s" % self.cluster_dir)
399 self.log.info("Cluster directory set to: %s" % self.cluster_dir)
400
400
401 def start_logging(self):
401 def start_logging(self):
402 # Remove old log files
402 # Remove old log files
403 if self.master_config.Global.clean_logs:
403 if self.master_config.Global.clean_logs:
404 log_dir = self.master_config.Global.log_dir
404 log_dir = self.master_config.Global.log_dir
405 for f in os.listdir(log_dir):
405 for f in os.listdir(log_dir):
406 if f.startswith(self.name + '-') and f.endswith('.log'):
406 if f.startswith(self.name + '-') and f.endswith('.log'):
407 os.remove(os.path.join(log_dir, f))
407 os.remove(os.path.join(log_dir, f))
408 # Start logging to the new log file
408 # Start logging to the new log file
409 if self.master_config.Global.log_to_file:
409 if self.master_config.Global.log_to_file:
410 log_filename = self.name + '-' + str(os.getpid()) + '.log'
410 log_filename = self.name + '-' + str(os.getpid()) + '.log'
411 logfile = os.path.join(self.log_dir, log_filename)
411 logfile = os.path.join(self.log_dir, log_filename)
412 open_log_file = open(logfile, 'w')
412 open_log_file = open(logfile, 'w')
413 else:
413 else:
414 open_log_file = sys.stdout
414 open_log_file = sys.stdout
415 log.startLogging(open_log_file)
415 log.startLogging(open_log_file)
416
416
417 def write_pid_file(self, overwrite=False):
417 def write_pid_file(self, overwrite=False):
418 """Create a .pid file in the pid_dir with my pid.
418 """Create a .pid file in the pid_dir with my pid.
419
419
420 This must be called after pre_construct, which sets `self.pid_dir`.
420 This must be called after pre_construct, which sets `self.pid_dir`.
421 This raises :exc:`PIDFileError` if the pid file exists already.
421 This raises :exc:`PIDFileError` if the pid file exists already.
422 """
422 """
423 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
423 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
424 if os.path.isfile(pid_file):
424 if os.path.isfile(pid_file):
425 pid = self.get_pid_from_file()
425 pid = self.get_pid_from_file()
426 if not overwrite:
426 if not overwrite:
427 raise PIDFileError(
427 raise PIDFileError(
428 'The pid file [%s] already exists. \nThis could mean that this '
428 'The pid file [%s] already exists. \nThis could mean that this '
429 'server is already running with [pid=%s].' % (pid_file, pid)
429 'server is already running with [pid=%s].' % (pid_file, pid)
430 )
430 )
431 with open(pid_file, 'w') as f:
431 with open(pid_file, 'w') as f:
432 self.log.info("Creating pid file: %s" % pid_file)
432 self.log.info("Creating pid file: %s" % pid_file)
433 f.write(repr(os.getpid())+'\n')
433 f.write(repr(os.getpid())+'\n')
434
434
435 def remove_pid_file(self):
435 def remove_pid_file(self):
436 """Remove the pid file.
436 """Remove the pid file.
437
437
438 This should be called at shutdown by registering a callback with
438 This should be called at shutdown by registering a callback with
439 :func:`reactor.addSystemEventTrigger`.
439 :func:`reactor.addSystemEventTrigger`.
440 """
440 """
441 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
441 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
442 if os.path.isfile(pid_file):
442 if os.path.isfile(pid_file):
443 try:
443 try:
444 self.log.info("Removing pid file: %s" % pid_file)
444 self.log.info("Removing pid file: %s" % pid_file)
445 os.remove(pid_file)
445 os.remove(pid_file)
446 except:
446 except:
447 self.log.warn("Error removing the pid file: %s" % pid_file)
447 self.log.warn("Error removing the pid file: %s" % pid_file)
448 raise
448 raise
449
449
450 def get_pid_from_file(self):
450 def get_pid_from_file(self):
451 """Get the pid from the pid file.
451 """Get the pid from the pid file.
452
452
453 If the pid file doesn't exist a :exc:`PIDFileError` is raised.
453 If the pid file doesn't exist a :exc:`PIDFileError` is raised.
454 """
454 """
455 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
455 pid_file = os.path.join(self.pid_dir, self.name + '.pid')
456 if os.path.isfile(pid_file):
456 if os.path.isfile(pid_file):
457 with open(pid_file, 'r') as f:
457 with open(pid_file, 'r') as f:
458 pid = int(f.read().strip())
458 pid = int(f.read().strip())
459 return pid
459 return pid
460 else:
460 else:
461 raise PIDFileError('pid file not found: %s' % pid_file) No newline at end of file
461 raise PIDFileError('pid file not found: %s' % pid_file)
@@ -1,384 +1,384 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The ipcluster application.
4 The ipcluster application.
5 """
5 """
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import logging
18 import logging
19 import os
19 import os
20 import signal
20 import signal
21 import sys
21 import sys
22
22
23 if os.name=='posix':
23 if os.name=='posix':
24 from twisted.scripts._twistd_unix import daemonize
24 from twisted.scripts._twistd_unix import daemonize
25
25
26 from IPython.core import release
26 from IPython.core import release
27 from IPython.external import argparse
27 from IPython.external import argparse
28 from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault
28 from IPython.config.loader import ArgParseConfigLoader, NoConfigDefault
29 from IPython.utils.importstring import import_item
29 from IPython.utils.importstring import import_item
30
30
31 from IPython.kernel.clusterdir import (
31 from IPython.kernel.clusterdir import (
32 ApplicationWithClusterDir, ClusterDirError, PIDFileError
32 ApplicationWithClusterDir, ClusterDirError, PIDFileError
33 )
33 )
34
34
35 from twisted.internet import reactor, defer
35 from twisted.internet import reactor, defer
36 from twisted.python import log
36 from twisted.python import log
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Code for launchers
39 # Code for launchers
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42
42
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # The ipcluster application
45 # The ipcluster application
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48
48
49 class IPClusterCLLoader(ArgParseConfigLoader):
49 class IPClusterCLLoader(ArgParseConfigLoader):
50
50
51 def _add_arguments(self):
51 def _add_arguments(self):
52 # This has all the common options that all subcommands use
52 # This has all the common options that all subcommands use
53 parent_parser1 = argparse.ArgumentParser(add_help=False)
53 parent_parser1 = argparse.ArgumentParser(add_help=False)
54 parent_parser1.add_argument('--ipython-dir',
54 parent_parser1.add_argument('--ipython-dir',
55 dest='Global.ipythondir',type=str,
55 dest='Global.ipython_dir',type=str,
56 help='Set to override default location of Global.ipythondir.',
56 help='Set to override default location of Global.ipython_dir.',
57 default=NoConfigDefault,
57 default=NoConfigDefault,
58 metavar='Global.ipythondir')
58 metavar='Global.ipython_dir')
59 parent_parser1.add_argument('--log-level',
59 parent_parser1.add_argument('--log-level',
60 dest="Global.log_level",type=int,
60 dest="Global.log_level",type=int,
61 help='Set the log level (0,10,20,30,40,50). Default is 30.',
61 help='Set the log level (0,10,20,30,40,50). Default is 30.',
62 default=NoConfigDefault,
62 default=NoConfigDefault,
63 metavar='Global.log_level')
63 metavar='Global.log_level')
64
64
65 # This has all the common options that other subcommands use
65 # This has all the common options that other subcommands use
66 parent_parser2 = argparse.ArgumentParser(add_help=False)
66 parent_parser2 = argparse.ArgumentParser(add_help=False)
67 parent_parser2.add_argument('-p','--profile',
67 parent_parser2.add_argument('-p','--profile',
68 dest='Global.profile',type=str,
68 dest='Global.profile',type=str,
69 default=NoConfigDefault,
69 default=NoConfigDefault,
70 help='The string name of the profile to be used. This determines '
70 help='The string name of the profile to be used. This determines '
71 'the name of the cluster dir as: cluster_<profile>. The default profile '
71 'the name of the cluster dir as: cluster_<profile>. The default profile '
72 'is named "default". The cluster directory is resolve this way '
72 'is named "default". The cluster directory is resolve this way '
73 'if the --cluster-dir option is not used.',
73 'if the --cluster-dir option is not used.',
74 default=NoConfigDefault,
74 default=NoConfigDefault,
75 metavar='Global.profile')
75 metavar='Global.profile')
76 parent_parser2.add_argument('--cluster-dir',
76 parent_parser2.add_argument('--cluster-dir',
77 dest='Global.cluster_dir',type=str,
77 dest='Global.cluster_dir',type=str,
78 default=NoConfigDefault,
78 default=NoConfigDefault,
79 help='Set the cluster dir. This overrides the logic used by the '
79 help='Set the cluster dir. This overrides the logic used by the '
80 '--profile option.',
80 '--profile option.',
81 default=NoConfigDefault,
81 default=NoConfigDefault,
82 metavar='Global.cluster_dir')
82 metavar='Global.cluster_dir')
83 parent_parser2.add_argument('--log-to-file',
83 parent_parser2.add_argument('--log-to-file',
84 action='store_true', dest='Global.log_to_file',
84 action='store_true', dest='Global.log_to_file',
85 default=NoConfigDefault,
85 default=NoConfigDefault,
86 help='Log to a file in the log directory (default is stdout)'
86 help='Log to a file in the log directory (default is stdout)'
87 )
87 )
88
88
89 subparsers = self.parser.add_subparsers(
89 subparsers = self.parser.add_subparsers(
90 dest='Global.subcommand',
90 dest='Global.subcommand',
91 title='ipcluster subcommands',
91 title='ipcluster subcommands',
92 description='ipcluster has a variety of subcommands. '
92 description='ipcluster has a variety of subcommands. '
93 'The general way of running ipcluster is "ipcluster <cmd> '
93 'The general way of running ipcluster is "ipcluster <cmd> '
94 ' [options]""',
94 ' [options]""',
95 help='For more help, type "ipcluster <cmd> -h"')
95 help='For more help, type "ipcluster <cmd> -h"')
96
96
97 parser_list = subparsers.add_parser(
97 parser_list = subparsers.add_parser(
98 'list',
98 'list',
99 help='List all clusters in cwd and ipythondir.',
99 help='List all clusters in cwd and ipython_dir.',
100 parents=[parent_parser1]
100 parents=[parent_parser1]
101 )
101 )
102
102
103 parser_create = subparsers.add_parser(
103 parser_create = subparsers.add_parser(
104 'create',
104 'create',
105 help='Create a new cluster directory.',
105 help='Create a new cluster directory.',
106 parents=[parent_parser1, parent_parser2]
106 parents=[parent_parser1, parent_parser2]
107 )
107 )
108 parser_create.add_argument(
108 parser_create.add_argument(
109 '--reset-config',
109 '--reset-config',
110 dest='Global.reset_config', action='store_true',
110 dest='Global.reset_config', action='store_true',
111 default=NoConfigDefault,
111 default=NoConfigDefault,
112 help='Recopy the default config files to the cluster directory. '
112 help='Recopy the default config files to the cluster directory. '
113 'You will loose any modifications you have made to these files.'
113 'You will loose any modifications you have made to these files.'
114 )
114 )
115
115
116 parser_start = subparsers.add_parser(
116 parser_start = subparsers.add_parser(
117 'start',
117 'start',
118 help='Start a cluster.',
118 help='Start a cluster.',
119 parents=[parent_parser1, parent_parser2]
119 parents=[parent_parser1, parent_parser2]
120 )
120 )
121 parser_start.add_argument(
121 parser_start.add_argument(
122 '-n', '--number',
122 '-n', '--number',
123 type=int, dest='Global.n',
123 type=int, dest='Global.n',
124 default=NoConfigDefault,
124 default=NoConfigDefault,
125 help='The number of engines to start.',
125 help='The number of engines to start.',
126 metavar='Global.n'
126 metavar='Global.n'
127 )
127 )
128 parser_start.add_argument('--clean-logs',
128 parser_start.add_argument('--clean-logs',
129 dest='Global.clean_logs', action='store_true',
129 dest='Global.clean_logs', action='store_true',
130 help='Delete old log flies before starting.',
130 help='Delete old log flies before starting.',
131 default=NoConfigDefault
131 default=NoConfigDefault
132 )
132 )
133 parser_start.add_argument('--no-clean-logs',
133 parser_start.add_argument('--no-clean-logs',
134 dest='Global.clean_logs', action='store_false',
134 dest='Global.clean_logs', action='store_false',
135 help="Don't delete old log flies before starting.",
135 help="Don't delete old log flies before starting.",
136 default=NoConfigDefault
136 default=NoConfigDefault
137 )
137 )
138 parser_start.add_argument('--daemon',
138 parser_start.add_argument('--daemon',
139 dest='Global.daemonize', action='store_true',
139 dest='Global.daemonize', action='store_true',
140 help='Daemonize the ipcluster program. This implies --log-to-file',
140 help='Daemonize the ipcluster program. This implies --log-to-file',
141 default=NoConfigDefault
141 default=NoConfigDefault
142 )
142 )
143 parser_start.add_argument('--nodaemon',
143 parser_start.add_argument('--no-daemon',
144 dest='Global.daemonize', action='store_false',
144 dest='Global.daemonize', action='store_false',
145 help="Dont't daemonize the ipcluster program.",
145 help="Dont't daemonize the ipcluster program.",
146 default=NoConfigDefault
146 default=NoConfigDefault
147 )
147 )
148
148
149 parser_start = subparsers.add_parser(
149 parser_start = subparsers.add_parser(
150 'stop',
150 'stop',
151 help='Stop a cluster.',
151 help='Stop a cluster.',
152 parents=[parent_parser1, parent_parser2]
152 parents=[parent_parser1, parent_parser2]
153 )
153 )
154 parser_start.add_argument('--signal-number',
154 parser_start.add_argument('--signal-number',
155 dest='Global.stop_signal', type=int,
155 dest='Global.stop_signal', type=int,
156 help="The signal number to use in stopping the cluster (default=2).",
156 help="The signal number to use in stopping the cluster (default=2).",
157 metavar="Global.stop_signal",
157 metavar="Global.stop_signal",
158 default=NoConfigDefault
158 default=NoConfigDefault
159 )
159 )
160
160
161 default_config_file_name = 'ipcluster_config.py'
161 default_config_file_name = 'ipcluster_config.py'
162
162
163
163
164 class IPClusterApp(ApplicationWithClusterDir):
164 class IPClusterApp(ApplicationWithClusterDir):
165
165
166 name = 'ipcluster'
166 name = 'ipcluster'
167 description = 'Start an IPython cluster (controller and engines).'
167 description = 'Start an IPython cluster (controller and engines).'
168 config_file_name = default_config_file_name
168 config_file_name = default_config_file_name
169 default_log_level = logging.INFO
169 default_log_level = logging.INFO
170 auto_create_cluster_dir = False
170 auto_create_cluster_dir = False
171
171
172 def create_default_config(self):
172 def create_default_config(self):
173 super(IPClusterApp, self).create_default_config()
173 super(IPClusterApp, self).create_default_config()
174 self.default_config.Global.controller_launcher = \
174 self.default_config.Global.controller_launcher = \
175 'IPython.kernel.launcher.LocalControllerLauncher'
175 'IPython.kernel.launcher.LocalControllerLauncher'
176 self.default_config.Global.engine_launcher = \
176 self.default_config.Global.engine_launcher = \
177 'IPython.kernel.launcher.LocalEngineSetLauncher'
177 'IPython.kernel.launcher.LocalEngineSetLauncher'
178 self.default_config.Global.n = 2
178 self.default_config.Global.n = 2
179 self.default_config.Global.reset_config = False
179 self.default_config.Global.reset_config = False
180 self.default_config.Global.clean_logs = True
180 self.default_config.Global.clean_logs = True
181 self.default_config.Global.stop_signal = 2
181 self.default_config.Global.stop_signal = 2
182 self.default_config.Global.daemonize = False
182 self.default_config.Global.daemonize = False
183
183
184 def create_command_line_config(self):
184 def create_command_line_config(self):
185 """Create and return a command line config loader."""
185 """Create and return a command line config loader."""
186 return IPClusterCLLoader(
186 return IPClusterCLLoader(
187 description=self.description,
187 description=self.description,
188 version=release.version
188 version=release.version
189 )
189 )
190
190
191 def find_resources(self):
191 def find_resources(self):
192 subcommand = self.command_line_config.Global.subcommand
192 subcommand = self.command_line_config.Global.subcommand
193 if subcommand=='list':
193 if subcommand=='list':
194 self.list_cluster_dirs()
194 self.list_cluster_dirs()
195 # Exit immediately because there is nothing left to do.
195 # Exit immediately because there is nothing left to do.
196 self.exit()
196 self.exit()
197 elif subcommand=='create':
197 elif subcommand=='create':
198 self.auto_create_cluster_dir = True
198 self.auto_create_cluster_dir = True
199 super(IPClusterApp, self).find_resources()
199 super(IPClusterApp, self).find_resources()
200 elif subcommand=='start' or subcommand=='stop':
200 elif subcommand=='start' or subcommand=='stop':
201 self.auto_create_cluster_dir = False
201 self.auto_create_cluster_dir = False
202 try:
202 try:
203 super(IPClusterApp, self).find_resources()
203 super(IPClusterApp, self).find_resources()
204 except ClusterDirError:
204 except ClusterDirError:
205 raise ClusterDirError(
205 raise ClusterDirError(
206 "Could not find a cluster directory. A cluster dir must "
206 "Could not find a cluster directory. A cluster dir must "
207 "be created before running 'ipcluster start'. Do "
207 "be created before running 'ipcluster start'. Do "
208 "'ipcluster create -h' or 'ipcluster list -h' for more "
208 "'ipcluster create -h' or 'ipcluster list -h' for more "
209 "information about creating and listing cluster dirs."
209 "information about creating and listing cluster dirs."
210 )
210 )
211
211
212 def pre_construct(self):
212 def pre_construct(self):
213 super(IPClusterApp, self).pre_construct()
213 super(IPClusterApp, self).pre_construct()
214 config = self.master_config
214 config = self.master_config
215 try:
215 try:
216 daemon = config.Global.daemonize
216 daemon = config.Global.daemonize
217 if daemon:
217 if daemon:
218 config.Global.log_to_file = True
218 config.Global.log_to_file = True
219 except AttributeError:
219 except AttributeError:
220 pass
220 pass
221
221
222 def construct(self):
222 def construct(self):
223 config = self.master_config
223 config = self.master_config
224 if config.Global.subcommand=='list':
224 if config.Global.subcommand=='list':
225 pass
225 pass
226 elif config.Global.subcommand=='create':
226 elif config.Global.subcommand=='create':
227 self.log.info('Copying default config files to cluster directory '
227 self.log.info('Copying default config files to cluster directory '
228 '[overwrite=%r]' % (config.Global.reset_config,))
228 '[overwrite=%r]' % (config.Global.reset_config,))
229 self.cluster_dir_obj.copy_all_config_files(overwrite=config.Global.reset_config)
229 self.cluster_dir_obj.copy_all_config_files(overwrite=config.Global.reset_config)
230 elif config.Global.subcommand=='start':
230 elif config.Global.subcommand=='start':
231 self.start_logging()
231 self.start_logging()
232 reactor.callWhenRunning(self.start_launchers)
232 reactor.callWhenRunning(self.start_launchers)
233
233
234 def list_cluster_dirs(self):
234 def list_cluster_dirs(self):
235 # Find the search paths
235 # Find the search paths
236 cluster_dir_paths = os.environ.get('IPCLUSTERDIR_PATH','')
236 cluster_dir_paths = os.environ.get('IPCLUSTER_DIR_PATH','')
237 if cluster_dir_paths:
237 if cluster_dir_paths:
238 cluster_dir_paths = cluster_dir_paths.split(':')
238 cluster_dir_paths = cluster_dir_paths.split(':')
239 else:
239 else:
240 cluster_dir_paths = []
240 cluster_dir_paths = []
241 try:
241 try:
242 ipythondir = self.command_line_config.Global.ipythondir
242 ipython_dir = self.command_line_config.Global.ipython_dir
243 except AttributeError:
243 except AttributeError:
244 ipythondir = self.default_config.Global.ipythondir
244 ipython_dir = self.default_config.Global.ipython_dir
245 paths = [os.getcwd(), ipythondir] + \
245 paths = [os.getcwd(), ipython_dir] + \
246 cluster_dir_paths
246 cluster_dir_paths
247 paths = list(set(paths))
247 paths = list(set(paths))
248
248
249 self.log.info('Searching for cluster dirs in paths: %r' % paths)
249 self.log.info('Searching for cluster dirs in paths: %r' % paths)
250 for path in paths:
250 for path in paths:
251 files = os.listdir(path)
251 files = os.listdir(path)
252 for f in files:
252 for f in files:
253 full_path = os.path.join(path, f)
253 full_path = os.path.join(path, f)
254 if os.path.isdir(full_path) and f.startswith('cluster_'):
254 if os.path.isdir(full_path) and f.startswith('cluster_'):
255 profile = full_path.split('_')[-1]
255 profile = full_path.split('_')[-1]
256 start_cmd = '"ipcluster start -n 4 -p %s"' % profile
256 start_cmd = '"ipcluster start -n 4 -p %s"' % profile
257 print start_cmd + " ==> " + full_path
257 print start_cmd + " ==> " + full_path
258
258
259 def start_launchers(self):
259 def start_launchers(self):
260 config = self.master_config
260 config = self.master_config
261
261
262 # Create the launchers
262 # Create the launchers
263 el_class = import_item(config.Global.engine_launcher)
263 el_class = import_item(config.Global.engine_launcher)
264 self.engine_launcher = el_class(
264 self.engine_launcher = el_class(
265 self.cluster_dir, config=config
265 self.cluster_dir, config=config
266 )
266 )
267 cl_class = import_item(config.Global.controller_launcher)
267 cl_class = import_item(config.Global.controller_launcher)
268 self.controller_launcher = cl_class(
268 self.controller_launcher = cl_class(
269 self.cluster_dir, config=config
269 self.cluster_dir, config=config
270 )
270 )
271
271
272 # Setup signals
272 # Setup signals
273 signal.signal(signal.SIGINT, self.stop_launchers)
273 signal.signal(signal.SIGINT, self.stop_launchers)
274 # signal.signal(signal.SIGKILL, self.stop_launchers)
274 # signal.signal(signal.SIGKILL, self.stop_launchers)
275
275
276 # Setup the observing of stopping
276 # Setup the observing of stopping
277 d1 = self.controller_launcher.observe_stop()
277 d1 = self.controller_launcher.observe_stop()
278 d1.addCallback(self.stop_engines)
278 d1.addCallback(self.stop_engines)
279 d1.addErrback(self.err_and_stop)
279 d1.addErrback(self.err_and_stop)
280 # If this triggers, just let them die
280 # If this triggers, just let them die
281 # d2 = self.engine_launcher.observe_stop()
281 # d2 = self.engine_launcher.observe_stop()
282
282
283 # Start the controller and engines
283 # Start the controller and engines
284 d = self.controller_launcher.start(
284 d = self.controller_launcher.start(
285 profile=None, cluster_dir=config.Global.cluster_dir
285 profile=None, cluster_dir=config.Global.cluster_dir
286 )
286 )
287 d.addCallback(lambda _: self.start_engines())
287 d.addCallback(lambda _: self.start_engines())
288 d.addErrback(self.err_and_stop)
288 d.addErrback(self.err_and_stop)
289
289
290 def err_and_stop(self, f):
290 def err_and_stop(self, f):
291 log.msg('Unexpected error in ipcluster:')
291 log.msg('Unexpected error in ipcluster:')
292 log.err(f)
292 log.err(f)
293 reactor.stop()
293 reactor.stop()
294
294
295 def stop_engines(self, r):
295 def stop_engines(self, r):
296 return self.engine_launcher.stop()
296 return self.engine_launcher.stop()
297
297
298 def start_engines(self):
298 def start_engines(self):
299 config = self.master_config
299 config = self.master_config
300 d = self.engine_launcher.start(
300 d = self.engine_launcher.start(
301 config.Global.n,
301 config.Global.n,
302 profile=None, cluster_dir=config.Global.cluster_dir
302 profile=None, cluster_dir=config.Global.cluster_dir
303 )
303 )
304 return d
304 return d
305
305
306 def stop_launchers(self, signum, frame):
306 def stop_launchers(self, signum, frame):
307 log.msg("Stopping cluster")
307 log.msg("Stopping cluster")
308 d1 = self.engine_launcher.stop()
308 d1 = self.engine_launcher.stop()
309 d2 = self.controller_launcher.stop()
309 d2 = self.controller_launcher.stop()
310 # d1.addCallback(lambda _: self.controller_launcher.stop)
310 # d1.addCallback(lambda _: self.controller_launcher.stop)
311 d1.addErrback(self.err_and_stop)
311 d1.addErrback(self.err_and_stop)
312 d2.addErrback(self.err_and_stop)
312 d2.addErrback(self.err_and_stop)
313 reactor.callLater(2.0, reactor.stop)
313 reactor.callLater(2.0, reactor.stop)
314
314
315 def start_logging(self):
315 def start_logging(self):
316 # Remove old log files
316 # Remove old log files
317 if self.master_config.Global.clean_logs:
317 if self.master_config.Global.clean_logs:
318 log_dir = self.master_config.Global.log_dir
318 log_dir = self.master_config.Global.log_dir
319 for f in os.listdir(log_dir):
319 for f in os.listdir(log_dir):
320 if f.startswith('ipengine' + '-') and f.endswith('.log'):
320 if f.startswith('ipengine' + '-') and f.endswith('.log'):
321 os.remove(os.path.join(log_dir, f))
321 os.remove(os.path.join(log_dir, f))
322 for f in os.listdir(log_dir):
322 for f in os.listdir(log_dir):
323 if f.startswith('ipcontroller' + '-') and f.endswith('.log'):
323 if f.startswith('ipcontroller' + '-') and f.endswith('.log'):
324 os.remove(os.path.join(log_dir, f))
324 os.remove(os.path.join(log_dir, f))
325 super(IPClusterApp, self).start_logging()
325 super(IPClusterApp, self).start_logging()
326
326
327 def start_app(self):
327 def start_app(self):
328 """Start the application, depending on what subcommand is used."""
328 """Start the application, depending on what subcommand is used."""
329 config = self.master_config
329 config = self.master_config
330 subcmd = config.Global.subcommand
330 subcmd = config.Global.subcommand
331 if subcmd=='create' or subcmd=='list':
331 if subcmd=='create' or subcmd=='list':
332 return
332 return
333 elif subcmd=='start':
333 elif subcmd=='start':
334 # First see if the cluster is already running
334 # First see if the cluster is already running
335 try:
335 try:
336 pid = self.get_pid_from_file()
336 pid = self.get_pid_from_file()
337 except:
337 except:
338 pass
338 pass
339 else:
339 else:
340 self.log.critical(
340 self.log.critical(
341 'Cluster is already running with [pid=%s]. '
341 'Cluster is already running with [pid=%s]. '
342 'use "ipcluster stop" to stop the cluster.' % pid
342 'use "ipcluster stop" to stop the cluster.' % pid
343 )
343 )
344 # Here I exit with a unusual exit status that other processes
344 # Here I exit with a unusual exit status that other processes
345 # can watch for to learn how I existed.
345 # can watch for to learn how I existed.
346 sys.exit(10)
346 sys.exit(10)
347 # Now log and daemonize
347 # Now log and daemonize
348 self.log.info('Starting ipcluster with [daemon=%r]' % config.Global.daemonize)
348 self.log.info('Starting ipcluster with [daemon=%r]' % config.Global.daemonize)
349 if config.Global.daemonize:
349 if config.Global.daemonize:
350 if os.name=='posix':
350 if os.name=='posix':
351 os.chdir(config.Global.cluster_dir)
351 os.chdir(config.Global.cluster_dir)
352 self.log_level = 40
352 self.log_level = 40
353 daemonize()
353 daemonize()
354
354
355 # Now write the new pid file after our new forked pid is active.
355 # Now write the new pid file after our new forked pid is active.
356 self.write_pid_file()
356 self.write_pid_file()
357 reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file)
357 reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file)
358 reactor.run()
358 reactor.run()
359 elif subcmd=='stop':
359 elif subcmd=='stop':
360 try:
360 try:
361 pid = self.get_pid_from_file()
361 pid = self.get_pid_from_file()
362 except PIDFileError:
362 except PIDFileError:
363 self.log.critical(
363 self.log.critical(
364 'Problem reading pid file, cluster is probably not running.'
364 'Problem reading pid file, cluster is probably not running.'
365 )
365 )
366 # Here I exit with a unusual exit status that other processes
366 # Here I exit with a unusual exit status that other processes
367 # can watch for to learn how I existed.
367 # can watch for to learn how I existed.
368 sys.exit(11)
368 sys.exit(11)
369 sig = config.Global.stop_signal
369 sig = config.Global.stop_signal
370 self.log.info(
370 self.log.info(
371 "Stopping cluster [pid=%r] with [signal=%r]" % (pid, sig)
371 "Stopping cluster [pid=%r] with [signal=%r]" % (pid, sig)
372 )
372 )
373 os.kill(pid, sig)
373 os.kill(pid, sig)
374
374
375
375
376 def launch_new_instance():
376 def launch_new_instance():
377 """Create and run the IPython cluster."""
377 """Create and run the IPython cluster."""
378 app = IPClusterApp()
378 app = IPClusterApp()
379 app.start()
379 app.start()
380
380
381
381
382 if __name__ == '__main__':
382 if __name__ == '__main__':
383 launch_new_instance()
383 launch_new_instance()
384
384
@@ -1,441 +1,441 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 def pexpect_monkeypatch():
48 def pexpect_monkeypatch():
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
50
50
51 Calling this function will monkeypatch the pexpect.spawn class and modify
51 Calling this function will monkeypatch the pexpect.spawn class and modify
52 its __del__ method to make it more robust in the face of failures that can
52 its __del__ method to make it more robust in the face of failures that can
53 occur if it is called when the Python VM is shutting down.
53 occur if it is called when the Python VM is shutting down.
54
54
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
56 them to execute during the teardown of the Python VM itself. At this
56 them to execute during the teardown of the Python VM itself. At this
57 point, various builtin modules have been reset to None. Thus, the call to
57 point, various builtin modules have been reset to None. Thus, the call to
58 self.close() will trigger an exception because it tries to call os.close(),
58 self.close() will trigger an exception because it tries to call os.close(),
59 and os is now None.
59 and os is now None.
60 """
60 """
61
61
62 if pexpect.__version__[:3] >= '2.2':
62 if pexpect.__version__[:3] >= '2.2':
63 # No need to patch, fix is already the upstream version.
63 # No need to patch, fix is already the upstream version.
64 return
64 return
65
65
66 def __del__(self):
66 def __del__(self):
67 """This makes sure that no system resources are left open.
67 """This makes sure that no system resources are left open.
68 Python only garbage collects Python objects. OS file descriptors
68 Python only garbage collects Python objects. OS file descriptors
69 are not Python objects, so they must be handled explicitly.
69 are not Python objects, so they must be handled explicitly.
70 If the child file descriptor was opened outside of this class
70 If the child file descriptor was opened outside of this class
71 (passed to the constructor) then this does not close it.
71 (passed to the constructor) then this does not close it.
72 """
72 """
73 if not self.closed:
73 if not self.closed:
74 try:
74 try:
75 self.close()
75 self.close()
76 except AttributeError:
76 except AttributeError:
77 pass
77 pass
78
78
79 pexpect.spawn.__del__ = __del__
79 pexpect.spawn.__del__ = __del__
80
80
81 pexpect_monkeypatch()
81 pexpect_monkeypatch()
82
82
83 # The generic runner class
83 # The generic runner class
84 class InteractiveRunner(object):
84 class InteractiveRunner(object):
85 """Class to run a sequence of commands through an interactive program."""
85 """Class to run a sequence of commands through an interactive program."""
86
86
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
88 """Construct a runner.
88 """Construct a runner.
89
89
90 Inputs:
90 Inputs:
91
91
92 - program: command to execute the given program.
92 - program: command to execute the given program.
93
93
94 - prompts: a list of patterns to match as valid prompts, in the
94 - prompts: a list of patterns to match as valid prompts, in the
95 format used by pexpect. This basically means that it can be either
95 format used by pexpect. This basically means that it can be either
96 a string (to be compiled as a regular expression) or a list of such
96 a string (to be compiled as a regular expression) or a list of such
97 (it must be a true list, as pexpect does type checks).
97 (it must be a true list, as pexpect does type checks).
98
98
99 If more than one prompt is given, the first is treated as the main
99 If more than one prompt is given, the first is treated as the main
100 program prompt and the others as 'continuation' prompts, like
100 program prompt and the others as 'continuation' prompts, like
101 python's. This means that blank lines in the input source are
101 python's. This means that blank lines in the input source are
102 ommitted when the first prompt is matched, but are NOT ommitted when
102 ommitted when the first prompt is matched, but are NOT ommitted when
103 the continuation one matches, since this is how python signals the
103 the continuation one matches, since this is how python signals the
104 end of multiline input interactively.
104 end of multiline input interactively.
105
105
106 Optional inputs:
106 Optional inputs:
107
107
108 - args(None): optional list of strings to pass as arguments to the
108 - args(None): optional list of strings to pass as arguments to the
109 child program.
109 child program.
110
110
111 - out(sys.stdout): if given, an output stream to be used when writing
111 - out(sys.stdout): if given, an output stream to be used when writing
112 output. The only requirement is that it must have a .write() method.
112 output. The only requirement is that it must have a .write() method.
113
113
114 Public members not parameterized in the constructor:
114 Public members not parameterized in the constructor:
115
115
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
117 sending each new input. For our purposes here, it's typically best
117 sending each new input. For our purposes here, it's typically best
118 to just set this to zero, but if you encounter reliability problems
118 to just set this to zero, but if you encounter reliability problems
119 or want an interactive run to pause briefly at each prompt, just
119 or want an interactive run to pause briefly at each prompt, just
120 increase this value (it is measured in seconds). Note that this
120 increase this value (it is measured in seconds). Note that this
121 variable is not honored at all by older versions of pexpect.
121 variable is not honored at all by older versions of pexpect.
122 """
122 """
123
123
124 self.program = program
124 self.program = program
125 self.prompts = prompts
125 self.prompts = prompts
126 if args is None: args = []
126 if args is None: args = []
127 self.args = args
127 self.args = args
128 self.out = out
128 self.out = out
129 self.echo = echo
129 self.echo = echo
130 # Other public members which we don't make as parameters, but which
130 # Other public members which we don't make as parameters, but which
131 # users may occasionally want to tweak
131 # users may occasionally want to tweak
132 self.delaybeforesend = 0
132 self.delaybeforesend = 0
133
133
134 # Create child process and hold on to it so we don't have to re-create
134 # Create child process and hold on to it so we don't have to re-create
135 # for every single execution call
135 # for every single execution call
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
137 c.delaybeforesend = self.delaybeforesend
137 c.delaybeforesend = self.delaybeforesend
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
139 # This causes problems because any line longer than 80 characters gets
139 # This causes problems because any line longer than 80 characters gets
140 # completely overwrapped on the printed outptut (even though
140 # completely overwrapped on the printed outptut (even though
141 # internally the code runs fine). We reset this to 99 rows X 200
141 # internally the code runs fine). We reset this to 99 rows X 200
142 # columns (arbitrarily chosen), which should avoid problems in all
142 # columns (arbitrarily chosen), which should avoid problems in all
143 # reasonable cases.
143 # reasonable cases.
144 c.setwinsize(99,200)
144 c.setwinsize(99,200)
145
145
146 def close(self):
146 def close(self):
147 """close child process"""
147 """close child process"""
148
148
149 self.child.close()
149 self.child.close()
150
150
151 def run_file(self,fname,interact=False,get_output=False):
151 def run_file(self,fname,interact=False,get_output=False):
152 """Run the given file interactively.
152 """Run the given file interactively.
153
153
154 Inputs:
154 Inputs:
155
155
156 -fname: name of the file to execute.
156 -fname: name of the file to execute.
157
157
158 See the run_source docstring for the meaning of the optional
158 See the run_source docstring for the meaning of the optional
159 arguments."""
159 arguments."""
160
160
161 fobj = open(fname,'r')
161 fobj = open(fname,'r')
162 try:
162 try:
163 out = self.run_source(fobj,interact,get_output)
163 out = self.run_source(fobj,interact,get_output)
164 finally:
164 finally:
165 fobj.close()
165 fobj.close()
166 if get_output:
166 if get_output:
167 return out
167 return out
168
168
169 def run_source(self,source,interact=False,get_output=False):
169 def run_source(self,source,interact=False,get_output=False):
170 """Run the given source code interactively.
170 """Run the given source code interactively.
171
171
172 Inputs:
172 Inputs:
173
173
174 - source: a string of code to be executed, or an open file object we
174 - source: a string of code to be executed, or an open file object we
175 can iterate over.
175 can iterate over.
176
176
177 Optional inputs:
177 Optional inputs:
178
178
179 - interact(False): if true, start to interact with the running
179 - interact(False): if true, start to interact with the running
180 program at the end of the script. Otherwise, just exit.
180 program at the end of the script. Otherwise, just exit.
181
181
182 - get_output(False): if true, capture the output of the child process
182 - get_output(False): if true, capture the output of the child process
183 (filtering the input commands out) and return it as a string.
183 (filtering the input commands out) and return it as a string.
184
184
185 Returns:
185 Returns:
186 A string containing the process output, but only if requested.
186 A string containing the process output, but only if requested.
187 """
187 """
188
188
189 # if the source is a string, chop it up in lines so we can iterate
189 # if the source is a string, chop it up in lines so we can iterate
190 # over it just as if it were an open file.
190 # over it just as if it were an open file.
191 if not isinstance(source,file):
191 if not isinstance(source,file):
192 source = source.splitlines(True)
192 source = source.splitlines(True)
193
193
194 if self.echo:
194 if self.echo:
195 # normalize all strings we write to use the native OS line
195 # normalize all strings we write to use the native OS line
196 # separators.
196 # separators.
197 linesep = os.linesep
197 linesep = os.linesep
198 stdwrite = self.out.write
198 stdwrite = self.out.write
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
200 else:
200 else:
201 # Quiet mode, all writes are no-ops
201 # Quiet mode, all writes are no-ops
202 write = lambda s: None
202 write = lambda s: None
203
203
204 c = self.child
204 c = self.child
205 prompts = c.compile_pattern_list(self.prompts)
205 prompts = c.compile_pattern_list(self.prompts)
206 prompt_idx = c.expect_list(prompts)
206 prompt_idx = c.expect_list(prompts)
207
207
208 # Flag whether the script ends normally or not, to know whether we can
208 # Flag whether the script ends normally or not, to know whether we can
209 # do anything further with the underlying process.
209 # do anything further with the underlying process.
210 end_normal = True
210 end_normal = True
211
211
212 # If the output was requested, store it in a list for return at the end
212 # If the output was requested, store it in a list for return at the end
213 if get_output:
213 if get_output:
214 output = []
214 output = []
215 store_output = output.append
215 store_output = output.append
216
216
217 for cmd in source:
217 for cmd in source:
218 # skip blank lines for all matches to the 'main' prompt, while the
218 # skip blank lines for all matches to the 'main' prompt, while the
219 # secondary prompts do not
219 # secondary prompts do not
220 if prompt_idx==0 and \
220 if prompt_idx==0 and \
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
222 write(cmd)
222 write(cmd)
223 continue
223 continue
224
224
225 # write('AFTER: '+c.after) # dbg
225 # write('AFTER: '+c.after) # dbg
226 write(c.after)
226 write(c.after)
227 c.send(cmd)
227 c.send(cmd)
228 try:
228 try:
229 prompt_idx = c.expect_list(prompts)
229 prompt_idx = c.expect_list(prompts)
230 except pexpect.EOF:
230 except pexpect.EOF:
231 # this will happen if the child dies unexpectedly
231 # this will happen if the child dies unexpectedly
232 write(c.before)
232 write(c.before)
233 end_normal = False
233 end_normal = False
234 break
234 break
235
235
236 write(c.before)
236 write(c.before)
237
237
238 # With an echoing process, the output we get in c.before contains
238 # With an echoing process, the output we get in c.before contains
239 # the command sent, a newline, and then the actual process output
239 # the command sent, a newline, and then the actual process output
240 if get_output:
240 if get_output:
241 store_output(c.before[len(cmd+'\n'):])
241 store_output(c.before[len(cmd+'\n'):])
242 #write('CMD: <<%s>>' % cmd) # dbg
242 #write('CMD: <<%s>>' % cmd) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
244
244
245 self.out.flush()
245 self.out.flush()
246 if end_normal:
246 if end_normal:
247 if interact:
247 if interact:
248 c.send('\n')
248 c.send('\n')
249 print '<< Starting interactive mode >>',
249 print '<< Starting interactive mode >>',
250 try:
250 try:
251 c.interact()
251 c.interact()
252 except OSError:
252 except OSError:
253 # This is what fires when the child stops. Simply print a
253 # This is what fires when the child stops. Simply print a
254 # newline so the system prompt is aligned. The extra
254 # newline so the system prompt is aligned. The extra
255 # space is there to make sure it gets printed, otherwise
255 # space is there to make sure it gets printed, otherwise
256 # OS buffering sometimes just suppresses it.
256 # OS buffering sometimes just suppresses it.
257 write(' \n')
257 write(' \n')
258 self.out.flush()
258 self.out.flush()
259 else:
259 else:
260 if interact:
260 if interact:
261 e="Further interaction is not possible: child process is dead."
261 e="Further interaction is not possible: child process is dead."
262 print >> sys.stderr, e
262 print >> sys.stderr, e
263
263
264 # Leave the child ready for more input later on, otherwise select just
264 # Leave the child ready for more input later on, otherwise select just
265 # hangs on the second invocation.
265 # hangs on the second invocation.
266 c.send('\n')
266 c.send('\n')
267
267
268 # Return any requested output
268 # Return any requested output
269 if get_output:
269 if get_output:
270 return ''.join(output)
270 return ''.join(output)
271
271
272 def main(self,argv=None):
272 def main(self,argv=None):
273 """Run as a command-line script."""
273 """Run as a command-line script."""
274
274
275 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
275 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
276 newopt = parser.add_option
276 newopt = parser.add_option
277 newopt('-i','--interact',action='store_true',default=False,
277 newopt('-i','--interact',action='store_true',default=False,
278 help='Interact with the program after the script is run.')
278 help='Interact with the program after the script is run.')
279
279
280 opts,args = parser.parse_args(argv)
280 opts,args = parser.parse_args(argv)
281
281
282 if len(args) != 1:
282 if len(args) != 1:
283 print >> sys.stderr,"You must supply exactly one file to run."
283 print >> sys.stderr,"You must supply exactly one file to run."
284 sys.exit(1)
284 sys.exit(1)
285
285
286 self.run_file(args[0],opts.interact)
286 self.run_file(args[0],opts.interact)
287
287
288
288
289 # Specific runners for particular programs
289 # Specific runners for particular programs
290 class IPythonRunner(InteractiveRunner):
290 class IPythonRunner(InteractiveRunner):
291 """Interactive IPython runner.
291 """Interactive IPython runner.
292
292
293 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
293 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
294 avoid having to write a regexp that matches ANSI sequences, though pexpect
294 avoid having to write a regexp that matches ANSI sequences, though pexpect
295 does support them. If anyone contributes patches for ANSI color support,
295 does support them. If anyone contributes patches for ANSI color support,
296 they will be welcome.
296 they will be welcome.
297
297
298 It also sets the prompts manually, since the prompt regexps for
298 It also sets the prompts manually, since the prompt regexps for
299 pexpect need to be matched to the actual prompts, so user-customized
299 pexpect need to be matched to the actual prompts, so user-customized
300 prompts would break this.
300 prompts would break this.
301 """
301 """
302
302
303 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
303 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
304 """New runner, optionally passing the ipython command to use."""
304 """New runner, optionally passing the ipython command to use."""
305
305
306 args0 = ['-colors','NoColor',
306 args0 = ['--colors','NoColor',
307 '-pi1','In [\\#]: ',
307 '-pi1','In [\\#]: ',
308 '-pi2',' .\\D.: ',
308 '-pi2',' .\\D.: ',
309 '-noterm_title',
309 '--noterm-title',
310 '-noautoindent']
310 '--no-auto-indent']
311 if args is None: args = args0
311 if args is None: args = args0
312 else: args = args0 + args
312 else: args = args0 + args
313 prompts = [r'In \[\d+\]: ',r' \.*: ']
313 prompts = [r'In \[\d+\]: ',r' \.*: ']
314 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
314 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
315
315
316
316
317 class PythonRunner(InteractiveRunner):
317 class PythonRunner(InteractiveRunner):
318 """Interactive Python runner."""
318 """Interactive Python runner."""
319
319
320 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
320 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
321 """New runner, optionally passing the python command to use."""
321 """New runner, optionally passing the python command to use."""
322
322
323 prompts = [r'>>> ',r'\.\.\. ']
323 prompts = [r'>>> ',r'\.\.\. ']
324 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
324 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
325
325
326
326
327 class SAGERunner(InteractiveRunner):
327 class SAGERunner(InteractiveRunner):
328 """Interactive SAGE runner.
328 """Interactive SAGE runner.
329
329
330 WARNING: this runner only works if you manually configure your SAGE copy
330 WARNING: this runner only works if you manually configure your SAGE copy
331 to use 'colors NoColor' in the ipythonrc config file, since currently the
331 to use 'colors NoColor' in the ipythonrc config file, since currently the
332 prompt matching regexp does not identify color sequences."""
332 prompt matching regexp does not identify color sequences."""
333
333
334 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
334 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
335 """New runner, optionally passing the sage command to use."""
335 """New runner, optionally passing the sage command to use."""
336
336
337 prompts = ['sage: ',r'\s*\.\.\. ']
337 prompts = ['sage: ',r'\s*\.\.\. ']
338 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
338 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
339
339
340
340
341 class RunnerFactory(object):
341 class RunnerFactory(object):
342 """Code runner factory.
342 """Code runner factory.
343
343
344 This class provides an IPython code runner, but enforces that only one
344 This class provides an IPython code runner, but enforces that only one
345 runner is ever instantiated. The runner is created based on the extension
345 runner is ever instantiated. The runner is created based on the extension
346 of the first file to run, and it raises an exception if a runner is later
346 of the first file to run, and it raises an exception if a runner is later
347 requested for a different extension type.
347 requested for a different extension type.
348
348
349 This ensures that we don't generate example files for doctest with a mix of
349 This ensures that we don't generate example files for doctest with a mix of
350 python and ipython syntax.
350 python and ipython syntax.
351 """
351 """
352
352
353 def __init__(self,out=sys.stdout):
353 def __init__(self,out=sys.stdout):
354 """Instantiate a code runner."""
354 """Instantiate a code runner."""
355
355
356 self.out = out
356 self.out = out
357 self.runner = None
357 self.runner = None
358 self.runnerClass = None
358 self.runnerClass = None
359
359
360 def _makeRunner(self,runnerClass):
360 def _makeRunner(self,runnerClass):
361 self.runnerClass = runnerClass
361 self.runnerClass = runnerClass
362 self.runner = runnerClass(out=self.out)
362 self.runner = runnerClass(out=self.out)
363 return self.runner
363 return self.runner
364
364
365 def __call__(self,fname):
365 def __call__(self,fname):
366 """Return a runner for the given filename."""
366 """Return a runner for the given filename."""
367
367
368 if fname.endswith('.py'):
368 if fname.endswith('.py'):
369 runnerClass = PythonRunner
369 runnerClass = PythonRunner
370 elif fname.endswith('.ipy'):
370 elif fname.endswith('.ipy'):
371 runnerClass = IPythonRunner
371 runnerClass = IPythonRunner
372 else:
372 else:
373 raise ValueError('Unknown file type for Runner: %r' % fname)
373 raise ValueError('Unknown file type for Runner: %r' % fname)
374
374
375 if self.runner is None:
375 if self.runner is None:
376 return self._makeRunner(runnerClass)
376 return self._makeRunner(runnerClass)
377 else:
377 else:
378 if runnerClass==self.runnerClass:
378 if runnerClass==self.runnerClass:
379 return self.runner
379 return self.runner
380 else:
380 else:
381 e='A runner of type %r can not run file %r' % \
381 e='A runner of type %r can not run file %r' % \
382 (self.runnerClass,fname)
382 (self.runnerClass,fname)
383 raise ValueError(e)
383 raise ValueError(e)
384
384
385
385
386 # Global usage string, to avoid indentation issues if typed in a function def.
386 # Global usage string, to avoid indentation issues if typed in a function def.
387 MAIN_USAGE = """
387 MAIN_USAGE = """
388 %prog [options] file_to_run
388 %prog [options] file_to_run
389
389
390 This is an interface to the various interactive runners available in this
390 This is an interface to the various interactive runners available in this
391 module. If you want to pass specific options to one of the runners, you need
391 module. If you want to pass specific options to one of the runners, you need
392 to first terminate the main options with a '--', and then provide the runner's
392 to first terminate the main options with a '--', and then provide the runner's
393 options. For example:
393 options. For example:
394
394
395 irunner.py --python -- --help
395 irunner.py --python -- --help
396
396
397 will pass --help to the python runner. Similarly,
397 will pass --help to the python runner. Similarly,
398
398
399 irunner.py --ipython -- --interact script.ipy
399 irunner.py --ipython -- --interact script.ipy
400
400
401 will run the script.ipy file under the IPython runner, and then will start to
401 will run the script.ipy file under the IPython runner, and then will start to
402 interact with IPython at the end of the script (instead of exiting).
402 interact with IPython at the end of the script (instead of exiting).
403
403
404 The already implemented runners are listed below; adding one for a new program
404 The already implemented runners are listed below; adding one for a new program
405 is a trivial task, see the source for examples.
405 is a trivial task, see the source for examples.
406
406
407 WARNING: the SAGE runner only works if you manually configure your SAGE copy
407 WARNING: the SAGE runner only works if you manually configure your SAGE copy
408 to use 'colors NoColor' in the ipythonrc config file, since currently the
408 to use 'colors NoColor' in the ipythonrc config file, since currently the
409 prompt matching regexp does not identify color sequences.
409 prompt matching regexp does not identify color sequences.
410 """
410 """
411
411
412 def main():
412 def main():
413 """Run as a command-line script."""
413 """Run as a command-line script."""
414
414
415 parser = optparse.OptionParser(usage=MAIN_USAGE)
415 parser = optparse.OptionParser(usage=MAIN_USAGE)
416 newopt = parser.add_option
416 newopt = parser.add_option
417 parser.set_defaults(mode='ipython')
417 parser.set_defaults(mode='ipython')
418 newopt('--ipython',action='store_const',dest='mode',const='ipython',
418 newopt('--ipython',action='store_const',dest='mode',const='ipython',
419 help='IPython interactive runner (default).')
419 help='IPython interactive runner (default).')
420 newopt('--python',action='store_const',dest='mode',const='python',
420 newopt('--python',action='store_const',dest='mode',const='python',
421 help='Python interactive runner.')
421 help='Python interactive runner.')
422 newopt('--sage',action='store_const',dest='mode',const='sage',
422 newopt('--sage',action='store_const',dest='mode',const='sage',
423 help='SAGE interactive runner.')
423 help='SAGE interactive runner.')
424
424
425 opts,args = parser.parse_args()
425 opts,args = parser.parse_args()
426 runners = dict(ipython=IPythonRunner,
426 runners = dict(ipython=IPythonRunner,
427 python=PythonRunner,
427 python=PythonRunner,
428 sage=SAGERunner)
428 sage=SAGERunner)
429
429
430 try:
430 try:
431 ext = os.path.splitext(args[0])[-1]
431 ext = os.path.splitext(args[0])[-1]
432 except IndexError:
432 except IndexError:
433 ext = ''
433 ext = ''
434 modes = {'.ipy':'ipython',
434 modes = {'.ipy':'ipython',
435 '.py':'python',
435 '.py':'python',
436 '.sage':'sage'}
436 '.sage':'sage'}
437 mode = modes.get(ext,opts.mode)
437 mode = modes.get(ext,opts.mode)
438 runners[mode]().main(args)
438 runners[mode]().main(args)
439
439
440 if __name__ == '__main__':
440 if __name__ == '__main__':
441 main()
441 main()
@@ -1,246 +1,246 b''
1 """ File system operations
1 """ File system operations
2
2
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
3 Contains: Simple variants of normal unix shell commands (icp, imv, irm,
4 imkdir, igrep).
4 imkdir, igrep).
5
5
6 Some "otherwise handy" utils ('collect' for gathering files to
6 Some "otherwise handy" utils ('collect' for gathering files to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
7 ~/_ipython/collect, 'inote' for collecting single note lines to
8 ~/_ipython/note.txt)
8 ~/_ipython/note.txt)
9
9
10 Mostly of use for bare windows installations where cygwin/equivalent is not
10 Mostly of use for bare windows installations where cygwin/equivalent is not
11 installed and you would otherwise need to deal with dos versions of the
11 installed and you would otherwise need to deal with dos versions of the
12 commands (that e.g. don't understand / as path separator). These can
12 commands (that e.g. don't understand / as path separator). These can
13 do some useful tricks on their own, though (like use 'mglob' patterns).
13 do some useful tricks on their own, though (like use 'mglob' patterns).
14
14
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
15 Not to be confused with ipipe commands (ils etc.) that also start with i.
16 """
16 """
17
17
18 from IPython.core import ipapi
18 from IPython.core import ipapi
19 from IPython.core.error import TryNext
19 from IPython.core.error import TryNext
20 ip = ipapi.get()
20 ip = ipapi.get()
21
21
22 import shutil,os,shlex
22 import shutil,os,shlex
23 from IPython.external import mglob
23 from IPython.external import mglob
24 from IPython.external.path import path
24 from IPython.external.path import path
25 from IPython.core.error import UsageError
25 from IPython.core.error import UsageError
26 import IPython.utils.generics
26 import IPython.utils.generics
27
27
28 def parse_args(args):
28 def parse_args(args):
29 """ Given arg string 'CMD files... target', return ([files], target) """
29 """ Given arg string 'CMD files... target', return ([files], target) """
30
30
31 tup = args.split(None, 1)
31 tup = args.split(None, 1)
32 if len(tup) == 1:
32 if len(tup) == 1:
33 raise UsageError("Expected arguments for " + tup[0])
33 raise UsageError("Expected arguments for " + tup[0])
34
34
35 tup2 = shlex.split(tup[1])
35 tup2 = shlex.split(tup[1])
36
36
37 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
37 flist, trg = mglob.expand(tup2[0:-1]), tup2[-1]
38 if not flist:
38 if not flist:
39 raise UsageError("No files found:" + str(tup2[0:-1]))
39 raise UsageError("No files found:" + str(tup2[0:-1]))
40 return flist, trg
40 return flist, trg
41
41
42 def icp(ip,arg):
42 def icp(ip,arg):
43 """ icp files... targetdir
43 """ icp files... targetdir
44
44
45 Copy all files to target, creating dirs for target if necessary
45 Copy all files to target, creating dirs for target if necessary
46
46
47 icp srcdir dstdir
47 icp srcdir dstdir
48
48
49 Copy srcdir to distdir
49 Copy srcdir to distdir
50
50
51 """
51 """
52 import distutils.dir_util
52 import distutils.dir_util
53
53
54 fs, targetdir = parse_args(arg)
54 fs, targetdir = parse_args(arg)
55 if not os.path.isdir(targetdir) and len(fs) > 1:
55 if not os.path.isdir(targetdir) and len(fs) > 1:
56 distutils.dir_util.mkpath(targetdir,verbose =1)
56 distutils.dir_util.mkpath(targetdir,verbose =1)
57 for f in fs:
57 for f in fs:
58 if os.path.isdir(f):
58 if os.path.isdir(f):
59 shutil.copytree(f, targetdir)
59 shutil.copytree(f, targetdir)
60 else:
60 else:
61 shutil.copy2(f,targetdir)
61 shutil.copy2(f,targetdir)
62 return fs
62 return fs
63 ip.define_alias("icp",icp)
63 ip.define_alias("icp",icp)
64
64
65 def imv(ip,arg):
65 def imv(ip,arg):
66 """ imv src tgt
66 """ imv src tgt
67
67
68 Move source to target.
68 Move source to target.
69 """
69 """
70
70
71 fs, target = parse_args(arg)
71 fs, target = parse_args(arg)
72 if len(fs) > 1:
72 if len(fs) > 1:
73 assert os.path.isdir(target)
73 assert os.path.isdir(target)
74 for f in fs:
74 for f in fs:
75 shutil.move(f, target)
75 shutil.move(f, target)
76 return fs
76 return fs
77 ip.define_alias("imv",imv)
77 ip.define_alias("imv",imv)
78
78
79 def irm(ip,arg):
79 def irm(ip,arg):
80 """ irm path[s]...
80 """ irm path[s]...
81
81
82 Remove file[s] or dir[s] path. Dirs are deleted recursively.
82 Remove file[s] or dir[s] path. Dirs are deleted recursively.
83 """
83 """
84 try:
84 try:
85 paths = mglob.expand(arg.split(None,1)[1])
85 paths = mglob.expand(arg.split(None,1)[1])
86 except IndexError:
86 except IndexError:
87 raise UsageError("%irm paths...")
87 raise UsageError("%irm paths...")
88 import distutils.dir_util
88 import distutils.dir_util
89 for p in paths:
89 for p in paths:
90 print "rm",p
90 print "rm",p
91 if os.path.isdir(p):
91 if os.path.isdir(p):
92 distutils.dir_util.remove_tree(p, verbose = 1)
92 distutils.dir_util.remove_tree(p, verbose = 1)
93 else:
93 else:
94 os.remove(p)
94 os.remove(p)
95
95
96 ip.define_alias("irm",irm)
96 ip.define_alias("irm",irm)
97
97
98 def imkdir(ip,arg):
98 def imkdir(ip,arg):
99 """ imkdir path
99 """ imkdir path
100
100
101 Creates dir path, and all dirs on the road
101 Creates dir path, and all dirs on the road
102 """
102 """
103 import distutils.dir_util
103 import distutils.dir_util
104 targetdir = arg.split(None,1)[1]
104 targetdir = arg.split(None,1)[1]
105 distutils.dir_util.mkpath(targetdir,verbose =1)
105 distutils.dir_util.mkpath(targetdir,verbose =1)
106
106
107 ip.define_alias("imkdir",imkdir)
107 ip.define_alias("imkdir",imkdir)
108
108
109 def igrep(ip,arg):
109 def igrep(ip,arg):
110 """ igrep PAT files...
110 """ igrep PAT files...
111
111
112 Very dumb file scan, case-insensitive.
112 Very dumb file scan, case-insensitive.
113
113
114 e.g.
114 e.g.
115
115
116 igrep "test this" rec:*.py
116 igrep "test this" rec:*.py
117
117
118 """
118 """
119 elems = shlex.split(arg)
119 elems = shlex.split(arg)
120 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
120 dummy, pat, fs = elems[0], elems[1], mglob.expand(elems[2:])
121 res = []
121 res = []
122 for f in fs:
122 for f in fs:
123 found = False
123 found = False
124 for l in open(f):
124 for l in open(f):
125 if pat.lower() in l.lower():
125 if pat.lower() in l.lower():
126 if not found:
126 if not found:
127 print "[[",f,"]]"
127 print "[[",f,"]]"
128 found = True
128 found = True
129 res.append(f)
129 res.append(f)
130 print l.rstrip()
130 print l.rstrip()
131 return res
131 return res
132
132
133 ip.define_alias("igrep",igrep)
133 ip.define_alias("igrep",igrep)
134
134
135 def collect(ip,arg):
135 def collect(ip,arg):
136 """ collect foo/a.txt rec:bar=*.py
136 """ collect foo/a.txt rec:bar=*.py
137
137
138 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
138 Copies foo/a.txt to ~/_ipython/collect/foo/a.txt and *.py from bar,
139 likewise
139 likewise
140
140
141 Without args, try to open ~/_ipython/collect dir (in win32 at least).
141 Without args, try to open ~/_ipython/collect dir (in win32 at least).
142 """
142 """
143 from IPython.external.path import path
143 from IPython.external.path import path
144 basedir = path(ip.options.IPYTHONDIR + '/collect')
144 basedir = path(ip.ipython_dir + '/collect')
145 try:
145 try:
146 fs = mglob.expand(arg.split(None,1)[1])
146 fs = mglob.expand(arg.split(None,1)[1])
147 except IndexError:
147 except IndexError:
148 os.startfile(basedir)
148 os.startfile(basedir)
149 return
149 return
150 for f in fs:
150 for f in fs:
151 f = path(f)
151 f = path(f)
152 trg = basedir / f.splitdrive()[1].lstrip('/\\')
152 trg = basedir / f.splitdrive()[1].lstrip('/\\')
153 if f.isdir():
153 if f.isdir():
154 print "mkdir",trg
154 print "mkdir",trg
155 trg.makedirs()
155 trg.makedirs()
156 continue
156 continue
157 dname = trg.dirname()
157 dname = trg.dirname()
158 if not dname.isdir():
158 if not dname.isdir():
159 dname.makedirs()
159 dname.makedirs()
160 print f,"=>",trg
160 print f,"=>",trg
161 shutil.copy2(f,trg)
161 shutil.copy2(f,trg)
162
162
163 ip.define_alias("collect",collect)
163 ip.define_alias("collect",collect)
164
164
165 def inote(ip,arg):
165 def inote(ip,arg):
166 """ inote Hello world
166 """ inote Hello world
167
167
168 Adds timestamp and Hello world to ~/_ipython/notes.txt
168 Adds timestamp and Hello world to ~/_ipython/notes.txt
169
169
170 Without args, opens notes.txt for editing.
170 Without args, opens notes.txt for editing.
171 """
171 """
172 import time
172 import time
173 fname = ip.options.IPYTHONDIR + '/notes.txt'
173 fname = ip.ipython_dir + '/notes.txt'
174
174
175 try:
175 try:
176 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
176 entry = " === " + time.asctime() + ': ===\n' + arg.split(None,1)[1] + '\n'
177 f= open(fname, 'a').write(entry)
177 f= open(fname, 'a').write(entry)
178 except IndexError:
178 except IndexError:
179 ip.hooks.editor(fname)
179 ip.hooks.editor(fname)
180
180
181 ip.define_alias("inote",inote)
181 ip.define_alias("inote",inote)
182
182
183 def pathobj_mangle(p):
183 def pathobj_mangle(p):
184 return p.replace(' ', '__').replace('.','DOT')
184 return p.replace(' ', '__').replace('.','DOT')
185 def pathobj_unmangle(s):
185 def pathobj_unmangle(s):
186 return s.replace('__',' ').replace('DOT','.')
186 return s.replace('__',' ').replace('DOT','.')
187
187
188
188
189
189
190 class PathObj(path):
190 class PathObj(path):
191 def __init__(self,p):
191 def __init__(self,p):
192 self.path = p
192 self.path = p
193 if p != '.':
193 if p != '.':
194 self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)]
194 self.ents = [pathobj_mangle(ent) for ent in os.listdir(p)]
195 else:
195 else:
196 self.ents = None
196 self.ents = None
197 def __complete__(self):
197 def __complete__(self):
198 if self.path != '.':
198 if self.path != '.':
199 return self.ents
199 return self.ents
200 self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')]
200 self.ents = [pathobj_mangle(ent) for ent in os.listdir('.')]
201 return self.ents
201 return self.ents
202 def __getattr__(self,name):
202 def __getattr__(self,name):
203 if name in self.ents:
203 if name in self.ents:
204 if self.path.endswith('/'):
204 if self.path.endswith('/'):
205 sep = ''
205 sep = ''
206 else:
206 else:
207 sep = '/'
207 sep = '/'
208
208
209 tgt = self.path + sep + pathobj_unmangle(name)
209 tgt = self.path + sep + pathobj_unmangle(name)
210 #print "tgt",tgt
210 #print "tgt",tgt
211 if os.path.isdir(tgt):
211 if os.path.isdir(tgt):
212 return PathObj(tgt)
212 return PathObj(tgt)
213 if os.path.isfile(tgt):
213 if os.path.isfile(tgt):
214 return path(tgt)
214 return path(tgt)
215
215
216 raise AttributeError, name # <<< DON'T FORGET THIS LINE !!
216 raise AttributeError, name # <<< DON'T FORGET THIS LINE !!
217 def __str__(self):
217 def __str__(self):
218 return self.path
218 return self.path
219
219
220 def __repr__(self):
220 def __repr__(self):
221 return "<PathObj to %s>" % self.path
221 return "<PathObj to %s>" % self.path
222
222
223 def __call__(self):
223 def __call__(self):
224 print "cd:",self.path
224 print "cd:",self.path
225 os.chdir(self.path)
225 os.chdir(self.path)
226
226
227 def complete_pathobj(obj, prev_completions):
227 def complete_pathobj(obj, prev_completions):
228 if hasattr(obj,'__complete__'):
228 if hasattr(obj,'__complete__'):
229 res = obj.__complete__()
229 res = obj.__complete__()
230 if res:
230 if res:
231 return res
231 return res
232 # just return normal attributes of 'path' object if the dir is empty
232 # just return normal attributes of 'path' object if the dir is empty
233 raise TryNext
233 raise TryNext
234
234
235 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
235 complete_pathobj = IPython.utils.generics.complete_object.when_type(PathObj)(complete_pathobj)
236
236
237 def test_pathobj():
237 def test_pathobj():
238 #p = PathObj('c:/prj')
238 #p = PathObj('c:/prj')
239 #p2 = p.cgi
239 #p2 = p.cgi
240 #print p,p2
240 #print p,p2
241 rootdir = PathObj("/")
241 rootdir = PathObj("/")
242 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
242 startmenu = PathObj("d:/Documents and Settings/All Users/Start Menu/Programs")
243 cwd = PathObj('.')
243 cwd = PathObj('.')
244 ip.push("rootdir startmenu cwd")
244 ip.push("rootdir startmenu cwd")
245
245
246 #test_pathobj() No newline at end of file
246 #test_pathobj()
@@ -1,1796 +1,1799 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """General purpose utilities.
2 """General purpose utilities.
3
3
4 This is a grab-bag of stuff I find useful in most programs I write. Some of
4 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 these things are also convenient when working at the command line.
5 these things are also convenient when working at the command line.
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 #****************************************************************************
15 #****************************************************************************
16 # required modules from the Python standard library
16 # required modules from the Python standard library
17 import __main__
17 import __main__
18
18
19 import os
19 import os
20 import platform
20 import platform
21 import re
21 import re
22 import shlex
22 import shlex
23 import shutil
23 import shutil
24 import subprocess
24 import subprocess
25 import sys
25 import sys
26 import time
26 import time
27 import types
27 import types
28 import warnings
28 import warnings
29
29
30 # Curses and termios are Unix-only modules
30 # Curses and termios are Unix-only modules
31 try:
31 try:
32 import curses
32 import curses
33 # We need termios as well, so if its import happens to raise, we bail on
33 # We need termios as well, so if its import happens to raise, we bail on
34 # using curses altogether.
34 # using curses altogether.
35 import termios
35 import termios
36 except ImportError:
36 except ImportError:
37 USE_CURSES = False
37 USE_CURSES = False
38 else:
38 else:
39 # Curses on Solaris may not be complete, so we can't use it there
39 # Curses on Solaris may not be complete, so we can't use it there
40 USE_CURSES = hasattr(curses,'initscr')
40 USE_CURSES = hasattr(curses,'initscr')
41
41
42 # Other IPython utilities
42 # Other IPython utilities
43 import IPython
43 import IPython
44 from IPython.external.Itpl import itpl,printpl
44 from IPython.external.Itpl import itpl,printpl
45 from IPython.utils import platutils
45 from IPython.utils import platutils
46 from IPython.utils.generics import result_display
46 from IPython.utils.generics import result_display
47 from IPython.external.path import path
47 from IPython.external.path import path
48
48
49 try:
49 try:
50 set
50 set
51 except:
51 except:
52 from sets import Set as set
52 from sets import Set as set
53
53
54
54
55 #****************************************************************************
55 #****************************************************************************
56 # Exceptions
56 # Exceptions
57 class Error(Exception):
57 class Error(Exception):
58 """Base class for exceptions in this module."""
58 """Base class for exceptions in this module."""
59 pass
59 pass
60
60
61 #----------------------------------------------------------------------------
61 #----------------------------------------------------------------------------
62 class IOStream:
62 class IOStream:
63 def __init__(self,stream,fallback):
63 def __init__(self,stream,fallback):
64 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
64 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
65 stream = fallback
65 stream = fallback
66 self.stream = stream
66 self.stream = stream
67 self._swrite = stream.write
67 self._swrite = stream.write
68 self.flush = stream.flush
68 self.flush = stream.flush
69
69
70 def write(self,data):
70 def write(self,data):
71 try:
71 try:
72 self._swrite(data)
72 self._swrite(data)
73 except:
73 except:
74 try:
74 try:
75 # print handles some unicode issues which may trip a plain
75 # print handles some unicode issues which may trip a plain
76 # write() call. Attempt to emulate write() by using a
76 # write() call. Attempt to emulate write() by using a
77 # trailing comma
77 # trailing comma
78 print >> self.stream, data,
78 print >> self.stream, data,
79 except:
79 except:
80 # if we get here, something is seriously broken.
80 # if we get here, something is seriously broken.
81 print >> sys.stderr, \
81 print >> sys.stderr, \
82 'ERROR - failed to write data to stream:', self.stream
82 'ERROR - failed to write data to stream:', self.stream
83
83
84 def close(self):
84 def close(self):
85 pass
85 pass
86
86
87
87
88 class IOTerm:
88 class IOTerm:
89 """ Term holds the file or file-like objects for handling I/O operations.
89 """ Term holds the file or file-like objects for handling I/O operations.
90
90
91 These are normally just sys.stdin, sys.stdout and sys.stderr but for
91 These are normally just sys.stdin, sys.stdout and sys.stderr but for
92 Windows they can can replaced to allow editing the strings before they are
92 Windows they can can replaced to allow editing the strings before they are
93 displayed."""
93 displayed."""
94
94
95 # In the future, having IPython channel all its I/O operations through
95 # In the future, having IPython channel all its I/O operations through
96 # this class will make it easier to embed it into other environments which
96 # this class will make it easier to embed it into other environments which
97 # are not a normal terminal (such as a GUI-based shell)
97 # are not a normal terminal (such as a GUI-based shell)
98 def __init__(self,cin=None,cout=None,cerr=None):
98 def __init__(self,cin=None,cout=None,cerr=None):
99 self.cin = IOStream(cin,sys.stdin)
99 self.cin = IOStream(cin,sys.stdin)
100 self.cout = IOStream(cout,sys.stdout)
100 self.cout = IOStream(cout,sys.stdout)
101 self.cerr = IOStream(cerr,sys.stderr)
101 self.cerr = IOStream(cerr,sys.stderr)
102
102
103 # Global variable to be used for all I/O
103 # Global variable to be used for all I/O
104 Term = IOTerm()
104 Term = IOTerm()
105
105
106 import IPython.utils.rlineimpl as readline
106 import IPython.utils.rlineimpl as readline
107 # Remake Term to use the readline i/o facilities
107 # Remake Term to use the readline i/o facilities
108 if sys.platform == 'win32' and readline.have_readline:
108 if sys.platform == 'win32' and readline.have_readline:
109
109
110 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
110 Term = IOTerm(cout=readline._outputfile,cerr=readline._outputfile)
111
111
112
112
113 #****************************************************************************
113 #****************************************************************************
114 # Generic warning/error printer, used by everything else
114 # Generic warning/error printer, used by everything else
115 def warn(msg,level=2,exit_val=1):
115 def warn(msg,level=2,exit_val=1):
116 """Standard warning printer. Gives formatting consistency.
116 """Standard warning printer. Gives formatting consistency.
117
117
118 Output is sent to Term.cerr (sys.stderr by default).
118 Output is sent to Term.cerr (sys.stderr by default).
119
119
120 Options:
120 Options:
121
121
122 -level(2): allows finer control:
122 -level(2): allows finer control:
123 0 -> Do nothing, dummy function.
123 0 -> Do nothing, dummy function.
124 1 -> Print message.
124 1 -> Print message.
125 2 -> Print 'WARNING:' + message. (Default level).
125 2 -> Print 'WARNING:' + message. (Default level).
126 3 -> Print 'ERROR:' + message.
126 3 -> Print 'ERROR:' + message.
127 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
127 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
128
128
129 -exit_val (1): exit value returned by sys.exit() for a level 4
129 -exit_val (1): exit value returned by sys.exit() for a level 4
130 warning. Ignored for all other levels."""
130 warning. Ignored for all other levels."""
131
131
132 if level>0:
132 if level>0:
133 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
133 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
134 print >> Term.cerr, '%s%s' % (header[level],msg)
134 print >> Term.cerr, '%s%s' % (header[level],msg)
135 if level == 4:
135 if level == 4:
136 print >> Term.cerr,'Exiting.\n'
136 print >> Term.cerr,'Exiting.\n'
137 sys.exit(exit_val)
137 sys.exit(exit_val)
138
138
139 def info(msg):
139 def info(msg):
140 """Equivalent to warn(msg,level=1)."""
140 """Equivalent to warn(msg,level=1)."""
141
141
142 warn(msg,level=1)
142 warn(msg,level=1)
143
143
144 def error(msg):
144 def error(msg):
145 """Equivalent to warn(msg,level=3)."""
145 """Equivalent to warn(msg,level=3)."""
146
146
147 warn(msg,level=3)
147 warn(msg,level=3)
148
148
149 def fatal(msg,exit_val=1):
149 def fatal(msg,exit_val=1):
150 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
150 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
151
151
152 warn(msg,exit_val=exit_val,level=4)
152 warn(msg,exit_val=exit_val,level=4)
153
153
154 #---------------------------------------------------------------------------
154 #---------------------------------------------------------------------------
155 # Debugging routines
155 # Debugging routines
156 #
156 #
157 def debugx(expr,pre_msg=''):
157 def debugx(expr,pre_msg=''):
158 """Print the value of an expression from the caller's frame.
158 """Print the value of an expression from the caller's frame.
159
159
160 Takes an expression, evaluates it in the caller's frame and prints both
160 Takes an expression, evaluates it in the caller's frame and prints both
161 the given expression and the resulting value (as well as a debug mark
161 the given expression and the resulting value (as well as a debug mark
162 indicating the name of the calling function. The input must be of a form
162 indicating the name of the calling function. The input must be of a form
163 suitable for eval().
163 suitable for eval().
164
164
165 An optional message can be passed, which will be prepended to the printed
165 An optional message can be passed, which will be prepended to the printed
166 expr->value pair."""
166 expr->value pair."""
167
167
168 cf = sys._getframe(1)
168 cf = sys._getframe(1)
169 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
169 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
170 eval(expr,cf.f_globals,cf.f_locals))
170 eval(expr,cf.f_globals,cf.f_locals))
171
171
172 # deactivate it by uncommenting the following line, which makes it a no-op
172 # deactivate it by uncommenting the following line, which makes it a no-op
173 #def debugx(expr,pre_msg=''): pass
173 #def debugx(expr,pre_msg=''): pass
174
174
175 #----------------------------------------------------------------------------
175 #----------------------------------------------------------------------------
176 StringTypes = types.StringTypes
176 StringTypes = types.StringTypes
177
177
178 # Basic timing functionality
178 # Basic timing functionality
179
179
180 # If possible (Unix), use the resource module instead of time.clock()
180 # If possible (Unix), use the resource module instead of time.clock()
181 try:
181 try:
182 import resource
182 import resource
183 def clocku():
183 def clocku():
184 """clocku() -> floating point number
184 """clocku() -> floating point number
185
185
186 Return the *USER* CPU time in seconds since the start of the process.
186 Return the *USER* CPU time in seconds since the start of the process.
187 This is done via a call to resource.getrusage, so it avoids the
187 This is done via a call to resource.getrusage, so it avoids the
188 wraparound problems in time.clock()."""
188 wraparound problems in time.clock()."""
189
189
190 return resource.getrusage(resource.RUSAGE_SELF)[0]
190 return resource.getrusage(resource.RUSAGE_SELF)[0]
191
191
192 def clocks():
192 def clocks():
193 """clocks() -> floating point number
193 """clocks() -> floating point number
194
194
195 Return the *SYSTEM* CPU time in seconds since the start of the process.
195 Return the *SYSTEM* CPU time in seconds since the start of the process.
196 This is done via a call to resource.getrusage, so it avoids the
196 This is done via a call to resource.getrusage, so it avoids the
197 wraparound problems in time.clock()."""
197 wraparound problems in time.clock()."""
198
198
199 return resource.getrusage(resource.RUSAGE_SELF)[1]
199 return resource.getrusage(resource.RUSAGE_SELF)[1]
200
200
201 def clock():
201 def clock():
202 """clock() -> floating point number
202 """clock() -> floating point number
203
203
204 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
204 Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of
205 the process. This is done via a call to resource.getrusage, so it
205 the process. This is done via a call to resource.getrusage, so it
206 avoids the wraparound problems in time.clock()."""
206 avoids the wraparound problems in time.clock()."""
207
207
208 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
208 u,s = resource.getrusage(resource.RUSAGE_SELF)[:2]
209 return u+s
209 return u+s
210
210
211 def clock2():
211 def clock2():
212 """clock2() -> (t_user,t_system)
212 """clock2() -> (t_user,t_system)
213
213
214 Similar to clock(), but return a tuple of user/system times."""
214 Similar to clock(), but return a tuple of user/system times."""
215 return resource.getrusage(resource.RUSAGE_SELF)[:2]
215 return resource.getrusage(resource.RUSAGE_SELF)[:2]
216
216
217 except ImportError:
217 except ImportError:
218 # There is no distinction of user/system time under windows, so we just use
218 # There is no distinction of user/system time under windows, so we just use
219 # time.clock() for everything...
219 # time.clock() for everything...
220 clocku = clocks = clock = time.clock
220 clocku = clocks = clock = time.clock
221 def clock2():
221 def clock2():
222 """Under windows, system CPU time can't be measured.
222 """Under windows, system CPU time can't be measured.
223
223
224 This just returns clock() and zero."""
224 This just returns clock() and zero."""
225 return time.clock(),0.0
225 return time.clock(),0.0
226
226
227 def timings_out(reps,func,*args,**kw):
227 def timings_out(reps,func,*args,**kw):
228 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
228 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
229
229
230 Execute a function reps times, return a tuple with the elapsed total
230 Execute a function reps times, return a tuple with the elapsed total
231 CPU time in seconds, the time per call and the function's output.
231 CPU time in seconds, the time per call and the function's output.
232
232
233 Under Unix, the return value is the sum of user+system time consumed by
233 Under Unix, the return value is the sum of user+system time consumed by
234 the process, computed via the resource module. This prevents problems
234 the process, computed via the resource module. This prevents problems
235 related to the wraparound effect which the time.clock() function has.
235 related to the wraparound effect which the time.clock() function has.
236
236
237 Under Windows the return value is in wall clock seconds. See the
237 Under Windows the return value is in wall clock seconds. See the
238 documentation for the time module for more details."""
238 documentation for the time module for more details."""
239
239
240 reps = int(reps)
240 reps = int(reps)
241 assert reps >=1, 'reps must be >= 1'
241 assert reps >=1, 'reps must be >= 1'
242 if reps==1:
242 if reps==1:
243 start = clock()
243 start = clock()
244 out = func(*args,**kw)
244 out = func(*args,**kw)
245 tot_time = clock()-start
245 tot_time = clock()-start
246 else:
246 else:
247 rng = xrange(reps-1) # the last time is executed separately to store output
247 rng = xrange(reps-1) # the last time is executed separately to store output
248 start = clock()
248 start = clock()
249 for dummy in rng: func(*args,**kw)
249 for dummy in rng: func(*args,**kw)
250 out = func(*args,**kw) # one last time
250 out = func(*args,**kw) # one last time
251 tot_time = clock()-start
251 tot_time = clock()-start
252 av_time = tot_time / reps
252 av_time = tot_time / reps
253 return tot_time,av_time,out
253 return tot_time,av_time,out
254
254
255 def timings(reps,func,*args,**kw):
255 def timings(reps,func,*args,**kw):
256 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
256 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
257
257
258 Execute a function reps times, return a tuple with the elapsed total CPU
258 Execute a function reps times, return a tuple with the elapsed total CPU
259 time in seconds and the time per call. These are just the first two values
259 time in seconds and the time per call. These are just the first two values
260 in timings_out()."""
260 in timings_out()."""
261
261
262 return timings_out(reps,func,*args,**kw)[0:2]
262 return timings_out(reps,func,*args,**kw)[0:2]
263
263
264 def timing(func,*args,**kw):
264 def timing(func,*args,**kw):
265 """timing(func,*args,**kw) -> t_total
265 """timing(func,*args,**kw) -> t_total
266
266
267 Execute a function once, return the elapsed total CPU time in
267 Execute a function once, return the elapsed total CPU time in
268 seconds. This is just the first value in timings_out()."""
268 seconds. This is just the first value in timings_out()."""
269
269
270 return timings_out(1,func,*args,**kw)[0]
270 return timings_out(1,func,*args,**kw)[0]
271
271
272 #****************************************************************************
272 #****************************************************************************
273 # file and system
273 # file and system
274
274
275 def arg_split(s,posix=False):
275 def arg_split(s,posix=False):
276 """Split a command line's arguments in a shell-like manner.
276 """Split a command line's arguments in a shell-like manner.
277
277
278 This is a modified version of the standard library's shlex.split()
278 This is a modified version of the standard library's shlex.split()
279 function, but with a default of posix=False for splitting, so that quotes
279 function, but with a default of posix=False for splitting, so that quotes
280 in inputs are respected."""
280 in inputs are respected."""
281
281
282 # XXX - there may be unicode-related problems here!!! I'm not sure that
282 # XXX - there may be unicode-related problems here!!! I'm not sure that
283 # shlex is truly unicode-safe, so it might be necessary to do
283 # shlex is truly unicode-safe, so it might be necessary to do
284 #
284 #
285 # s = s.encode(sys.stdin.encoding)
285 # s = s.encode(sys.stdin.encoding)
286 #
286 #
287 # first, to ensure that shlex gets a normal string. Input from anyone who
287 # first, to ensure that shlex gets a normal string. Input from anyone who
288 # knows more about unicode and shlex than I would be good to have here...
288 # knows more about unicode and shlex than I would be good to have here...
289 lex = shlex.shlex(s, posix=posix)
289 lex = shlex.shlex(s, posix=posix)
290 lex.whitespace_split = True
290 lex.whitespace_split = True
291 return list(lex)
291 return list(lex)
292
292
293 def system(cmd,verbose=0,debug=0,header=''):
293 def system(cmd,verbose=0,debug=0,header=''):
294 """Execute a system command, return its exit status.
294 """Execute a system command, return its exit status.
295
295
296 Options:
296 Options:
297
297
298 - verbose (0): print the command to be executed.
298 - verbose (0): print the command to be executed.
299
299
300 - debug (0): only print, do not actually execute.
300 - debug (0): only print, do not actually execute.
301
301
302 - header (''): Header to print on screen prior to the executed command (it
302 - header (''): Header to print on screen prior to the executed command (it
303 is only prepended to the command, no newlines are added).
303 is only prepended to the command, no newlines are added).
304
304
305 Note: a stateful version of this function is available through the
305 Note: a stateful version of this function is available through the
306 SystemExec class."""
306 SystemExec class."""
307
307
308 stat = 0
308 stat = 0
309 if verbose or debug: print header+cmd
309 if verbose or debug: print header+cmd
310 sys.stdout.flush()
310 sys.stdout.flush()
311 if not debug: stat = os.system(cmd)
311 if not debug: stat = os.system(cmd)
312 return stat
312 return stat
313
313
314 def abbrev_cwd():
314 def abbrev_cwd():
315 """ Return abbreviated version of cwd, e.g. d:mydir """
315 """ Return abbreviated version of cwd, e.g. d:mydir """
316 cwd = os.getcwd().replace('\\','/')
316 cwd = os.getcwd().replace('\\','/')
317 drivepart = ''
317 drivepart = ''
318 tail = cwd
318 tail = cwd
319 if sys.platform == 'win32':
319 if sys.platform == 'win32':
320 if len(cwd) < 4:
320 if len(cwd) < 4:
321 return cwd
321 return cwd
322 drivepart,tail = os.path.splitdrive(cwd)
322 drivepart,tail = os.path.splitdrive(cwd)
323
323
324
324
325 parts = tail.split('/')
325 parts = tail.split('/')
326 if len(parts) > 2:
326 if len(parts) > 2:
327 tail = '/'.join(parts[-2:])
327 tail = '/'.join(parts[-2:])
328
328
329 return (drivepart + (
329 return (drivepart + (
330 cwd == '/' and '/' or tail))
330 cwd == '/' and '/' or tail))
331
331
332
332
333 # This function is used by ipython in a lot of places to make system calls.
333 # This function is used by ipython in a lot of places to make system calls.
334 # We need it to be slightly different under win32, due to the vagaries of
334 # We need it to be slightly different under win32, due to the vagaries of
335 # 'network shares'. A win32 override is below.
335 # 'network shares'. A win32 override is below.
336
336
337 def shell(cmd,verbose=0,debug=0,header=''):
337 def shell(cmd,verbose=0,debug=0,header=''):
338 """Execute a command in the system shell, always return None.
338 """Execute a command in the system shell, always return None.
339
339
340 Options:
340 Options:
341
341
342 - verbose (0): print the command to be executed.
342 - verbose (0): print the command to be executed.
343
343
344 - debug (0): only print, do not actually execute.
344 - debug (0): only print, do not actually execute.
345
345
346 - header (''): Header to print on screen prior to the executed command (it
346 - header (''): Header to print on screen prior to the executed command (it
347 is only prepended to the command, no newlines are added).
347 is only prepended to the command, no newlines are added).
348
348
349 Note: this is similar to genutils.system(), but it returns None so it can
349 Note: this is similar to genutils.system(), but it returns None so it can
350 be conveniently used in interactive loops without getting the return value
350 be conveniently used in interactive loops without getting the return value
351 (typically 0) printed many times."""
351 (typically 0) printed many times."""
352
352
353 stat = 0
353 stat = 0
354 if verbose or debug: print header+cmd
354 if verbose or debug: print header+cmd
355 # flush stdout so we don't mangle python's buffering
355 # flush stdout so we don't mangle python's buffering
356 sys.stdout.flush()
356 sys.stdout.flush()
357
357
358 if not debug:
358 if not debug:
359 platutils.set_term_title("IPy " + cmd)
359 platutils.set_term_title("IPy " + cmd)
360 os.system(cmd)
360 os.system(cmd)
361 platutils.set_term_title("IPy " + abbrev_cwd())
361 platutils.set_term_title("IPy " + abbrev_cwd())
362
362
363 # override shell() for win32 to deal with network shares
363 # override shell() for win32 to deal with network shares
364 if os.name in ('nt','dos'):
364 if os.name in ('nt','dos'):
365
365
366 shell_ori = shell
366 shell_ori = shell
367
367
368 def shell(cmd,verbose=0,debug=0,header=''):
368 def shell(cmd,verbose=0,debug=0,header=''):
369 if os.getcwd().startswith(r"\\"):
369 if os.getcwd().startswith(r"\\"):
370 path = os.getcwd()
370 path = os.getcwd()
371 # change to c drive (cannot be on UNC-share when issuing os.system,
371 # change to c drive (cannot be on UNC-share when issuing os.system,
372 # as cmd.exe cannot handle UNC addresses)
372 # as cmd.exe cannot handle UNC addresses)
373 os.chdir("c:")
373 os.chdir("c:")
374 # issue pushd to the UNC-share and then run the command
374 # issue pushd to the UNC-share and then run the command
375 try:
375 try:
376 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
376 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
377 finally:
377 finally:
378 os.chdir(path)
378 os.chdir(path)
379 else:
379 else:
380 shell_ori(cmd,verbose,debug,header)
380 shell_ori(cmd,verbose,debug,header)
381
381
382 shell.__doc__ = shell_ori.__doc__
382 shell.__doc__ = shell_ori.__doc__
383
383
384 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
384 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
385 """Dummy substitute for perl's backquotes.
385 """Dummy substitute for perl's backquotes.
386
386
387 Executes a command and returns the output.
387 Executes a command and returns the output.
388
388
389 Accepts the same arguments as system(), plus:
389 Accepts the same arguments as system(), plus:
390
390
391 - split(0): if true, the output is returned as a list split on newlines.
391 - split(0): if true, the output is returned as a list split on newlines.
392
392
393 Note: a stateful version of this function is available through the
393 Note: a stateful version of this function is available through the
394 SystemExec class.
394 SystemExec class.
395
395
396 This is pretty much deprecated and rarely used,
396 This is pretty much deprecated and rarely used,
397 genutils.getoutputerror may be what you need.
397 genutils.getoutputerror may be what you need.
398
398
399 """
399 """
400
400
401 if verbose or debug: print header+cmd
401 if verbose or debug: print header+cmd
402 if not debug:
402 if not debug:
403 output = os.popen(cmd).read()
403 output = os.popen(cmd).read()
404 # stipping last \n is here for backwards compat.
404 # stipping last \n is here for backwards compat.
405 if output.endswith('\n'):
405 if output.endswith('\n'):
406 output = output[:-1]
406 output = output[:-1]
407 if split:
407 if split:
408 return output.split('\n')
408 return output.split('\n')
409 else:
409 else:
410 return output
410 return output
411
411
412 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
412 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
413 """Return (standard output,standard error) of executing cmd in a shell.
413 """Return (standard output,standard error) of executing cmd in a shell.
414
414
415 Accepts the same arguments as system(), plus:
415 Accepts the same arguments as system(), plus:
416
416
417 - split(0): if true, each of stdout/err is returned as a list split on
417 - split(0): if true, each of stdout/err is returned as a list split on
418 newlines.
418 newlines.
419
419
420 Note: a stateful version of this function is available through the
420 Note: a stateful version of this function is available through the
421 SystemExec class."""
421 SystemExec class."""
422
422
423 if verbose or debug: print header+cmd
423 if verbose or debug: print header+cmd
424 if not cmd:
424 if not cmd:
425 if split:
425 if split:
426 return [],[]
426 return [],[]
427 else:
427 else:
428 return '',''
428 return '',''
429 if not debug:
429 if not debug:
430 pin,pout,perr = os.popen3(cmd)
430 pin,pout,perr = os.popen3(cmd)
431 tout = pout.read().rstrip()
431 tout = pout.read().rstrip()
432 terr = perr.read().rstrip()
432 terr = perr.read().rstrip()
433 pin.close()
433 pin.close()
434 pout.close()
434 pout.close()
435 perr.close()
435 perr.close()
436 if split:
436 if split:
437 return tout.split('\n'),terr.split('\n')
437 return tout.split('\n'),terr.split('\n')
438 else:
438 else:
439 return tout,terr
439 return tout,terr
440
440
441 # for compatibility with older naming conventions
441 # for compatibility with older naming conventions
442 xsys = system
442 xsys = system
443 bq = getoutput
443 bq = getoutput
444
444
445 class SystemExec:
445 class SystemExec:
446 """Access the system and getoutput functions through a stateful interface.
446 """Access the system and getoutput functions through a stateful interface.
447
447
448 Note: here we refer to the system and getoutput functions from this
448 Note: here we refer to the system and getoutput functions from this
449 library, not the ones from the standard python library.
449 library, not the ones from the standard python library.
450
450
451 This class offers the system and getoutput functions as methods, but the
451 This class offers the system and getoutput functions as methods, but the
452 verbose, debug and header parameters can be set for the instance (at
452 verbose, debug and header parameters can be set for the instance (at
453 creation time or later) so that they don't need to be specified on each
453 creation time or later) so that they don't need to be specified on each
454 call.
454 call.
455
455
456 For efficiency reasons, there's no way to override the parameters on a
456 For efficiency reasons, there's no way to override the parameters on a
457 per-call basis other than by setting instance attributes. If you need
457 per-call basis other than by setting instance attributes. If you need
458 local overrides, it's best to directly call system() or getoutput().
458 local overrides, it's best to directly call system() or getoutput().
459
459
460 The following names are provided as alternate options:
460 The following names are provided as alternate options:
461 - xsys: alias to system
461 - xsys: alias to system
462 - bq: alias to getoutput
462 - bq: alias to getoutput
463
463
464 An instance can then be created as:
464 An instance can then be created as:
465 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
465 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
466 """
466 """
467
467
468 def __init__(self,verbose=0,debug=0,header='',split=0):
468 def __init__(self,verbose=0,debug=0,header='',split=0):
469 """Specify the instance's values for verbose, debug and header."""
469 """Specify the instance's values for verbose, debug and header."""
470 setattr_list(self,'verbose debug header split')
470 setattr_list(self,'verbose debug header split')
471
471
472 def system(self,cmd):
472 def system(self,cmd):
473 """Stateful interface to system(), with the same keyword parameters."""
473 """Stateful interface to system(), with the same keyword parameters."""
474
474
475 system(cmd,self.verbose,self.debug,self.header)
475 system(cmd,self.verbose,self.debug,self.header)
476
476
477 def shell(self,cmd):
477 def shell(self,cmd):
478 """Stateful interface to shell(), with the same keyword parameters."""
478 """Stateful interface to shell(), with the same keyword parameters."""
479
479
480 shell(cmd,self.verbose,self.debug,self.header)
480 shell(cmd,self.verbose,self.debug,self.header)
481
481
482 xsys = system # alias
482 xsys = system # alias
483
483
484 def getoutput(self,cmd):
484 def getoutput(self,cmd):
485 """Stateful interface to getoutput()."""
485 """Stateful interface to getoutput()."""
486
486
487 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
487 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
488
488
489 def getoutputerror(self,cmd):
489 def getoutputerror(self,cmd):
490 """Stateful interface to getoutputerror()."""
490 """Stateful interface to getoutputerror()."""
491
491
492 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
492 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
493
493
494 bq = getoutput # alias
494 bq = getoutput # alias
495
495
496 #-----------------------------------------------------------------------------
496 #-----------------------------------------------------------------------------
497 def mutex_opts(dict,ex_op):
497 def mutex_opts(dict,ex_op):
498 """Check for presence of mutually exclusive keys in a dict.
498 """Check for presence of mutually exclusive keys in a dict.
499
499
500 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
500 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
501 for op1,op2 in ex_op:
501 for op1,op2 in ex_op:
502 if op1 in dict and op2 in dict:
502 if op1 in dict and op2 in dict:
503 raise ValueError,'\n*** ERROR in Arguments *** '\
503 raise ValueError,'\n*** ERROR in Arguments *** '\
504 'Options '+op1+' and '+op2+' are mutually exclusive.'
504 'Options '+op1+' and '+op2+' are mutually exclusive.'
505
505
506 #-----------------------------------------------------------------------------
506 #-----------------------------------------------------------------------------
507 def get_py_filename(name):
507 def get_py_filename(name):
508 """Return a valid python filename in the current directory.
508 """Return a valid python filename in the current directory.
509
509
510 If the given name is not a file, it adds '.py' and searches again.
510 If the given name is not a file, it adds '.py' and searches again.
511 Raises IOError with an informative message if the file isn't found."""
511 Raises IOError with an informative message if the file isn't found."""
512
512
513 name = os.path.expanduser(name)
513 name = os.path.expanduser(name)
514 if not os.path.isfile(name) and not name.endswith('.py'):
514 if not os.path.isfile(name) and not name.endswith('.py'):
515 name += '.py'
515 name += '.py'
516 if os.path.isfile(name):
516 if os.path.isfile(name):
517 return name
517 return name
518 else:
518 else:
519 raise IOError,'File `%s` not found.' % name
519 raise IOError,'File `%s` not found.' % name
520
520
521 #-----------------------------------------------------------------------------
521 #-----------------------------------------------------------------------------
522
522
523
523
524 def filefind(filename, path_dirs=None):
524 def filefind(filename, path_dirs=None):
525 """Find a file by looking through a sequence of paths.
525 """Find a file by looking through a sequence of paths.
526
526
527 This iterates through a sequence of paths looking for a file and returns
527 This iterates through a sequence of paths looking for a file and returns
528 the full, absolute path of the first occurence of the file. If no set of
528 the full, absolute path of the first occurence of the file. If no set of
529 path dirs is given, the filename is tested as is, after running through
529 path dirs is given, the filename is tested as is, after running through
530 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
530 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
531
531
532 filefind('myfile.txt')
532 filefind('myfile.txt')
533
533
534 will find the file in the current working dir, but::
534 will find the file in the current working dir, but::
535
535
536 filefind('~/myfile.txt')
536 filefind('~/myfile.txt')
537
537
538 Will find the file in the users home directory. This function does not
538 Will find the file in the users home directory. This function does not
539 automatically try any paths, such as the cwd or the user's home directory.
539 automatically try any paths, such as the cwd or the user's home directory.
540
540
541 Parameters
541 Parameters
542 ----------
542 ----------
543 filename : str
543 filename : str
544 The filename to look for.
544 The filename to look for.
545 path_dirs : str, None or sequence of str
545 path_dirs : str, None or sequence of str
546 The sequence of paths to look for the file in. If None, the filename
546 The sequence of paths to look for the file in. If None, the filename
547 need to be absolute or be in the cwd. If a string, the string is
547 need to be absolute or be in the cwd. If a string, the string is
548 put into a sequence and the searched. If a sequence, walk through
548 put into a sequence and the searched. If a sequence, walk through
549 each element and join with ``filename``, calling :func:`expandvars`
549 each element and join with ``filename``, calling :func:`expandvars`
550 and :func:`expanduser` before testing for existence.
550 and :func:`expanduser` before testing for existence.
551
551
552 Returns
552 Returns
553 -------
553 -------
554 Raises :exc:`IOError` or returns absolute path to file.
554 Raises :exc:`IOError` or returns absolute path to file.
555 """
555 """
556 if path_dirs is None:
556 if path_dirs is None:
557 path_dirs = ("",)
557 path_dirs = ("",)
558 elif isinstance(path_dirs, basestring):
558 elif isinstance(path_dirs, basestring):
559 path_dirs = (path_dirs,)
559 path_dirs = (path_dirs,)
560 for path in path_dirs:
560 for path in path_dirs:
561 if path == '.': path = os.getcwd()
561 if path == '.': path = os.getcwd()
562 testname = os.path.expandvars(
562 testname = os.path.expandvars(
563 os.path.expanduser(
563 os.path.expanduser(
564 os.path.join(path, filename)))
564 os.path.join(path, filename)))
565 if os.path.isfile(testname):
565 if os.path.isfile(testname):
566 return os.path.abspath(testname)
566 return os.path.abspath(testname)
567 raise IOError("File does not exist in any "
567 raise IOError("File does not exist in any "
568 "of the search paths: %r, %r" % \
568 "of the search paths: %r, %r" % \
569 (filename, path_dirs))
569 (filename, path_dirs))
570
570
571
571
572 #----------------------------------------------------------------------------
572 #----------------------------------------------------------------------------
573 def file_read(filename):
573 def file_read(filename):
574 """Read a file and close it. Returns the file source."""
574 """Read a file and close it. Returns the file source."""
575 fobj = open(filename,'r');
575 fobj = open(filename,'r');
576 source = fobj.read();
576 source = fobj.read();
577 fobj.close()
577 fobj.close()
578 return source
578 return source
579
579
580 def file_readlines(filename):
580 def file_readlines(filename):
581 """Read a file and close it. Returns the file source using readlines()."""
581 """Read a file and close it. Returns the file source using readlines()."""
582 fobj = open(filename,'r');
582 fobj = open(filename,'r');
583 lines = fobj.readlines();
583 lines = fobj.readlines();
584 fobj.close()
584 fobj.close()
585 return lines
585 return lines
586
586
587 #----------------------------------------------------------------------------
587 #----------------------------------------------------------------------------
588 def target_outdated(target,deps):
588 def target_outdated(target,deps):
589 """Determine whether a target is out of date.
589 """Determine whether a target is out of date.
590
590
591 target_outdated(target,deps) -> 1/0
591 target_outdated(target,deps) -> 1/0
592
592
593 deps: list of filenames which MUST exist.
593 deps: list of filenames which MUST exist.
594 target: single filename which may or may not exist.
594 target: single filename which may or may not exist.
595
595
596 If target doesn't exist or is older than any file listed in deps, return
596 If target doesn't exist or is older than any file listed in deps, return
597 true, otherwise return false.
597 true, otherwise return false.
598 """
598 """
599 try:
599 try:
600 target_time = os.path.getmtime(target)
600 target_time = os.path.getmtime(target)
601 except os.error:
601 except os.error:
602 return 1
602 return 1
603 for dep in deps:
603 for dep in deps:
604 dep_time = os.path.getmtime(dep)
604 dep_time = os.path.getmtime(dep)
605 if dep_time > target_time:
605 if dep_time > target_time:
606 #print "For target",target,"Dep failed:",dep # dbg
606 #print "For target",target,"Dep failed:",dep # dbg
607 #print "times (dep,tar):",dep_time,target_time # dbg
607 #print "times (dep,tar):",dep_time,target_time # dbg
608 return 1
608 return 1
609 return 0
609 return 0
610
610
611 #-----------------------------------------------------------------------------
611 #-----------------------------------------------------------------------------
612 def target_update(target,deps,cmd):
612 def target_update(target,deps,cmd):
613 """Update a target with a given command given a list of dependencies.
613 """Update a target with a given command given a list of dependencies.
614
614
615 target_update(target,deps,cmd) -> runs cmd if target is outdated.
615 target_update(target,deps,cmd) -> runs cmd if target is outdated.
616
616
617 This is just a wrapper around target_outdated() which calls the given
617 This is just a wrapper around target_outdated() which calls the given
618 command if target is outdated."""
618 command if target is outdated."""
619
619
620 if target_outdated(target,deps):
620 if target_outdated(target,deps):
621 xsys(cmd)
621 xsys(cmd)
622
622
623 #----------------------------------------------------------------------------
623 #----------------------------------------------------------------------------
624 def unquote_ends(istr):
624 def unquote_ends(istr):
625 """Remove a single pair of quotes from the endpoints of a string."""
625 """Remove a single pair of quotes from the endpoints of a string."""
626
626
627 if not istr:
627 if not istr:
628 return istr
628 return istr
629 if (istr[0]=="'" and istr[-1]=="'") or \
629 if (istr[0]=="'" and istr[-1]=="'") or \
630 (istr[0]=='"' and istr[-1]=='"'):
630 (istr[0]=='"' and istr[-1]=='"'):
631 return istr[1:-1]
631 return istr[1:-1]
632 else:
632 else:
633 return istr
633 return istr
634
634
635 #----------------------------------------------------------------------------
635 #----------------------------------------------------------------------------
636 def flag_calls(func):
636 def flag_calls(func):
637 """Wrap a function to detect and flag when it gets called.
637 """Wrap a function to detect and flag when it gets called.
638
638
639 This is a decorator which takes a function and wraps it in a function with
639 This is a decorator which takes a function and wraps it in a function with
640 a 'called' attribute. wrapper.called is initialized to False.
640 a 'called' attribute. wrapper.called is initialized to False.
641
641
642 The wrapper.called attribute is set to False right before each call to the
642 The wrapper.called attribute is set to False right before each call to the
643 wrapped function, so if the call fails it remains False. After the call
643 wrapped function, so if the call fails it remains False. After the call
644 completes, wrapper.called is set to True and the output is returned.
644 completes, wrapper.called is set to True and the output is returned.
645
645
646 Testing for truth in wrapper.called allows you to determine if a call to
646 Testing for truth in wrapper.called allows you to determine if a call to
647 func() was attempted and succeeded."""
647 func() was attempted and succeeded."""
648
648
649 def wrapper(*args,**kw):
649 def wrapper(*args,**kw):
650 wrapper.called = False
650 wrapper.called = False
651 out = func(*args,**kw)
651 out = func(*args,**kw)
652 wrapper.called = True
652 wrapper.called = True
653 return out
653 return out
654
654
655 wrapper.called = False
655 wrapper.called = False
656 wrapper.__doc__ = func.__doc__
656 wrapper.__doc__ = func.__doc__
657 return wrapper
657 return wrapper
658
658
659 #----------------------------------------------------------------------------
659 #----------------------------------------------------------------------------
660 def dhook_wrap(func,*a,**k):
660 def dhook_wrap(func,*a,**k):
661 """Wrap a function call in a sys.displayhook controller.
661 """Wrap a function call in a sys.displayhook controller.
662
662
663 Returns a wrapper around func which calls func, with all its arguments and
663 Returns a wrapper around func which calls func, with all its arguments and
664 keywords unmodified, using the default sys.displayhook. Since IPython
664 keywords unmodified, using the default sys.displayhook. Since IPython
665 modifies sys.displayhook, it breaks the behavior of certain systems that
665 modifies sys.displayhook, it breaks the behavior of certain systems that
666 rely on the default behavior, notably doctest.
666 rely on the default behavior, notably doctest.
667 """
667 """
668
668
669 def f(*a,**k):
669 def f(*a,**k):
670
670
671 dhook_s = sys.displayhook
671 dhook_s = sys.displayhook
672 sys.displayhook = sys.__displayhook__
672 sys.displayhook = sys.__displayhook__
673 try:
673 try:
674 out = func(*a,**k)
674 out = func(*a,**k)
675 finally:
675 finally:
676 sys.displayhook = dhook_s
676 sys.displayhook = dhook_s
677
677
678 return out
678 return out
679
679
680 f.__doc__ = func.__doc__
680 f.__doc__ = func.__doc__
681 return f
681 return f
682
682
683 #----------------------------------------------------------------------------
683 #----------------------------------------------------------------------------
684 def doctest_reload():
684 def doctest_reload():
685 """Properly reload doctest to reuse it interactively.
685 """Properly reload doctest to reuse it interactively.
686
686
687 This routine:
687 This routine:
688
688
689 - imports doctest but does NOT reload it (see below).
689 - imports doctest but does NOT reload it (see below).
690
690
691 - resets its global 'master' attribute to None, so that multiple uses of
691 - resets its global 'master' attribute to None, so that multiple uses of
692 the module interactively don't produce cumulative reports.
692 the module interactively don't produce cumulative reports.
693
693
694 - Monkeypatches its core test runner method to protect it from IPython's
694 - Monkeypatches its core test runner method to protect it from IPython's
695 modified displayhook. Doctest expects the default displayhook behavior
695 modified displayhook. Doctest expects the default displayhook behavior
696 deep down, so our modification breaks it completely. For this reason, a
696 deep down, so our modification breaks it completely. For this reason, a
697 hard monkeypatch seems like a reasonable solution rather than asking
697 hard monkeypatch seems like a reasonable solution rather than asking
698 users to manually use a different doctest runner when under IPython.
698 users to manually use a different doctest runner when under IPython.
699
699
700 Notes
700 Notes
701 -----
701 -----
702
702
703 This function *used to* reload doctest, but this has been disabled because
703 This function *used to* reload doctest, but this has been disabled because
704 reloading doctest unconditionally can cause massive breakage of other
704 reloading doctest unconditionally can cause massive breakage of other
705 doctest-dependent modules already in memory, such as those for IPython's
705 doctest-dependent modules already in memory, such as those for IPython's
706 own testing system. The name wasn't changed to avoid breaking people's
706 own testing system. The name wasn't changed to avoid breaking people's
707 code, but the reload call isn't actually made anymore."""
707 code, but the reload call isn't actually made anymore."""
708
708
709 import doctest
709 import doctest
710 doctest.master = None
710 doctest.master = None
711 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
711 doctest.DocTestRunner.run = dhook_wrap(doctest.DocTestRunner.run)
712
712
713 #----------------------------------------------------------------------------
713 #----------------------------------------------------------------------------
714 class HomeDirError(Error):
714 class HomeDirError(Error):
715 pass
715 pass
716
716
717 def get_home_dir():
717 def get_home_dir():
718 """Return the closest possible equivalent to a 'home' directory.
718 """Return the closest possible equivalent to a 'home' directory.
719
719
720 * On POSIX, we try $HOME.
720 * On POSIX, we try $HOME.
721 * On Windows we try:
721 * On Windows we try:
722 - %HOMESHARE%
722 - %HOMESHARE%
723 - %HOMEDRIVE\%HOMEPATH%
723 - %HOMEDRIVE\%HOMEPATH%
724 - %USERPROFILE%
724 - %USERPROFILE%
725 - Registry hack
725 - Registry hack
726 * On Dos C:\
726 * On Dos C:\
727
727
728 Currently only Posix and NT are implemented, a HomeDirError exception is
728 Currently only Posix and NT are implemented, a HomeDirError exception is
729 raised for all other OSes.
729 raised for all other OSes.
730 """
730 """
731
731
732 isdir = os.path.isdir
732 isdir = os.path.isdir
733 env = os.environ
733 env = os.environ
734
734
735 # first, check py2exe distribution root directory for _ipython.
735 # first, check py2exe distribution root directory for _ipython.
736 # This overrides all. Normally does not exist.
736 # This overrides all. Normally does not exist.
737
737
738 if hasattr(sys, "frozen"): #Is frozen by py2exe
738 if hasattr(sys, "frozen"): #Is frozen by py2exe
739 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
739 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
740 root, rest = IPython.__file__.lower().split('library.zip')
740 root, rest = IPython.__file__.lower().split('library.zip')
741 else:
741 else:
742 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
742 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
743 root=os.path.abspath(root).rstrip('\\')
743 root=os.path.abspath(root).rstrip('\\')
744 if isdir(os.path.join(root, '_ipython')):
744 if isdir(os.path.join(root, '_ipython')):
745 os.environ["IPYKITROOT"] = root
745 os.environ["IPYKITROOT"] = root
746 return root.decode(sys.getfilesystemencoding())
746 return root.decode(sys.getfilesystemencoding())
747
747
748 if os.name == 'posix':
748 if os.name == 'posix':
749 # Linux, Unix, AIX, OS X
749 # Linux, Unix, AIX, OS X
750 try:
750 try:
751 homedir = env['HOME']
751 homedir = env['HOME']
752 except KeyError:
752 except KeyError:
753 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
753 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
754 else:
754 else:
755 return homedir.decode(sys.getfilesystemencoding())
755 return homedir.decode(sys.getfilesystemencoding())
756 elif os.name == 'nt':
756 elif os.name == 'nt':
757 # Now for win9x, XP, Vista, 7?
757 # Now for win9x, XP, Vista, 7?
758 # For some strange reason all of these return 'nt' for os.name.
758 # For some strange reason all of these return 'nt' for os.name.
759 # First look for a network home directory. This will return the UNC
759 # First look for a network home directory. This will return the UNC
760 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
760 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
761 # is needed when running IPython on cluster where all paths have to
761 # is needed when running IPython on cluster where all paths have to
762 # be UNC.
762 # be UNC.
763 try:
763 try:
764 homedir = env['HOMESHARE']
764 homedir = env['HOMESHARE']
765 except KeyError:
765 except KeyError:
766 pass
766 pass
767 else:
767 else:
768 if isdir(homedir):
768 if isdir(homedir):
769 return homedir.decode(sys.getfilesystemencoding())
769 return homedir.decode(sys.getfilesystemencoding())
770
770
771 # Now look for a local home directory
771 # Now look for a local home directory
772 try:
772 try:
773 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
773 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
774 except KeyError:
774 except KeyError:
775 pass
775 pass
776 else:
776 else:
777 if isdir(homedir):
777 if isdir(homedir):
778 return homedir.decode(sys.getfilesystemencoding())
778 return homedir.decode(sys.getfilesystemencoding())
779
779
780 # Now the users profile directory
780 # Now the users profile directory
781 try:
781 try:
782 homedir = os.path.join(env['USERPROFILE'])
782 homedir = os.path.join(env['USERPROFILE'])
783 except KeyError:
783 except KeyError:
784 pass
784 pass
785 else:
785 else:
786 if isdir(homedir):
786 if isdir(homedir):
787 return homedir.decode(sys.getfilesystemencoding())
787 return homedir.decode(sys.getfilesystemencoding())
788
788
789 # Use the registry to get the 'My Documents' folder.
789 # Use the registry to get the 'My Documents' folder.
790 try:
790 try:
791 import _winreg as wreg
791 import _winreg as wreg
792 key = wreg.OpenKey(
792 key = wreg.OpenKey(
793 wreg.HKEY_CURRENT_USER,
793 wreg.HKEY_CURRENT_USER,
794 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
794 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
795 )
795 )
796 homedir = wreg.QueryValueEx(key,'Personal')[0]
796 homedir = wreg.QueryValueEx(key,'Personal')[0]
797 key.Close()
797 key.Close()
798 except:
798 except:
799 pass
799 pass
800 else:
800 else:
801 if isdir(homedir):
801 if isdir(homedir):
802 return homedir.decode(sys.getfilesystemencoding())
802 return homedir.decode(sys.getfilesystemencoding())
803
803
804 # If all else fails, raise HomeDirError
804 # If all else fails, raise HomeDirError
805 raise HomeDirError('No valid home directory could be found')
805 raise HomeDirError('No valid home directory could be found')
806 elif os.name == 'dos':
806 elif os.name == 'dos':
807 # Desperate, may do absurd things in classic MacOS. May work under DOS.
807 # Desperate, may do absurd things in classic MacOS. May work under DOS.
808 return 'C:\\'.decode(sys.getfilesystemencoding())
808 return 'C:\\'.decode(sys.getfilesystemencoding())
809 else:
809 else:
810 raise HomeDirError('No valid home directory could be found for your OS')
810 raise HomeDirError('No valid home directory could be found for your OS')
811
811
812
812
813 def get_ipython_dir():
813 def get_ipython_dir():
814 """Get the IPython directory for this platform and user.
814 """Get the IPython directory for this platform and user.
815
815
816 This uses the logic in `get_home_dir` to find the home directory
816 This uses the logic in `get_home_dir` to find the home directory
817 and the adds .ipython to the end of the path.
817 and the adds .ipython to the end of the path.
818 """
818 """
819 ipdir_def = '.ipython'
819 ipdir_def = '.ipython'
820 home_dir = get_home_dir()
820 home_dir = get_home_dir()
821 ipdir = os.path.abspath(os.environ.get('IPYTHONDIR',
821 ipdir = os.environ.get(
822 os.path.join(home_dir, ipdir_def)))
822 'IPYTHON_DIR', os.environ.get(
823 'IPYTHONDIR', os.path.join(home_dir, ipdir_def)
824 )
825 )
823 return ipdir.decode(sys.getfilesystemencoding())
826 return ipdir.decode(sys.getfilesystemencoding())
824
827
825
828
826 #****************************************************************************
829 #****************************************************************************
827 # strings and text
830 # strings and text
828
831
829 class LSString(str):
832 class LSString(str):
830 """String derivative with a special access attributes.
833 """String derivative with a special access attributes.
831
834
832 These are normal strings, but with the special attributes:
835 These are normal strings, but with the special attributes:
833
836
834 .l (or .list) : value as list (split on newlines).
837 .l (or .list) : value as list (split on newlines).
835 .n (or .nlstr): original value (the string itself).
838 .n (or .nlstr): original value (the string itself).
836 .s (or .spstr): value as whitespace-separated string.
839 .s (or .spstr): value as whitespace-separated string.
837 .p (or .paths): list of path objects
840 .p (or .paths): list of path objects
838
841
839 Any values which require transformations are computed only once and
842 Any values which require transformations are computed only once and
840 cached.
843 cached.
841
844
842 Such strings are very useful to efficiently interact with the shell, which
845 Such strings are very useful to efficiently interact with the shell, which
843 typically only understands whitespace-separated options for commands."""
846 typically only understands whitespace-separated options for commands."""
844
847
845 def get_list(self):
848 def get_list(self):
846 try:
849 try:
847 return self.__list
850 return self.__list
848 except AttributeError:
851 except AttributeError:
849 self.__list = self.split('\n')
852 self.__list = self.split('\n')
850 return self.__list
853 return self.__list
851
854
852 l = list = property(get_list)
855 l = list = property(get_list)
853
856
854 def get_spstr(self):
857 def get_spstr(self):
855 try:
858 try:
856 return self.__spstr
859 return self.__spstr
857 except AttributeError:
860 except AttributeError:
858 self.__spstr = self.replace('\n',' ')
861 self.__spstr = self.replace('\n',' ')
859 return self.__spstr
862 return self.__spstr
860
863
861 s = spstr = property(get_spstr)
864 s = spstr = property(get_spstr)
862
865
863 def get_nlstr(self):
866 def get_nlstr(self):
864 return self
867 return self
865
868
866 n = nlstr = property(get_nlstr)
869 n = nlstr = property(get_nlstr)
867
870
868 def get_paths(self):
871 def get_paths(self):
869 try:
872 try:
870 return self.__paths
873 return self.__paths
871 except AttributeError:
874 except AttributeError:
872 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
875 self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)]
873 return self.__paths
876 return self.__paths
874
877
875 p = paths = property(get_paths)
878 p = paths = property(get_paths)
876
879
877 def print_lsstring(arg):
880 def print_lsstring(arg):
878 """ Prettier (non-repr-like) and more informative printer for LSString """
881 """ Prettier (non-repr-like) and more informative printer for LSString """
879 print "LSString (.p, .n, .l, .s available). Value:"
882 print "LSString (.p, .n, .l, .s available). Value:"
880 print arg
883 print arg
881
884
882 print_lsstring = result_display.when_type(LSString)(print_lsstring)
885 print_lsstring = result_display.when_type(LSString)(print_lsstring)
883
886
884 #----------------------------------------------------------------------------
887 #----------------------------------------------------------------------------
885 class SList(list):
888 class SList(list):
886 """List derivative with a special access attributes.
889 """List derivative with a special access attributes.
887
890
888 These are normal lists, but with the special attributes:
891 These are normal lists, but with the special attributes:
889
892
890 .l (or .list) : value as list (the list itself).
893 .l (or .list) : value as list (the list itself).
891 .n (or .nlstr): value as a string, joined on newlines.
894 .n (or .nlstr): value as a string, joined on newlines.
892 .s (or .spstr): value as a string, joined on spaces.
895 .s (or .spstr): value as a string, joined on spaces.
893 .p (or .paths): list of path objects
896 .p (or .paths): list of path objects
894
897
895 Any values which require transformations are computed only once and
898 Any values which require transformations are computed only once and
896 cached."""
899 cached."""
897
900
898 def get_list(self):
901 def get_list(self):
899 return self
902 return self
900
903
901 l = list = property(get_list)
904 l = list = property(get_list)
902
905
903 def get_spstr(self):
906 def get_spstr(self):
904 try:
907 try:
905 return self.__spstr
908 return self.__spstr
906 except AttributeError:
909 except AttributeError:
907 self.__spstr = ' '.join(self)
910 self.__spstr = ' '.join(self)
908 return self.__spstr
911 return self.__spstr
909
912
910 s = spstr = property(get_spstr)
913 s = spstr = property(get_spstr)
911
914
912 def get_nlstr(self):
915 def get_nlstr(self):
913 try:
916 try:
914 return self.__nlstr
917 return self.__nlstr
915 except AttributeError:
918 except AttributeError:
916 self.__nlstr = '\n'.join(self)
919 self.__nlstr = '\n'.join(self)
917 return self.__nlstr
920 return self.__nlstr
918
921
919 n = nlstr = property(get_nlstr)
922 n = nlstr = property(get_nlstr)
920
923
921 def get_paths(self):
924 def get_paths(self):
922 try:
925 try:
923 return self.__paths
926 return self.__paths
924 except AttributeError:
927 except AttributeError:
925 self.__paths = [path(p) for p in self if os.path.exists(p)]
928 self.__paths = [path(p) for p in self if os.path.exists(p)]
926 return self.__paths
929 return self.__paths
927
930
928 p = paths = property(get_paths)
931 p = paths = property(get_paths)
929
932
930 def grep(self, pattern, prune = False, field = None):
933 def grep(self, pattern, prune = False, field = None):
931 """ Return all strings matching 'pattern' (a regex or callable)
934 """ Return all strings matching 'pattern' (a regex or callable)
932
935
933 This is case-insensitive. If prune is true, return all items
936 This is case-insensitive. If prune is true, return all items
934 NOT matching the pattern.
937 NOT matching the pattern.
935
938
936 If field is specified, the match must occur in the specified
939 If field is specified, the match must occur in the specified
937 whitespace-separated field.
940 whitespace-separated field.
938
941
939 Examples::
942 Examples::
940
943
941 a.grep( lambda x: x.startswith('C') )
944 a.grep( lambda x: x.startswith('C') )
942 a.grep('Cha.*log', prune=1)
945 a.grep('Cha.*log', prune=1)
943 a.grep('chm', field=-1)
946 a.grep('chm', field=-1)
944 """
947 """
945
948
946 def match_target(s):
949 def match_target(s):
947 if field is None:
950 if field is None:
948 return s
951 return s
949 parts = s.split()
952 parts = s.split()
950 try:
953 try:
951 tgt = parts[field]
954 tgt = parts[field]
952 return tgt
955 return tgt
953 except IndexError:
956 except IndexError:
954 return ""
957 return ""
955
958
956 if isinstance(pattern, basestring):
959 if isinstance(pattern, basestring):
957 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
960 pred = lambda x : re.search(pattern, x, re.IGNORECASE)
958 else:
961 else:
959 pred = pattern
962 pred = pattern
960 if not prune:
963 if not prune:
961 return SList([el for el in self if pred(match_target(el))])
964 return SList([el for el in self if pred(match_target(el))])
962 else:
965 else:
963 return SList([el for el in self if not pred(match_target(el))])
966 return SList([el for el in self if not pred(match_target(el))])
964 def fields(self, *fields):
967 def fields(self, *fields):
965 """ Collect whitespace-separated fields from string list
968 """ Collect whitespace-separated fields from string list
966
969
967 Allows quick awk-like usage of string lists.
970 Allows quick awk-like usage of string lists.
968
971
969 Example data (in var a, created by 'a = !ls -l')::
972 Example data (in var a, created by 'a = !ls -l')::
970 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
973 -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog
971 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
974 drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython
972
975
973 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
976 a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+']
974 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
977 a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+']
975 (note the joining by space).
978 (note the joining by space).
976 a.fields(-1) is ['ChangeLog', 'IPython']
979 a.fields(-1) is ['ChangeLog', 'IPython']
977
980
978 IndexErrors are ignored.
981 IndexErrors are ignored.
979
982
980 Without args, fields() just split()'s the strings.
983 Without args, fields() just split()'s the strings.
981 """
984 """
982 if len(fields) == 0:
985 if len(fields) == 0:
983 return [el.split() for el in self]
986 return [el.split() for el in self]
984
987
985 res = SList()
988 res = SList()
986 for el in [f.split() for f in self]:
989 for el in [f.split() for f in self]:
987 lineparts = []
990 lineparts = []
988
991
989 for fd in fields:
992 for fd in fields:
990 try:
993 try:
991 lineparts.append(el[fd])
994 lineparts.append(el[fd])
992 except IndexError:
995 except IndexError:
993 pass
996 pass
994 if lineparts:
997 if lineparts:
995 res.append(" ".join(lineparts))
998 res.append(" ".join(lineparts))
996
999
997 return res
1000 return res
998 def sort(self,field= None, nums = False):
1001 def sort(self,field= None, nums = False):
999 """ sort by specified fields (see fields())
1002 """ sort by specified fields (see fields())
1000
1003
1001 Example::
1004 Example::
1002 a.sort(1, nums = True)
1005 a.sort(1, nums = True)
1003
1006
1004 Sorts a by second field, in numerical order (so that 21 > 3)
1007 Sorts a by second field, in numerical order (so that 21 > 3)
1005
1008
1006 """
1009 """
1007
1010
1008 #decorate, sort, undecorate
1011 #decorate, sort, undecorate
1009 if field is not None:
1012 if field is not None:
1010 dsu = [[SList([line]).fields(field), line] for line in self]
1013 dsu = [[SList([line]).fields(field), line] for line in self]
1011 else:
1014 else:
1012 dsu = [[line, line] for line in self]
1015 dsu = [[line, line] for line in self]
1013 if nums:
1016 if nums:
1014 for i in range(len(dsu)):
1017 for i in range(len(dsu)):
1015 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
1018 numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()])
1016 try:
1019 try:
1017 n = int(numstr)
1020 n = int(numstr)
1018 except ValueError:
1021 except ValueError:
1019 n = 0;
1022 n = 0;
1020 dsu[i][0] = n
1023 dsu[i][0] = n
1021
1024
1022
1025
1023 dsu.sort()
1026 dsu.sort()
1024 return SList([t[1] for t in dsu])
1027 return SList([t[1] for t in dsu])
1025
1028
1026 def print_slist(arg):
1029 def print_slist(arg):
1027 """ Prettier (non-repr-like) and more informative printer for SList """
1030 """ Prettier (non-repr-like) and more informative printer for SList """
1028 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
1031 print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):"
1029 if hasattr(arg, 'hideonce') and arg.hideonce:
1032 if hasattr(arg, 'hideonce') and arg.hideonce:
1030 arg.hideonce = False
1033 arg.hideonce = False
1031 return
1034 return
1032
1035
1033 nlprint(arg)
1036 nlprint(arg)
1034
1037
1035 print_slist = result_display.when_type(SList)(print_slist)
1038 print_slist = result_display.when_type(SList)(print_slist)
1036
1039
1037
1040
1038
1041
1039 #----------------------------------------------------------------------------
1042 #----------------------------------------------------------------------------
1040 def esc_quotes(strng):
1043 def esc_quotes(strng):
1041 """Return the input string with single and double quotes escaped out"""
1044 """Return the input string with single and double quotes escaped out"""
1042
1045
1043 return strng.replace('"','\\"').replace("'","\\'")
1046 return strng.replace('"','\\"').replace("'","\\'")
1044
1047
1045 #----------------------------------------------------------------------------
1048 #----------------------------------------------------------------------------
1046 def make_quoted_expr(s):
1049 def make_quoted_expr(s):
1047 """Return string s in appropriate quotes, using raw string if possible.
1050 """Return string s in appropriate quotes, using raw string if possible.
1048
1051
1049 XXX - example removed because it caused encoding errors in documentation
1052 XXX - example removed because it caused encoding errors in documentation
1050 generation. We need a new example that doesn't contain invalid chars.
1053 generation. We need a new example that doesn't contain invalid chars.
1051
1054
1052 Note the use of raw string and padding at the end to allow trailing
1055 Note the use of raw string and padding at the end to allow trailing
1053 backslash.
1056 backslash.
1054 """
1057 """
1055
1058
1056 tail = ''
1059 tail = ''
1057 tailpadding = ''
1060 tailpadding = ''
1058 raw = ''
1061 raw = ''
1059 if "\\" in s:
1062 if "\\" in s:
1060 raw = 'r'
1063 raw = 'r'
1061 if s.endswith('\\'):
1064 if s.endswith('\\'):
1062 tail = '[:-1]'
1065 tail = '[:-1]'
1063 tailpadding = '_'
1066 tailpadding = '_'
1064 if '"' not in s:
1067 if '"' not in s:
1065 quote = '"'
1068 quote = '"'
1066 elif "'" not in s:
1069 elif "'" not in s:
1067 quote = "'"
1070 quote = "'"
1068 elif '"""' not in s and not s.endswith('"'):
1071 elif '"""' not in s and not s.endswith('"'):
1069 quote = '"""'
1072 quote = '"""'
1070 elif "'''" not in s and not s.endswith("'"):
1073 elif "'''" not in s and not s.endswith("'"):
1071 quote = "'''"
1074 quote = "'''"
1072 else:
1075 else:
1073 # give up, backslash-escaped string will do
1076 # give up, backslash-escaped string will do
1074 return '"%s"' % esc_quotes(s)
1077 return '"%s"' % esc_quotes(s)
1075 res = raw + quote + s + tailpadding + quote + tail
1078 res = raw + quote + s + tailpadding + quote + tail
1076 return res
1079 return res
1077
1080
1078
1081
1079 #----------------------------------------------------------------------------
1082 #----------------------------------------------------------------------------
1080 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1083 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
1081 """Take multiple lines of input.
1084 """Take multiple lines of input.
1082
1085
1083 A list with each line of input as a separate element is returned when a
1086 A list with each line of input as a separate element is returned when a
1084 termination string is entered (defaults to a single '.'). Input can also
1087 termination string is entered (defaults to a single '.'). Input can also
1085 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1088 terminate via EOF (^D in Unix, ^Z-RET in Windows).
1086
1089
1087 Lines of input which end in \\ are joined into single entries (and a
1090 Lines of input which end in \\ are joined into single entries (and a
1088 secondary continuation prompt is issued as long as the user terminates
1091 secondary continuation prompt is issued as long as the user terminates
1089 lines with \\). This allows entering very long strings which are still
1092 lines with \\). This allows entering very long strings which are still
1090 meant to be treated as single entities.
1093 meant to be treated as single entities.
1091 """
1094 """
1092
1095
1093 try:
1096 try:
1094 if header:
1097 if header:
1095 header += '\n'
1098 header += '\n'
1096 lines = [raw_input(header + ps1)]
1099 lines = [raw_input(header + ps1)]
1097 except EOFError:
1100 except EOFError:
1098 return []
1101 return []
1099 terminate = [terminate_str]
1102 terminate = [terminate_str]
1100 try:
1103 try:
1101 while lines[-1:] != terminate:
1104 while lines[-1:] != terminate:
1102 new_line = raw_input(ps1)
1105 new_line = raw_input(ps1)
1103 while new_line.endswith('\\'):
1106 while new_line.endswith('\\'):
1104 new_line = new_line[:-1] + raw_input(ps2)
1107 new_line = new_line[:-1] + raw_input(ps2)
1105 lines.append(new_line)
1108 lines.append(new_line)
1106
1109
1107 return lines[:-1] # don't return the termination command
1110 return lines[:-1] # don't return the termination command
1108 except EOFError:
1111 except EOFError:
1109 print
1112 print
1110 return lines
1113 return lines
1111
1114
1112 #----------------------------------------------------------------------------
1115 #----------------------------------------------------------------------------
1113 def raw_input_ext(prompt='', ps2='... '):
1116 def raw_input_ext(prompt='', ps2='... '):
1114 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1117 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1115
1118
1116 line = raw_input(prompt)
1119 line = raw_input(prompt)
1117 while line.endswith('\\'):
1120 while line.endswith('\\'):
1118 line = line[:-1] + raw_input(ps2)
1121 line = line[:-1] + raw_input(ps2)
1119 return line
1122 return line
1120
1123
1121 #----------------------------------------------------------------------------
1124 #----------------------------------------------------------------------------
1122 def ask_yes_no(prompt,default=None):
1125 def ask_yes_no(prompt,default=None):
1123 """Asks a question and returns a boolean (y/n) answer.
1126 """Asks a question and returns a boolean (y/n) answer.
1124
1127
1125 If default is given (one of 'y','n'), it is used if the user input is
1128 If default is given (one of 'y','n'), it is used if the user input is
1126 empty. Otherwise the question is repeated until an answer is given.
1129 empty. Otherwise the question is repeated until an answer is given.
1127
1130
1128 An EOF is treated as the default answer. If there is no default, an
1131 An EOF is treated as the default answer. If there is no default, an
1129 exception is raised to prevent infinite loops.
1132 exception is raised to prevent infinite loops.
1130
1133
1131 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1134 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1132
1135
1133 answers = {'y':True,'n':False,'yes':True,'no':False}
1136 answers = {'y':True,'n':False,'yes':True,'no':False}
1134 ans = None
1137 ans = None
1135 while ans not in answers.keys():
1138 while ans not in answers.keys():
1136 try:
1139 try:
1137 ans = raw_input(prompt+' ').lower()
1140 ans = raw_input(prompt+' ').lower()
1138 if not ans: # response was an empty string
1141 if not ans: # response was an empty string
1139 ans = default
1142 ans = default
1140 except KeyboardInterrupt:
1143 except KeyboardInterrupt:
1141 pass
1144 pass
1142 except EOFError:
1145 except EOFError:
1143 if default in answers.keys():
1146 if default in answers.keys():
1144 ans = default
1147 ans = default
1145 print
1148 print
1146 else:
1149 else:
1147 raise
1150 raise
1148
1151
1149 return answers[ans]
1152 return answers[ans]
1150
1153
1151 #----------------------------------------------------------------------------
1154 #----------------------------------------------------------------------------
1152 class EvalDict:
1155 class EvalDict:
1153 """
1156 """
1154 Emulate a dict which evaluates its contents in the caller's frame.
1157 Emulate a dict which evaluates its contents in the caller's frame.
1155
1158
1156 Usage:
1159 Usage:
1157 >>> number = 19
1160 >>> number = 19
1158
1161
1159 >>> text = "python"
1162 >>> text = "python"
1160
1163
1161 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1164 >>> print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1162 Python 2.1 rules!
1165 Python 2.1 rules!
1163 """
1166 """
1164
1167
1165 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1168 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1166 # modified (shorter) version of:
1169 # modified (shorter) version of:
1167 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1170 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1168 # Skip Montanaro (skip@pobox.com).
1171 # Skip Montanaro (skip@pobox.com).
1169
1172
1170 def __getitem__(self, name):
1173 def __getitem__(self, name):
1171 frame = sys._getframe(1)
1174 frame = sys._getframe(1)
1172 return eval(name, frame.f_globals, frame.f_locals)
1175 return eval(name, frame.f_globals, frame.f_locals)
1173
1176
1174 EvalString = EvalDict # for backwards compatibility
1177 EvalString = EvalDict # for backwards compatibility
1175 #----------------------------------------------------------------------------
1178 #----------------------------------------------------------------------------
1176 def qw(words,flat=0,sep=None,maxsplit=-1):
1179 def qw(words,flat=0,sep=None,maxsplit=-1):
1177 """Similar to Perl's qw() operator, but with some more options.
1180 """Similar to Perl's qw() operator, but with some more options.
1178
1181
1179 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1182 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1180
1183
1181 words can also be a list itself, and with flat=1, the output will be
1184 words can also be a list itself, and with flat=1, the output will be
1182 recursively flattened.
1185 recursively flattened.
1183
1186
1184 Examples:
1187 Examples:
1185
1188
1186 >>> qw('1 2')
1189 >>> qw('1 2')
1187 ['1', '2']
1190 ['1', '2']
1188
1191
1189 >>> qw(['a b','1 2',['m n','p q']])
1192 >>> qw(['a b','1 2',['m n','p q']])
1190 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1193 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1191
1194
1192 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1195 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1193 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1196 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q']
1194 """
1197 """
1195
1198
1196 if type(words) in StringTypes:
1199 if type(words) in StringTypes:
1197 return [word.strip() for word in words.split(sep,maxsplit)
1200 return [word.strip() for word in words.split(sep,maxsplit)
1198 if word and not word.isspace() ]
1201 if word and not word.isspace() ]
1199 if flat:
1202 if flat:
1200 return flatten(map(qw,words,[1]*len(words)))
1203 return flatten(map(qw,words,[1]*len(words)))
1201 return map(qw,words)
1204 return map(qw,words)
1202
1205
1203 #----------------------------------------------------------------------------
1206 #----------------------------------------------------------------------------
1204 def qwflat(words,sep=None,maxsplit=-1):
1207 def qwflat(words,sep=None,maxsplit=-1):
1205 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1208 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1206 return qw(words,1,sep,maxsplit)
1209 return qw(words,1,sep,maxsplit)
1207
1210
1208 #----------------------------------------------------------------------------
1211 #----------------------------------------------------------------------------
1209 def qw_lol(indata):
1212 def qw_lol(indata):
1210 """qw_lol('a b') -> [['a','b']],
1213 """qw_lol('a b') -> [['a','b']],
1211 otherwise it's just a call to qw().
1214 otherwise it's just a call to qw().
1212
1215
1213 We need this to make sure the modules_some keys *always* end up as a
1216 We need this to make sure the modules_some keys *always* end up as a
1214 list of lists."""
1217 list of lists."""
1215
1218
1216 if type(indata) in StringTypes:
1219 if type(indata) in StringTypes:
1217 return [qw(indata)]
1220 return [qw(indata)]
1218 else:
1221 else:
1219 return qw(indata)
1222 return qw(indata)
1220
1223
1221 #----------------------------------------------------------------------------
1224 #----------------------------------------------------------------------------
1222 def grep(pat,list,case=1):
1225 def grep(pat,list,case=1):
1223 """Simple minded grep-like function.
1226 """Simple minded grep-like function.
1224 grep(pat,list) returns occurrences of pat in list, None on failure.
1227 grep(pat,list) returns occurrences of pat in list, None on failure.
1225
1228
1226 It only does simple string matching, with no support for regexps. Use the
1229 It only does simple string matching, with no support for regexps. Use the
1227 option case=0 for case-insensitive matching."""
1230 option case=0 for case-insensitive matching."""
1228
1231
1229 # This is pretty crude. At least it should implement copying only references
1232 # This is pretty crude. At least it should implement copying only references
1230 # to the original data in case it's big. Now it copies the data for output.
1233 # to the original data in case it's big. Now it copies the data for output.
1231 out=[]
1234 out=[]
1232 if case:
1235 if case:
1233 for term in list:
1236 for term in list:
1234 if term.find(pat)>-1: out.append(term)
1237 if term.find(pat)>-1: out.append(term)
1235 else:
1238 else:
1236 lpat=pat.lower()
1239 lpat=pat.lower()
1237 for term in list:
1240 for term in list:
1238 if term.lower().find(lpat)>-1: out.append(term)
1241 if term.lower().find(lpat)>-1: out.append(term)
1239
1242
1240 if len(out): return out
1243 if len(out): return out
1241 else: return None
1244 else: return None
1242
1245
1243 #----------------------------------------------------------------------------
1246 #----------------------------------------------------------------------------
1244 def dgrep(pat,*opts):
1247 def dgrep(pat,*opts):
1245 """Return grep() on dir()+dir(__builtins__).
1248 """Return grep() on dir()+dir(__builtins__).
1246
1249
1247 A very common use of grep() when working interactively."""
1250 A very common use of grep() when working interactively."""
1248
1251
1249 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1252 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1250
1253
1251 #----------------------------------------------------------------------------
1254 #----------------------------------------------------------------------------
1252 def idgrep(pat):
1255 def idgrep(pat):
1253 """Case-insensitive dgrep()"""
1256 """Case-insensitive dgrep()"""
1254
1257
1255 return dgrep(pat,0)
1258 return dgrep(pat,0)
1256
1259
1257 #----------------------------------------------------------------------------
1260 #----------------------------------------------------------------------------
1258 def igrep(pat,list):
1261 def igrep(pat,list):
1259 """Synonym for case-insensitive grep."""
1262 """Synonym for case-insensitive grep."""
1260
1263
1261 return grep(pat,list,case=0)
1264 return grep(pat,list,case=0)
1262
1265
1263 #----------------------------------------------------------------------------
1266 #----------------------------------------------------------------------------
1264 def indent(str,nspaces=4,ntabs=0):
1267 def indent(str,nspaces=4,ntabs=0):
1265 """Indent a string a given number of spaces or tabstops.
1268 """Indent a string a given number of spaces or tabstops.
1266
1269
1267 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1270 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1268 """
1271 """
1269 if str is None:
1272 if str is None:
1270 return
1273 return
1271 ind = '\t'*ntabs+' '*nspaces
1274 ind = '\t'*ntabs+' '*nspaces
1272 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1275 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1273 if outstr.endswith(os.linesep+ind):
1276 if outstr.endswith(os.linesep+ind):
1274 return outstr[:-len(ind)]
1277 return outstr[:-len(ind)]
1275 else:
1278 else:
1276 return outstr
1279 return outstr
1277
1280
1278 #-----------------------------------------------------------------------------
1281 #-----------------------------------------------------------------------------
1279 def native_line_ends(filename,backup=1):
1282 def native_line_ends(filename,backup=1):
1280 """Convert (in-place) a file to line-ends native to the current OS.
1283 """Convert (in-place) a file to line-ends native to the current OS.
1281
1284
1282 If the optional backup argument is given as false, no backup of the
1285 If the optional backup argument is given as false, no backup of the
1283 original file is left. """
1286 original file is left. """
1284
1287
1285 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1288 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1286
1289
1287 bak_filename = filename + backup_suffixes[os.name]
1290 bak_filename = filename + backup_suffixes[os.name]
1288
1291
1289 original = open(filename).read()
1292 original = open(filename).read()
1290 shutil.copy2(filename,bak_filename)
1293 shutil.copy2(filename,bak_filename)
1291 try:
1294 try:
1292 new = open(filename,'wb')
1295 new = open(filename,'wb')
1293 new.write(os.linesep.join(original.splitlines()))
1296 new.write(os.linesep.join(original.splitlines()))
1294 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1297 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1295 new.close()
1298 new.close()
1296 except:
1299 except:
1297 os.rename(bak_filename,filename)
1300 os.rename(bak_filename,filename)
1298 if not backup:
1301 if not backup:
1299 try:
1302 try:
1300 os.remove(bak_filename)
1303 os.remove(bak_filename)
1301 except:
1304 except:
1302 pass
1305 pass
1303
1306
1304 #****************************************************************************
1307 #****************************************************************************
1305 # lists, dicts and structures
1308 # lists, dicts and structures
1306
1309
1307 def belong(candidates,checklist):
1310 def belong(candidates,checklist):
1308 """Check whether a list of items appear in a given list of options.
1311 """Check whether a list of items appear in a given list of options.
1309
1312
1310 Returns a list of 1 and 0, one for each candidate given."""
1313 Returns a list of 1 and 0, one for each candidate given."""
1311
1314
1312 return [x in checklist for x in candidates]
1315 return [x in checklist for x in candidates]
1313
1316
1314 #----------------------------------------------------------------------------
1317 #----------------------------------------------------------------------------
1315 def uniq_stable(elems):
1318 def uniq_stable(elems):
1316 """uniq_stable(elems) -> list
1319 """uniq_stable(elems) -> list
1317
1320
1318 Return from an iterable, a list of all the unique elements in the input,
1321 Return from an iterable, a list of all the unique elements in the input,
1319 but maintaining the order in which they first appear.
1322 but maintaining the order in which they first appear.
1320
1323
1321 A naive solution to this problem which just makes a dictionary with the
1324 A naive solution to this problem which just makes a dictionary with the
1322 elements as keys fails to respect the stability condition, since
1325 elements as keys fails to respect the stability condition, since
1323 dictionaries are unsorted by nature.
1326 dictionaries are unsorted by nature.
1324
1327
1325 Note: All elements in the input must be valid dictionary keys for this
1328 Note: All elements in the input must be valid dictionary keys for this
1326 routine to work, as it internally uses a dictionary for efficiency
1329 routine to work, as it internally uses a dictionary for efficiency
1327 reasons."""
1330 reasons."""
1328
1331
1329 unique = []
1332 unique = []
1330 unique_dict = {}
1333 unique_dict = {}
1331 for nn in elems:
1334 for nn in elems:
1332 if nn not in unique_dict:
1335 if nn not in unique_dict:
1333 unique.append(nn)
1336 unique.append(nn)
1334 unique_dict[nn] = None
1337 unique_dict[nn] = None
1335 return unique
1338 return unique
1336
1339
1337 #----------------------------------------------------------------------------
1340 #----------------------------------------------------------------------------
1338 class NLprinter:
1341 class NLprinter:
1339 """Print an arbitrarily nested list, indicating index numbers.
1342 """Print an arbitrarily nested list, indicating index numbers.
1340
1343
1341 An instance of this class called nlprint is available and callable as a
1344 An instance of this class called nlprint is available and callable as a
1342 function.
1345 function.
1343
1346
1344 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1347 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1345 and using 'sep' to separate the index from the value. """
1348 and using 'sep' to separate the index from the value. """
1346
1349
1347 def __init__(self):
1350 def __init__(self):
1348 self.depth = 0
1351 self.depth = 0
1349
1352
1350 def __call__(self,lst,pos='',**kw):
1353 def __call__(self,lst,pos='',**kw):
1351 """Prints the nested list numbering levels."""
1354 """Prints the nested list numbering levels."""
1352 kw.setdefault('indent',' ')
1355 kw.setdefault('indent',' ')
1353 kw.setdefault('sep',': ')
1356 kw.setdefault('sep',': ')
1354 kw.setdefault('start',0)
1357 kw.setdefault('start',0)
1355 kw.setdefault('stop',len(lst))
1358 kw.setdefault('stop',len(lst))
1356 # we need to remove start and stop from kw so they don't propagate
1359 # we need to remove start and stop from kw so they don't propagate
1357 # into a recursive call for a nested list.
1360 # into a recursive call for a nested list.
1358 start = kw['start']; del kw['start']
1361 start = kw['start']; del kw['start']
1359 stop = kw['stop']; del kw['stop']
1362 stop = kw['stop']; del kw['stop']
1360 if self.depth == 0 and 'header' in kw.keys():
1363 if self.depth == 0 and 'header' in kw.keys():
1361 print kw['header']
1364 print kw['header']
1362
1365
1363 for idx in range(start,stop):
1366 for idx in range(start,stop):
1364 elem = lst[idx]
1367 elem = lst[idx]
1365 if type(elem)==type([]):
1368 if type(elem)==type([]):
1366 self.depth += 1
1369 self.depth += 1
1367 self.__call__(elem,itpl('$pos$idx,'),**kw)
1370 self.__call__(elem,itpl('$pos$idx,'),**kw)
1368 self.depth -= 1
1371 self.depth -= 1
1369 else:
1372 else:
1370 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1373 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1371
1374
1372 nlprint = NLprinter()
1375 nlprint = NLprinter()
1373 #----------------------------------------------------------------------------
1376 #----------------------------------------------------------------------------
1374 def all_belong(candidates,checklist):
1377 def all_belong(candidates,checklist):
1375 """Check whether a list of items ALL appear in a given list of options.
1378 """Check whether a list of items ALL appear in a given list of options.
1376
1379
1377 Returns a single 1 or 0 value."""
1380 Returns a single 1 or 0 value."""
1378
1381
1379 return 1-(0 in [x in checklist for x in candidates])
1382 return 1-(0 in [x in checklist for x in candidates])
1380
1383
1381 #----------------------------------------------------------------------------
1384 #----------------------------------------------------------------------------
1382 def sort_compare(lst1,lst2,inplace = 1):
1385 def sort_compare(lst1,lst2,inplace = 1):
1383 """Sort and compare two lists.
1386 """Sort and compare two lists.
1384
1387
1385 By default it does it in place, thus modifying the lists. Use inplace = 0
1388 By default it does it in place, thus modifying the lists. Use inplace = 0
1386 to avoid that (at the cost of temporary copy creation)."""
1389 to avoid that (at the cost of temporary copy creation)."""
1387 if not inplace:
1390 if not inplace:
1388 lst1 = lst1[:]
1391 lst1 = lst1[:]
1389 lst2 = lst2[:]
1392 lst2 = lst2[:]
1390 lst1.sort(); lst2.sort()
1393 lst1.sort(); lst2.sort()
1391 return lst1 == lst2
1394 return lst1 == lst2
1392
1395
1393 #----------------------------------------------------------------------------
1396 #----------------------------------------------------------------------------
1394 def list2dict(lst):
1397 def list2dict(lst):
1395 """Takes a list of (key,value) pairs and turns it into a dict."""
1398 """Takes a list of (key,value) pairs and turns it into a dict."""
1396
1399
1397 dic = {}
1400 dic = {}
1398 for k,v in lst: dic[k] = v
1401 for k,v in lst: dic[k] = v
1399 return dic
1402 return dic
1400
1403
1401 #----------------------------------------------------------------------------
1404 #----------------------------------------------------------------------------
1402 def list2dict2(lst,default=''):
1405 def list2dict2(lst,default=''):
1403 """Takes a list and turns it into a dict.
1406 """Takes a list and turns it into a dict.
1404 Much slower than list2dict, but more versatile. This version can take
1407 Much slower than list2dict, but more versatile. This version can take
1405 lists with sublists of arbitrary length (including sclars)."""
1408 lists with sublists of arbitrary length (including sclars)."""
1406
1409
1407 dic = {}
1410 dic = {}
1408 for elem in lst:
1411 for elem in lst:
1409 if type(elem) in (types.ListType,types.TupleType):
1412 if type(elem) in (types.ListType,types.TupleType):
1410 size = len(elem)
1413 size = len(elem)
1411 if size == 0:
1414 if size == 0:
1412 pass
1415 pass
1413 elif size == 1:
1416 elif size == 1:
1414 dic[elem] = default
1417 dic[elem] = default
1415 else:
1418 else:
1416 k,v = elem[0], elem[1:]
1419 k,v = elem[0], elem[1:]
1417 if len(v) == 1: v = v[0]
1420 if len(v) == 1: v = v[0]
1418 dic[k] = v
1421 dic[k] = v
1419 else:
1422 else:
1420 dic[elem] = default
1423 dic[elem] = default
1421 return dic
1424 return dic
1422
1425
1423 #----------------------------------------------------------------------------
1426 #----------------------------------------------------------------------------
1424 def flatten(seq):
1427 def flatten(seq):
1425 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1428 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1426
1429
1427 return [x for subseq in seq for x in subseq]
1430 return [x for subseq in seq for x in subseq]
1428
1431
1429 #----------------------------------------------------------------------------
1432 #----------------------------------------------------------------------------
1430 def get_slice(seq,start=0,stop=None,step=1):
1433 def get_slice(seq,start=0,stop=None,step=1):
1431 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1434 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1432 if stop == None:
1435 if stop == None:
1433 stop = len(seq)
1436 stop = len(seq)
1434 item = lambda i: seq[i]
1437 item = lambda i: seq[i]
1435 return map(item,xrange(start,stop,step))
1438 return map(item,xrange(start,stop,step))
1436
1439
1437 #----------------------------------------------------------------------------
1440 #----------------------------------------------------------------------------
1438 def chop(seq,size):
1441 def chop(seq,size):
1439 """Chop a sequence into chunks of the given size."""
1442 """Chop a sequence into chunks of the given size."""
1440 chunk = lambda i: seq[i:i+size]
1443 chunk = lambda i: seq[i:i+size]
1441 return map(chunk,xrange(0,len(seq),size))
1444 return map(chunk,xrange(0,len(seq),size))
1442
1445
1443 #----------------------------------------------------------------------------
1446 #----------------------------------------------------------------------------
1444 # with is a keyword as of python 2.5, so this function is renamed to withobj
1447 # with is a keyword as of python 2.5, so this function is renamed to withobj
1445 # from its old 'with' name.
1448 # from its old 'with' name.
1446 def with_obj(object, **args):
1449 def with_obj(object, **args):
1447 """Set multiple attributes for an object, similar to Pascal's with.
1450 """Set multiple attributes for an object, similar to Pascal's with.
1448
1451
1449 Example:
1452 Example:
1450 with_obj(jim,
1453 with_obj(jim,
1451 born = 1960,
1454 born = 1960,
1452 haircolour = 'Brown',
1455 haircolour = 'Brown',
1453 eyecolour = 'Green')
1456 eyecolour = 'Green')
1454
1457
1455 Credit: Greg Ewing, in
1458 Credit: Greg Ewing, in
1456 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1459 http://mail.python.org/pipermail/python-list/2001-May/040703.html.
1457
1460
1458 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1461 NOTE: up until IPython 0.7.2, this was called simply 'with', but 'with'
1459 has become a keyword for Python 2.5, so we had to rename it."""
1462 has become a keyword for Python 2.5, so we had to rename it."""
1460
1463
1461 object.__dict__.update(args)
1464 object.__dict__.update(args)
1462
1465
1463 #----------------------------------------------------------------------------
1466 #----------------------------------------------------------------------------
1464 def setattr_list(obj,alist,nspace = None):
1467 def setattr_list(obj,alist,nspace = None):
1465 """Set a list of attributes for an object taken from a namespace.
1468 """Set a list of attributes for an object taken from a namespace.
1466
1469
1467 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1470 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1468 alist with their values taken from nspace, which must be a dict (something
1471 alist with their values taken from nspace, which must be a dict (something
1469 like locals() will often do) If nspace isn't given, locals() of the
1472 like locals() will often do) If nspace isn't given, locals() of the
1470 *caller* is used, so in most cases you can omit it.
1473 *caller* is used, so in most cases you can omit it.
1471
1474
1472 Note that alist can be given as a string, which will be automatically
1475 Note that alist can be given as a string, which will be automatically
1473 split into a list on whitespace. If given as a list, it must be a list of
1476 split into a list on whitespace. If given as a list, it must be a list of
1474 *strings* (the variable names themselves), not of variables."""
1477 *strings* (the variable names themselves), not of variables."""
1475
1478
1476 # this grabs the local variables from the *previous* call frame -- that is
1479 # this grabs the local variables from the *previous* call frame -- that is
1477 # the locals from the function that called setattr_list().
1480 # the locals from the function that called setattr_list().
1478 # - snipped from weave.inline()
1481 # - snipped from weave.inline()
1479 if nspace is None:
1482 if nspace is None:
1480 call_frame = sys._getframe().f_back
1483 call_frame = sys._getframe().f_back
1481 nspace = call_frame.f_locals
1484 nspace = call_frame.f_locals
1482
1485
1483 if type(alist) in StringTypes:
1486 if type(alist) in StringTypes:
1484 alist = alist.split()
1487 alist = alist.split()
1485 for attr in alist:
1488 for attr in alist:
1486 val = eval(attr,nspace)
1489 val = eval(attr,nspace)
1487 setattr(obj,attr,val)
1490 setattr(obj,attr,val)
1488
1491
1489 #----------------------------------------------------------------------------
1492 #----------------------------------------------------------------------------
1490 def getattr_list(obj,alist,*args):
1493 def getattr_list(obj,alist,*args):
1491 """getattr_list(obj,alist[, default]) -> attribute list.
1494 """getattr_list(obj,alist[, default]) -> attribute list.
1492
1495
1493 Get a list of named attributes for an object. When a default argument is
1496 Get a list of named attributes for an object. When a default argument is
1494 given, it is returned when the attribute doesn't exist; without it, an
1497 given, it is returned when the attribute doesn't exist; without it, an
1495 exception is raised in that case.
1498 exception is raised in that case.
1496
1499
1497 Note that alist can be given as a string, which will be automatically
1500 Note that alist can be given as a string, which will be automatically
1498 split into a list on whitespace. If given as a list, it must be a list of
1501 split into a list on whitespace. If given as a list, it must be a list of
1499 *strings* (the variable names themselves), not of variables."""
1502 *strings* (the variable names themselves), not of variables."""
1500
1503
1501 if type(alist) in StringTypes:
1504 if type(alist) in StringTypes:
1502 alist = alist.split()
1505 alist = alist.split()
1503 if args:
1506 if args:
1504 if len(args)==1:
1507 if len(args)==1:
1505 default = args[0]
1508 default = args[0]
1506 return map(lambda attr: getattr(obj,attr,default),alist)
1509 return map(lambda attr: getattr(obj,attr,default),alist)
1507 else:
1510 else:
1508 raise ValueError,'getattr_list() takes only one optional argument'
1511 raise ValueError,'getattr_list() takes only one optional argument'
1509 else:
1512 else:
1510 return map(lambda attr: getattr(obj,attr),alist)
1513 return map(lambda attr: getattr(obj,attr),alist)
1511
1514
1512 #----------------------------------------------------------------------------
1515 #----------------------------------------------------------------------------
1513 def map_method(method,object_list,*argseq,**kw):
1516 def map_method(method,object_list,*argseq,**kw):
1514 """map_method(method,object_list,*args,**kw) -> list
1517 """map_method(method,object_list,*args,**kw) -> list
1515
1518
1516 Return a list of the results of applying the methods to the items of the
1519 Return a list of the results of applying the methods to the items of the
1517 argument sequence(s). If more than one sequence is given, the method is
1520 argument sequence(s). If more than one sequence is given, the method is
1518 called with an argument list consisting of the corresponding item of each
1521 called with an argument list consisting of the corresponding item of each
1519 sequence. All sequences must be of the same length.
1522 sequence. All sequences must be of the same length.
1520
1523
1521 Keyword arguments are passed verbatim to all objects called.
1524 Keyword arguments are passed verbatim to all objects called.
1522
1525
1523 This is Python code, so it's not nearly as fast as the builtin map()."""
1526 This is Python code, so it's not nearly as fast as the builtin map()."""
1524
1527
1525 out_list = []
1528 out_list = []
1526 idx = 0
1529 idx = 0
1527 for object in object_list:
1530 for object in object_list:
1528 try:
1531 try:
1529 handler = getattr(object, method)
1532 handler = getattr(object, method)
1530 except AttributeError:
1533 except AttributeError:
1531 out_list.append(None)
1534 out_list.append(None)
1532 else:
1535 else:
1533 if argseq:
1536 if argseq:
1534 args = map(lambda lst:lst[idx],argseq)
1537 args = map(lambda lst:lst[idx],argseq)
1535 #print 'ob',object,'hand',handler,'ar',args # dbg
1538 #print 'ob',object,'hand',handler,'ar',args # dbg
1536 out_list.append(handler(args,**kw))
1539 out_list.append(handler(args,**kw))
1537 else:
1540 else:
1538 out_list.append(handler(**kw))
1541 out_list.append(handler(**kw))
1539 idx += 1
1542 idx += 1
1540 return out_list
1543 return out_list
1541
1544
1542 #----------------------------------------------------------------------------
1545 #----------------------------------------------------------------------------
1543 def get_class_members(cls):
1546 def get_class_members(cls):
1544 ret = dir(cls)
1547 ret = dir(cls)
1545 if hasattr(cls,'__bases__'):
1548 if hasattr(cls,'__bases__'):
1546 for base in cls.__bases__:
1549 for base in cls.__bases__:
1547 ret.extend(get_class_members(base))
1550 ret.extend(get_class_members(base))
1548 return ret
1551 return ret
1549
1552
1550 #----------------------------------------------------------------------------
1553 #----------------------------------------------------------------------------
1551 def dir2(obj):
1554 def dir2(obj):
1552 """dir2(obj) -> list of strings
1555 """dir2(obj) -> list of strings
1553
1556
1554 Extended version of the Python builtin dir(), which does a few extra
1557 Extended version of the Python builtin dir(), which does a few extra
1555 checks, and supports common objects with unusual internals that confuse
1558 checks, and supports common objects with unusual internals that confuse
1556 dir(), such as Traits and PyCrust.
1559 dir(), such as Traits and PyCrust.
1557
1560
1558 This version is guaranteed to return only a list of true strings, whereas
1561 This version is guaranteed to return only a list of true strings, whereas
1559 dir() returns anything that objects inject into themselves, even if they
1562 dir() returns anything that objects inject into themselves, even if they
1560 are later not really valid for attribute access (many extension libraries
1563 are later not really valid for attribute access (many extension libraries
1561 have such bugs).
1564 have such bugs).
1562 """
1565 """
1563
1566
1564 # Start building the attribute list via dir(), and then complete it
1567 # Start building the attribute list via dir(), and then complete it
1565 # with a few extra special-purpose calls.
1568 # with a few extra special-purpose calls.
1566 words = dir(obj)
1569 words = dir(obj)
1567
1570
1568 if hasattr(obj,'__class__'):
1571 if hasattr(obj,'__class__'):
1569 words.append('__class__')
1572 words.append('__class__')
1570 words.extend(get_class_members(obj.__class__))
1573 words.extend(get_class_members(obj.__class__))
1571 #if '__base__' in words: 1/0
1574 #if '__base__' in words: 1/0
1572
1575
1573 # Some libraries (such as traits) may introduce duplicates, we want to
1576 # Some libraries (such as traits) may introduce duplicates, we want to
1574 # track and clean this up if it happens
1577 # track and clean this up if it happens
1575 may_have_dupes = False
1578 may_have_dupes = False
1576
1579
1577 # this is the 'dir' function for objects with Enthought's traits
1580 # this is the 'dir' function for objects with Enthought's traits
1578 if hasattr(obj, 'trait_names'):
1581 if hasattr(obj, 'trait_names'):
1579 try:
1582 try:
1580 words.extend(obj.trait_names())
1583 words.extend(obj.trait_names())
1581 may_have_dupes = True
1584 may_have_dupes = True
1582 except TypeError:
1585 except TypeError:
1583 # This will happen if `obj` is a class and not an instance.
1586 # This will happen if `obj` is a class and not an instance.
1584 pass
1587 pass
1585
1588
1586 # Support for PyCrust-style _getAttributeNames magic method.
1589 # Support for PyCrust-style _getAttributeNames magic method.
1587 if hasattr(obj, '_getAttributeNames'):
1590 if hasattr(obj, '_getAttributeNames'):
1588 try:
1591 try:
1589 words.extend(obj._getAttributeNames())
1592 words.extend(obj._getAttributeNames())
1590 may_have_dupes = True
1593 may_have_dupes = True
1591 except TypeError:
1594 except TypeError:
1592 # `obj` is a class and not an instance. Ignore
1595 # `obj` is a class and not an instance. Ignore
1593 # this error.
1596 # this error.
1594 pass
1597 pass
1595
1598
1596 if may_have_dupes:
1599 if may_have_dupes:
1597 # eliminate possible duplicates, as some traits may also
1600 # eliminate possible duplicates, as some traits may also
1598 # appear as normal attributes in the dir() call.
1601 # appear as normal attributes in the dir() call.
1599 words = list(set(words))
1602 words = list(set(words))
1600 words.sort()
1603 words.sort()
1601
1604
1602 # filter out non-string attributes which may be stuffed by dir() calls
1605 # filter out non-string attributes which may be stuffed by dir() calls
1603 # and poor coding in third-party modules
1606 # and poor coding in third-party modules
1604 return [w for w in words if isinstance(w, basestring)]
1607 return [w for w in words if isinstance(w, basestring)]
1605
1608
1606 #----------------------------------------------------------------------------
1609 #----------------------------------------------------------------------------
1607 def import_fail_info(mod_name,fns=None):
1610 def import_fail_info(mod_name,fns=None):
1608 """Inform load failure for a module."""
1611 """Inform load failure for a module."""
1609
1612
1610 if fns == None:
1613 if fns == None:
1611 warn("Loading of %s failed.\n" % (mod_name,))
1614 warn("Loading of %s failed.\n" % (mod_name,))
1612 else:
1615 else:
1613 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1616 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1614
1617
1615 #----------------------------------------------------------------------------
1618 #----------------------------------------------------------------------------
1616 # Proposed popitem() extension, written as a method
1619 # Proposed popitem() extension, written as a method
1617
1620
1618
1621
1619 class NotGiven: pass
1622 class NotGiven: pass
1620
1623
1621 def popkey(dct,key,default=NotGiven):
1624 def popkey(dct,key,default=NotGiven):
1622 """Return dct[key] and delete dct[key].
1625 """Return dct[key] and delete dct[key].
1623
1626
1624 If default is given, return it if dct[key] doesn't exist, otherwise raise
1627 If default is given, return it if dct[key] doesn't exist, otherwise raise
1625 KeyError. """
1628 KeyError. """
1626
1629
1627 try:
1630 try:
1628 val = dct[key]
1631 val = dct[key]
1629 except KeyError:
1632 except KeyError:
1630 if default is NotGiven:
1633 if default is NotGiven:
1631 raise
1634 raise
1632 else:
1635 else:
1633 return default
1636 return default
1634 else:
1637 else:
1635 del dct[key]
1638 del dct[key]
1636 return val
1639 return val
1637
1640
1638 def wrap_deprecated(func, suggest = '<nothing>'):
1641 def wrap_deprecated(func, suggest = '<nothing>'):
1639 def newFunc(*args, **kwargs):
1642 def newFunc(*args, **kwargs):
1640 warnings.warn("Call to deprecated function %s, use %s instead" %
1643 warnings.warn("Call to deprecated function %s, use %s instead" %
1641 ( func.__name__, suggest),
1644 ( func.__name__, suggest),
1642 category=DeprecationWarning,
1645 category=DeprecationWarning,
1643 stacklevel = 2)
1646 stacklevel = 2)
1644 return func(*args, **kwargs)
1647 return func(*args, **kwargs)
1645 return newFunc
1648 return newFunc
1646
1649
1647
1650
1648 def _num_cpus_unix():
1651 def _num_cpus_unix():
1649 """Return the number of active CPUs on a Unix system."""
1652 """Return the number of active CPUs on a Unix system."""
1650 return os.sysconf("SC_NPROCESSORS_ONLN")
1653 return os.sysconf("SC_NPROCESSORS_ONLN")
1651
1654
1652
1655
1653 def _num_cpus_darwin():
1656 def _num_cpus_darwin():
1654 """Return the number of active CPUs on a Darwin system."""
1657 """Return the number of active CPUs on a Darwin system."""
1655 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
1658 p = subprocess.Popen(['sysctl','-n','hw.ncpu'],stdout=subprocess.PIPE)
1656 return p.stdout.read()
1659 return p.stdout.read()
1657
1660
1658
1661
1659 def _num_cpus_windows():
1662 def _num_cpus_windows():
1660 """Return the number of active CPUs on a Windows system."""
1663 """Return the number of active CPUs on a Windows system."""
1661 return os.environ.get("NUMBER_OF_PROCESSORS")
1664 return os.environ.get("NUMBER_OF_PROCESSORS")
1662
1665
1663
1666
1664 def num_cpus():
1667 def num_cpus():
1665 """Return the effective number of CPUs in the system as an integer.
1668 """Return the effective number of CPUs in the system as an integer.
1666
1669
1667 This cross-platform function makes an attempt at finding the total number of
1670 This cross-platform function makes an attempt at finding the total number of
1668 available CPUs in the system, as returned by various underlying system and
1671 available CPUs in the system, as returned by various underlying system and
1669 python calls.
1672 python calls.
1670
1673
1671 If it can't find a sensible answer, it returns 1 (though an error *may* make
1674 If it can't find a sensible answer, it returns 1 (though an error *may* make
1672 it return a large positive number that's actually incorrect).
1675 it return a large positive number that's actually incorrect).
1673 """
1676 """
1674
1677
1675 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
1678 # Many thanks to the Parallel Python project (http://www.parallelpython.com)
1676 # for the names of the keys we needed to look up for this function. This
1679 # for the names of the keys we needed to look up for this function. This
1677 # code was inspired by their equivalent function.
1680 # code was inspired by their equivalent function.
1678
1681
1679 ncpufuncs = {'Linux':_num_cpus_unix,
1682 ncpufuncs = {'Linux':_num_cpus_unix,
1680 'Darwin':_num_cpus_darwin,
1683 'Darwin':_num_cpus_darwin,
1681 'Windows':_num_cpus_windows,
1684 'Windows':_num_cpus_windows,
1682 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
1685 # On Vista, python < 2.5.2 has a bug and returns 'Microsoft'
1683 # See http://bugs.python.org/issue1082 for details.
1686 # See http://bugs.python.org/issue1082 for details.
1684 'Microsoft':_num_cpus_windows,
1687 'Microsoft':_num_cpus_windows,
1685 }
1688 }
1686
1689
1687 ncpufunc = ncpufuncs.get(platform.system(),
1690 ncpufunc = ncpufuncs.get(platform.system(),
1688 # default to unix version (Solaris, AIX, etc)
1691 # default to unix version (Solaris, AIX, etc)
1689 _num_cpus_unix)
1692 _num_cpus_unix)
1690
1693
1691 try:
1694 try:
1692 ncpus = max(1,int(ncpufunc()))
1695 ncpus = max(1,int(ncpufunc()))
1693 except:
1696 except:
1694 ncpus = 1
1697 ncpus = 1
1695 return ncpus
1698 return ncpus
1696
1699
1697 def extract_vars(*names,**kw):
1700 def extract_vars(*names,**kw):
1698 """Extract a set of variables by name from another frame.
1701 """Extract a set of variables by name from another frame.
1699
1702
1700 :Parameters:
1703 :Parameters:
1701 - `*names`: strings
1704 - `*names`: strings
1702 One or more variable names which will be extracted from the caller's
1705 One or more variable names which will be extracted from the caller's
1703 frame.
1706 frame.
1704
1707
1705 :Keywords:
1708 :Keywords:
1706 - `depth`: integer (0)
1709 - `depth`: integer (0)
1707 How many frames in the stack to walk when looking for your variables.
1710 How many frames in the stack to walk when looking for your variables.
1708
1711
1709
1712
1710 Examples:
1713 Examples:
1711
1714
1712 In [2]: def func(x):
1715 In [2]: def func(x):
1713 ...: y = 1
1716 ...: y = 1
1714 ...: print extract_vars('x','y')
1717 ...: print extract_vars('x','y')
1715 ...:
1718 ...:
1716
1719
1717 In [3]: func('hello')
1720 In [3]: func('hello')
1718 {'y': 1, 'x': 'hello'}
1721 {'y': 1, 'x': 'hello'}
1719 """
1722 """
1720
1723
1721 depth = kw.get('depth',0)
1724 depth = kw.get('depth',0)
1722
1725
1723 callerNS = sys._getframe(depth+1).f_locals
1726 callerNS = sys._getframe(depth+1).f_locals
1724 return dict((k,callerNS[k]) for k in names)
1727 return dict((k,callerNS[k]) for k in names)
1725
1728
1726
1729
1727 def extract_vars_above(*names):
1730 def extract_vars_above(*names):
1728 """Extract a set of variables by name from another frame.
1731 """Extract a set of variables by name from another frame.
1729
1732
1730 Similar to extractVars(), but with a specified depth of 1, so that names
1733 Similar to extractVars(), but with a specified depth of 1, so that names
1731 are exctracted exactly from above the caller.
1734 are exctracted exactly from above the caller.
1732
1735
1733 This is simply a convenience function so that the very common case (for us)
1736 This is simply a convenience function so that the very common case (for us)
1734 of skipping exactly 1 frame doesn't have to construct a special dict for
1737 of skipping exactly 1 frame doesn't have to construct a special dict for
1735 keyword passing."""
1738 keyword passing."""
1736
1739
1737 callerNS = sys._getframe(2).f_locals
1740 callerNS = sys._getframe(2).f_locals
1738 return dict((k,callerNS[k]) for k in names)
1741 return dict((k,callerNS[k]) for k in names)
1739
1742
1740 def shexp(s):
1743 def shexp(s):
1741 """Expand $VARS and ~names in a string, like a shell
1744 """Expand $VARS and ~names in a string, like a shell
1742
1745
1743 :Examples:
1746 :Examples:
1744
1747
1745 In [2]: os.environ['FOO']='test'
1748 In [2]: os.environ['FOO']='test'
1746
1749
1747 In [3]: shexp('variable FOO is $FOO')
1750 In [3]: shexp('variable FOO is $FOO')
1748 Out[3]: 'variable FOO is test'
1751 Out[3]: 'variable FOO is test'
1749 """
1752 """
1750 return os.path.expandvars(os.path.expanduser(s))
1753 return os.path.expandvars(os.path.expanduser(s))
1751
1754
1752
1755
1753 def list_strings(arg):
1756 def list_strings(arg):
1754 """Always return a list of strings, given a string or list of strings
1757 """Always return a list of strings, given a string or list of strings
1755 as input.
1758 as input.
1756
1759
1757 :Examples:
1760 :Examples:
1758
1761
1759 In [7]: list_strings('A single string')
1762 In [7]: list_strings('A single string')
1760 Out[7]: ['A single string']
1763 Out[7]: ['A single string']
1761
1764
1762 In [8]: list_strings(['A single string in a list'])
1765 In [8]: list_strings(['A single string in a list'])
1763 Out[8]: ['A single string in a list']
1766 Out[8]: ['A single string in a list']
1764
1767
1765 In [9]: list_strings(['A','list','of','strings'])
1768 In [9]: list_strings(['A','list','of','strings'])
1766 Out[9]: ['A', 'list', 'of', 'strings']
1769 Out[9]: ['A', 'list', 'of', 'strings']
1767 """
1770 """
1768
1771
1769 if isinstance(arg,basestring): return [arg]
1772 if isinstance(arg,basestring): return [arg]
1770 else: return arg
1773 else: return arg
1771
1774
1772
1775
1773 #----------------------------------------------------------------------------
1776 #----------------------------------------------------------------------------
1774 def marquee(txt='',width=78,mark='*'):
1777 def marquee(txt='',width=78,mark='*'):
1775 """Return the input string centered in a 'marquee'.
1778 """Return the input string centered in a 'marquee'.
1776
1779
1777 :Examples:
1780 :Examples:
1778
1781
1779 In [16]: marquee('A test',40)
1782 In [16]: marquee('A test',40)
1780 Out[16]: '**************** A test ****************'
1783 Out[16]: '**************** A test ****************'
1781
1784
1782 In [17]: marquee('A test',40,'-')
1785 In [17]: marquee('A test',40,'-')
1783 Out[17]: '---------------- A test ----------------'
1786 Out[17]: '---------------- A test ----------------'
1784
1787
1785 In [18]: marquee('A test',40,' ')
1788 In [18]: marquee('A test',40,' ')
1786 Out[18]: ' A test '
1789 Out[18]: ' A test '
1787
1790
1788 """
1791 """
1789 if not txt:
1792 if not txt:
1790 return (mark*width)[:width]
1793 return (mark*width)[:width]
1791 nmark = (width-len(txt)-2)/len(mark)/2
1794 nmark = (width-len(txt)-2)/len(mark)/2
1792 if nmark < 0: nmark =0
1795 if nmark < 0: nmark =0
1793 marks = mark*nmark
1796 marks = mark*nmark
1794 return '%s %s %s' % (marks,txt,marks)
1797 return '%s %s %s' % (marks,txt,marks)
1795
1798
1796 #*************************** end of file <genutils.py> **********************
1799 #*************************** end of file <genutils.py> **********************
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now