##// END OF EJS Templates
Fixing minor bug with the logging level in ipapp.py.
Brian Granger -
Show More
@@ -1,298 +1,300 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 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 import logging
26 import logging
27 import os
27 import os
28 import sys
28 import sys
29 import traceback
29 import traceback
30 from copy import deepcopy
30 from copy import deepcopy
31
31
32 from IPython.utils.genutils import get_ipython_dir, filefind
32 from IPython.utils.genutils import get_ipython_dir, filefind
33 from IPython.config.loader import (
33 from IPython.config.loader import (
34 PyFileConfigLoader,
34 PyFileConfigLoader,
35 ArgParseConfigLoader,
35 ArgParseConfigLoader,
36 Config,
36 Config,
37 NoConfigDefault
37 NoConfigDefault
38 )
38 )
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Classes and functions
41 # Classes and functions
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44
44
45 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
45 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
46 """Default command line options for IPython based applications."""
46 """Default command line options for IPython based applications."""
47
47
48 def _add_other_arguments(self):
48 def _add_other_arguments(self):
49 self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str,
49 self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str,
50 help='Set to override default location of Global.ipythondir.',
50 help='Set to override default location of Global.ipythondir.',
51 default=NoConfigDefault,
51 default=NoConfigDefault,
52 metavar='Global.ipythondir')
52 metavar='Global.ipythondir')
53 self.parser.add_argument('-p','-profile',dest='Global.profile',type=str,
53 self.parser.add_argument('-p','-profile',dest='Global.profile',type=str,
54 help='The string name of the ipython profile to be used.',
54 help='The string name of the ipython profile to be used.',
55 default=NoConfigDefault,
55 default=NoConfigDefault,
56 metavar='Global.profile')
56 metavar='Global.profile')
57 self.parser.add_argument('-log_level',dest="Global.log_level",type=int,
57 self.parser.add_argument('-log_level',dest="Global.log_level",type=int,
58 help='Set the log level (0,10,20,30,40,50). Default is 30.',
58 help='Set the log level (0,10,20,30,40,50). Default is 30.',
59 default=NoConfigDefault)
59 default=NoConfigDefault)
60 self.parser.add_argument('-config_file',dest='Global.config_file',type=str,
60 self.parser.add_argument('-config_file',dest='Global.config_file',type=str,
61 help='Set the config file name to override default.',
61 help='Set the config file name to override default.',
62 default=NoConfigDefault,
62 default=NoConfigDefault,
63 metavar='Global.config_file')
63 metavar='Global.config_file')
64
64
65
65
66 class ApplicationError(Exception):
66 class ApplicationError(Exception):
67 pass
67 pass
68
68
69
69
70 class Application(object):
70 class Application(object):
71 """Load a config, construct an app and run it.
71 """Load a config, construct an app and run it.
72 """
72 """
73
73
74 config_file_name = 'ipython_config.py'
74 config_file_name = 'ipython_config.py'
75 name = 'ipython'
75 name = 'ipython'
76
76
77 def __init__(self):
77 def __init__(self):
78 self.init_logger()
78 self.init_logger()
79 self.default_config_file_name = self.config_file_name
79 self.default_config_file_name = self.config_file_name
80
80
81 def init_logger(self):
81 def init_logger(self):
82 self.log = logging.getLogger(self.__class__.__name__)
82 self.log = logging.getLogger(self.__class__.__name__)
83 # This is used as the default until the command line arguments are read.
83 # This is used as the default until the command line arguments are read.
84 self.log.setLevel(logging.WARN)
84 self.log.setLevel(logging.WARN)
85 self._log_handler = logging.StreamHandler()
85 self._log_handler = logging.StreamHandler()
86 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
86 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
87 self._log_handler.setFormatter(self._log_formatter)
87 self._log_handler.setFormatter(self._log_formatter)
88 self.log.addHandler(self._log_handler)
88 self.log.addHandler(self._log_handler)
89
89
90 def _set_log_level(self, level):
90 def _set_log_level(self, level):
91 self.log.setLevel(level)
91 self.log.setLevel(level)
92
92
93 def _get_log_level(self):
93 def _get_log_level(self):
94 return self.log.level
94 return self.log.level
95
95
96 log_level = property(_get_log_level, _set_log_level)
96 log_level = property(_get_log_level, _set_log_level)
97
97
98 def start(self):
98 def start(self):
99 """Start the application."""
99 """Start the application."""
100 self.attempt(self.create_default_config)
100 self.attempt(self.create_default_config)
101 self.attempt(self.pre_load_command_line_config)
101 self.attempt(self.pre_load_command_line_config)
102 self.attempt(self.load_command_line_config, action='abort')
102 self.attempt(self.load_command_line_config, action='abort')
103 self.attempt(self.post_load_command_line_config)
103 self.attempt(self.post_load_command_line_config)
104 self.attempt(self.find_ipythondir)
104 self.attempt(self.find_ipythondir)
105 self.attempt(self.find_config_file_name)
105 self.attempt(self.find_config_file_name)
106 self.attempt(self.find_config_file_paths)
106 self.attempt(self.find_config_file_paths)
107 self.attempt(self.pre_load_file_config)
107 self.attempt(self.pre_load_file_config)
108 self.attempt(self.load_file_config)
108 self.attempt(self.load_file_config)
109 self.attempt(self.post_load_file_config)
109 self.attempt(self.post_load_file_config)
110 self.attempt(self.merge_configs)
110 self.attempt(self.merge_configs)
111 self.attempt(self.pre_construct)
111 self.attempt(self.pre_construct)
112 self.attempt(self.construct)
112 self.attempt(self.construct)
113 self.attempt(self.post_construct)
113 self.attempt(self.post_construct)
114 self.attempt(self.start_app)
114 self.attempt(self.start_app)
115
115
116 #-------------------------------------------------------------------------
116 #-------------------------------------------------------------------------
117 # Various stages of Application creation
117 # Various stages of Application creation
118 #-------------------------------------------------------------------------
118 #-------------------------------------------------------------------------
119
119
120 def create_default_config(self):
120 def create_default_config(self):
121 """Create defaults that can't be set elsewhere.
121 """Create defaults that can't be set elsewhere.
122
122
123 For the most part, we try to set default in the class attributes
123 For the most part, we try to set default in the class attributes
124 of Components. But, defaults the top-level Application (which is
124 of Components. But, defaults the top-level Application (which is
125 not a HasTraitlets or Component) are not set in this way. Instead
125 not a HasTraitlets or Component) are not set in this way. Instead
126 we set them here. The Global section is for variables like this that
126 we set them here. The Global section is for variables like this that
127 don't belong to a particular component.
127 don't belong to a particular component.
128 """
128 """
129 self.default_config = Config()
129 self.default_config = Config()
130 self.default_config.Global.ipythondir = get_ipython_dir()
130 self.default_config.Global.ipythondir = get_ipython_dir()
131 self.log.debug('Default config loaded:')
131 self.log.debug('Default config loaded:')
132 self.log.debug(repr(self.default_config))
132 self.log.debug(repr(self.default_config))
133
133
134 def create_command_line_config(self):
134 def create_command_line_config(self):
135 """Create and return a command line config loader."""
135 """Create and return a command line config loader."""
136 return IPythonArgParseConfigLoader(description=self.name)
136 return IPythonArgParseConfigLoader(description=self.name)
137
137
138 def pre_load_command_line_config(self):
138 def pre_load_command_line_config(self):
139 """Do actions just before loading the command line config."""
139 """Do actions just before loading the command line config."""
140 pass
140 pass
141
141
142 def load_command_line_config(self):
142 def load_command_line_config(self):
143 """Load the command line config.
143 """Load the command line config.
144
144
145 This method also sets ``self.debug``.
145 This method also sets ``self.debug``.
146 """
146 """
147
147
148 loader = self.create_command_line_config()
148 loader = self.create_command_line_config()
149 self.command_line_config = loader.load_config()
149 self.command_line_config = loader.load_config()
150 self.extra_args = loader.get_extra_args()
150 self.extra_args = loader.get_extra_args()
151
151
152 try:
152 try:
153 self.log_level = self.command_line_config.Global.log_level
153 self.log_level = self.command_line_config.Global.log_level
154 except AttributeError:
154 except AttributeError:
155 pass # Use existing value which is set in Application.init_logger.
155 pass # Use existing value which is set in Application.init_logger.
156
157 self.log.debug("Command line config loaded:")
156 self.log.debug("Command line config loaded:")
158 self.log.debug(repr(self.command_line_config))
157 self.log.debug(repr(self.command_line_config))
159
158
160 def post_load_command_line_config(self):
159 def post_load_command_line_config(self):
161 """Do actions just after loading the command line config."""
160 """Do actions just after loading the command line config."""
162 pass
161 pass
163
162
164 def find_ipythondir(self):
163 def find_ipythondir(self):
165 """Set the IPython directory.
164 """Set the IPython directory.
166
165
167 This sets ``self.ipythondir``, but the actual value that is passed
166 This sets ``self.ipythondir``, but the actual value that is passed
168 to the application is kept in either ``self.default_config`` or
167 to the application is kept in either ``self.default_config`` or
169 ``self.command_line_config``. This also added ``self.ipythondir`` to
168 ``self.command_line_config``. This also added ``self.ipythondir`` to
170 ``sys.path`` so config files there can be references by other config
169 ``sys.path`` so config files there can be references by other config
171 files.
170 files.
172 """
171 """
173
172
174 try:
173 try:
175 self.ipythondir = self.command_line_config.Global.ipythondir
174 self.ipythondir = self.command_line_config.Global.ipythondir
176 except AttributeError:
175 except AttributeError:
177 self.ipythondir = self.default_config.Global.ipythondir
176 self.ipythondir = self.default_config.Global.ipythondir
178 sys.path.append(os.path.abspath(self.ipythondir))
177 sys.path.append(os.path.abspath(self.ipythondir))
179 if not os.path.isdir(self.ipythondir):
178 if not os.path.isdir(self.ipythondir):
180 os.makedirs(self.ipythondir, mode = 0777)
179 os.makedirs(self.ipythondir, mode = 0777)
181 self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir)
180 self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir)
182
181
183 def find_config_file_name(self):
182 def find_config_file_name(self):
184 """Find the config file name for this application.
183 """Find the config file name for this application.
185
184
186 If a profile has been set at the command line, this will resolve
185 If a profile has been set at the command line, this will resolve
187 it. The search paths for the config file are set in
186 it. The search paths for the config file are set in
188 :meth:`find_config_file_paths` and then passed to the config file
187 :meth:`find_config_file_paths` and then passed to the config file
189 loader where they are resolved to an absolute path.
188 loader where they are resolved to an absolute path.
190 """
189 """
191
190
192 try:
191 try:
193 self.config_file_name = self.command_line_config.Global.config_file
192 self.config_file_name = self.command_line_config.Global.config_file
194 except AttributeError:
193 except AttributeError:
195 pass
194 pass
196
195
197 try:
196 try:
198 self.profile_name = self.command_line_config.Global.profile
197 self.profile_name = self.command_line_config.Global.profile
199 name_parts = self.config_file_name.split('.')
198 name_parts = self.config_file_name.split('.')
200 name_parts.insert(1, '_' + self.profile_name + '.')
199 name_parts.insert(1, '_' + self.profile_name + '.')
201 self.config_file_name = ''.join(name_parts)
200 self.config_file_name = ''.join(name_parts)
202 except AttributeError:
201 except AttributeError:
203 pass
202 pass
204
203
205 def find_config_file_paths(self):
204 def find_config_file_paths(self):
206 """Set the search paths for resolving the config file."""
205 """Set the search paths for resolving the config file."""
207 self.config_file_paths = (os.getcwd(), self.ipythondir)
206 self.config_file_paths = (os.getcwd(), self.ipythondir)
208
207
209 def pre_load_file_config(self):
208 def pre_load_file_config(self):
210 """Do actions before the config file is loaded."""
209 """Do actions before the config file is loaded."""
211 pass
210 pass
212
211
213 def load_file_config(self):
212 def load_file_config(self):
214 """Load the config file.
213 """Load the config file.
215
214
216 This tries to load the config file from disk. If successful, the
215 This tries to load the config file from disk. If successful, the
217 ``CONFIG_FILE`` config variable is set to the resolved config file
216 ``CONFIG_FILE`` config variable is set to the resolved config file
218 location. If not successful, an empty config is used.
217 location. If not successful, an empty config is used.
219 """
218 """
220 self.log.debug("Attempting to load config file: <%s>" % self.config_file_name)
219 self.log.debug("Attempting to load config file: <%s>" % self.config_file_name)
221 loader = PyFileConfigLoader(self.config_file_name,
220 loader = PyFileConfigLoader(self.config_file_name,
222 path=self.config_file_paths)
221 path=self.config_file_paths)
223 try:
222 try:
224 self.file_config = loader.load_config()
223 self.file_config = loader.load_config()
225 self.file_config.Global.config_file = loader.full_filename
224 self.file_config.Global.config_file = loader.full_filename
226 except IOError:
225 except IOError:
227 # Only warn if the default config file was NOT being used.
226 # Only warn if the default config file was NOT being used.
228 if not self.config_file_name==self.default_config_file_name:
227 if not self.config_file_name==self.default_config_file_name:
229 self.log.warn("Config file not found, skipping: <%s>" % \
228 self.log.warn("Config file not found, skipping: <%s>" % \
230 self.config_file_name, exc_info=True)
229 self.config_file_name, exc_info=True)
231 self.file_config = Config()
230 self.file_config = Config()
232 except:
231 except:
233 self.log.warn("Error loading config file: <%s>" % \
232 self.log.warn("Error loading config file: <%s>" % \
234 self.config_file_name, exc_info=True)
233 self.config_file_name, exc_info=True)
235 self.file_config = Config()
234 self.file_config = Config()
236 else:
235 else:
237 self.log.debug("Config file loaded: <%s>" % loader.full_filename)
236 self.log.debug("Config file loaded: <%s>" % loader.full_filename)
238 self.log.debug(repr(self.file_config))
237 self.log.debug(repr(self.file_config))
239 # We need to keeep self.log_level updated.
238 # We need to keeep self.log_level updated. But we only use the value
239 # of the file_config if a value was not specified at the command
240 # line.
241 if not hasattr(self.command_line_config.Global, 'log_level'):
240 try:
242 try:
241 self.log_level = self.file_config.Global.log_level
243 self.log_level = self.file_config.Global.log_level
242 except AttributeError:
244 except AttributeError:
243 pass # Use existing value
245 pass # Use existing value
244
246
245 def post_load_file_config(self):
247 def post_load_file_config(self):
246 """Do actions after the config file is loaded."""
248 """Do actions after the config file is loaded."""
247 pass
249 pass
248
250
249 def merge_configs(self):
251 def merge_configs(self):
250 """Merge the default, command line and file config objects."""
252 """Merge the default, command line and file config objects."""
251 config = Config()
253 config = Config()
252 config._merge(self.default_config)
254 config._merge(self.default_config)
253 config._merge(self.file_config)
255 config._merge(self.file_config)
254 config._merge(self.command_line_config)
256 config._merge(self.command_line_config)
255 self.master_config = config
257 self.master_config = config
256 self.log.debug("Master config created:")
258 self.log.debug("Master config created:")
257 self.log.debug(repr(self.master_config))
259 self.log.debug(repr(self.master_config))
258
260
259 def pre_construct(self):
261 def pre_construct(self):
260 """Do actions after the config has been built, but before construct."""
262 """Do actions after the config has been built, but before construct."""
261 pass
263 pass
262
264
263 def construct(self):
265 def construct(self):
264 """Construct the main components that make up this app."""
266 """Construct the main components that make up this app."""
265 self.log.debug("Constructing components for application")
267 self.log.debug("Constructing components for application")
266
268
267 def post_construct(self):
269 def post_construct(self):
268 """Do actions after construct, but before starting the app."""
270 """Do actions after construct, but before starting the app."""
269 pass
271 pass
270
272
271 def start_app(self):
273 def start_app(self):
272 """Actually start the app."""
274 """Actually start the app."""
273 self.log.debug("Starting application")
275 self.log.debug("Starting application")
274
276
275 #-------------------------------------------------------------------------
277 #-------------------------------------------------------------------------
276 # Utility methods
278 # Utility methods
277 #-------------------------------------------------------------------------
279 #-------------------------------------------------------------------------
278
280
279 def abort(self):
281 def abort(self):
280 """Abort the starting of the application."""
282 """Abort the starting of the application."""
281 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
283 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
282 sys.exit(1)
284 sys.exit(1)
283
285
284 def exit(self):
286 def exit(self):
285 self.log.critical("Aborting application: %s" % self.name)
287 self.log.critical("Aborting application: %s" % self.name)
286 sys.exit(1)
288 sys.exit(1)
287
289
288 def attempt(self, func, action='abort'):
290 def attempt(self, func, action='abort'):
289 try:
291 try:
290 func()
292 func()
291 except SystemExit:
293 except SystemExit:
292 self.exit()
294 self.exit()
293 except:
295 except:
294 if action == 'abort':
296 if action == 'abort':
295 self.abort()
297 self.abort()
296 elif action == 'exit':
298 elif action == 'exit':
297 self.exit()
299 self.exit()
298 No newline at end of file
300
@@ -1,545 +1,546 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The main IPython application object
4 The main IPython application object
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 import logging
26 import logging
27 import os
27 import os
28 import sys
28 import sys
29 import warnings
29 import warnings
30
30
31 from IPython.core.application import Application, IPythonArgParseConfigLoader
31 from IPython.core.application import Application, IPythonArgParseConfigLoader
32 from IPython.core import release
32 from IPython.core import release
33 from IPython.core.iplib import InteractiveShell
33 from IPython.core.iplib import InteractiveShell
34 from IPython.config.loader import (
34 from IPython.config.loader import (
35 NoConfigDefault,
35 NoConfigDefault,
36 Config,
36 Config,
37 ConfigError,
37 ConfigError,
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.ipstruct import Struct
43 from IPython.utils.ipstruct import Struct
44 from IPython.utils.genutils import filefind, get_ipython_dir
44 from IPython.utils.genutils import filefind, get_ipython_dir
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Utilities and helpers
47 # Utilities and helpers
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50
50
51 ipython_desc = """
51 ipython_desc = """
52 A Python shell with automatic history (input and output), dynamic object
52 A Python shell with automatic history (input and output), dynamic object
53 introspection, easier configuration, command completion, access to the system
53 introspection, easier configuration, command completion, access to the system
54 shell and more.
54 shell and more.
55 """
55 """
56
56
57 def pylab_warning():
57 def pylab_warning():
58 msg = """
58 msg = """
59
59
60 IPython's -pylab mode has been disabled until matplotlib supports this version
60 IPython's -pylab mode has been disabled until matplotlib supports this version
61 of IPython. This version of IPython has greatly improved GUI integration that
61 of IPython. This version of IPython has greatly improved GUI integration that
62 matplotlib will soon be able to take advantage of. This will eventually
62 matplotlib will soon be able to take advantage of. This will eventually
63 result in greater stability and a richer API for matplotlib under IPython.
63 result in greater stability and a richer API for matplotlib under IPython.
64 However during this transition, you will either need to use an older version
64 However during this transition, you will either need to use an older version
65 of IPython, or do the following to use matplotlib interactively::
65 of IPython, or do the following to use matplotlib interactively::
66
66
67 import matplotlib
67 import matplotlib
68 matplotlib.interactive(True)
68 matplotlib.interactive(True)
69 matplotlib.use('wxagg') # adjust for your backend
69 matplotlib.use('wxagg') # adjust for your backend
70 %gui -a wx # adjust for your GUI
70 %gui -a wx # adjust for your GUI
71 from matplotlib import pyplot as plt
71 from matplotlib import pyplot as plt
72
72
73 See the %gui magic for information on the new interface.
73 See the %gui magic for information on the new interface.
74 """
74 """
75 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
75 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
76
76
77
77
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79 # Main classes and functions
79 # Main classes and functions
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81
81
82 cl_args = (
82 cl_args = (
83 (('-autocall',), dict(
83 (('-autocall',), dict(
84 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
84 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
85 help='Set the autocall value (0,1,2).',
85 help='Set the autocall value (0,1,2).',
86 metavar='InteractiveShell.autocall')
86 metavar='InteractiveShell.autocall')
87 ),
87 ),
88 (('-autoindent',), dict(
88 (('-autoindent',), dict(
89 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
89 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
90 help='Turn on autoindenting.')
90 help='Turn on autoindenting.')
91 ),
91 ),
92 (('-noautoindent',), dict(
92 (('-noautoindent',), dict(
93 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
93 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
94 help='Turn off autoindenting.')
94 help='Turn off autoindenting.')
95 ),
95 ),
96 (('-automagic',), dict(
96 (('-automagic',), dict(
97 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
97 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
98 help='Turn on the auto calling of magic commands.')
98 help='Turn on the auto calling of magic commands.')
99 ),
99 ),
100 (('-noautomagic',), dict(
100 (('-noautomagic',), dict(
101 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
101 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
102 help='Turn off the auto calling of magic commands.')
102 help='Turn off the auto calling of magic commands.')
103 ),
103 ),
104 (('-autoedit_syntax',), dict(
104 (('-autoedit_syntax',), dict(
105 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
105 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
106 help='Turn on auto editing of files with syntax errors.')
106 help='Turn on auto editing of files with syntax errors.')
107 ),
107 ),
108 (('-noautoedit_syntax',), dict(
108 (('-noautoedit_syntax',), dict(
109 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
109 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
110 help='Turn off auto editing of files with syntax errors.')
110 help='Turn off auto editing of files with syntax errors.')
111 ),
111 ),
112 (('-banner',), dict(
112 (('-banner',), dict(
113 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
113 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
114 help='Display a banner upon starting IPython.')
114 help='Display a banner upon starting IPython.')
115 ),
115 ),
116 (('-nobanner',), dict(
116 (('-nobanner',), dict(
117 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
117 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
118 help="Don't display a banner upon starting IPython.")
118 help="Don't display a banner upon starting IPython.")
119 ),
119 ),
120 (('-cache_size',), dict(
120 (('-cache_size',), dict(
121 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
121 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
122 help="Set the size of the output cache.",
122 help="Set the size of the output cache.",
123 metavar='InteractiveShell.cache_size')
123 metavar='InteractiveShell.cache_size')
124 ),
124 ),
125 (('-classic',), dict(
125 (('-classic',), dict(
126 action='store_true', dest='Global.classic', default=NoConfigDefault,
126 action='store_true', dest='Global.classic', default=NoConfigDefault,
127 help="Gives IPython a similar feel to the classic Python prompt.")
127 help="Gives IPython a similar feel to the classic Python prompt.")
128 ),
128 ),
129 (('-colors',), dict(
129 (('-colors',), dict(
130 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
130 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
131 help="Set the color scheme (NoColor, Linux, and LightBG).",
131 help="Set the color scheme (NoColor, Linux, and LightBG).",
132 metavar='InteractiveShell.colors')
132 metavar='InteractiveShell.colors')
133 ),
133 ),
134 (('-color_info',), dict(
134 (('-color_info',), dict(
135 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
135 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
136 help="Enable using colors for info related things.")
136 help="Enable using colors for info related things.")
137 ),
137 ),
138 (('-nocolor_info',), dict(
138 (('-nocolor_info',), dict(
139 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
139 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
140 help="Disable using colors for info related things.")
140 help="Disable using colors for info related things.")
141 ),
141 ),
142 (('-confirm_exit',), dict(
142 (('-confirm_exit',), dict(
143 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
143 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
144 help="Prompt the user when existing.")
144 help="Prompt the user when existing.")
145 ),
145 ),
146 (('-noconfirm_exit',), dict(
146 (('-noconfirm_exit',), dict(
147 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
147 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
148 help="Don't prompt the user when existing.")
148 help="Don't prompt the user when existing.")
149 ),
149 ),
150 (('-deep_reload',), dict(
150 (('-deep_reload',), dict(
151 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
151 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
152 help="Enable deep (recursive) reloading by default.")
152 help="Enable deep (recursive) reloading by default.")
153 ),
153 ),
154 (('-nodeep_reload',), dict(
154 (('-nodeep_reload',), dict(
155 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
155 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
156 help="Disable deep (recursive) reloading by default.")
156 help="Disable deep (recursive) reloading by default.")
157 ),
157 ),
158 (('-editor',), dict(
158 (('-editor',), dict(
159 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
159 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
160 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
160 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
161 metavar='InteractiveShell.editor')
161 metavar='InteractiveShell.editor')
162 ),
162 ),
163 (('-log','-l'), dict(
163 (('-log','-l'), dict(
164 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
164 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
165 help="Start logging to the default file (./ipython_log.py).")
165 help="Start logging to the default file (./ipython_log.py).")
166 ),
166 ),
167 (('-logfile','-lf'), dict(
167 (('-logfile','-lf'), dict(
168 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
168 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
169 help="Start logging to logfile.",
169 help="Start logging to logfile.",
170 metavar='InteractiveShell.logfile')
170 metavar='InteractiveShell.logfile')
171 ),
171 ),
172 (('-logappend','-la'), dict(
172 (('-logappend','-la'), dict(
173 type=str, dest='InteractiveShell.logappend', default=NoConfigDefault,
173 type=str, dest='InteractiveShell.logappend', default=NoConfigDefault,
174 help="Start logging to logappend in append mode.",
174 help="Start logging to logappend in append mode.",
175 metavar='InteractiveShell.logfile')
175 metavar='InteractiveShell.logfile')
176 ),
176 ),
177 (('-pdb',), dict(
177 (('-pdb',), dict(
178 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
178 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
179 help="Enable auto calling the pdb debugger after every exception.")
179 help="Enable auto calling the pdb debugger after every exception.")
180 ),
180 ),
181 (('-nopdb',), dict(
181 (('-nopdb',), dict(
182 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
182 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
183 help="Disable auto calling the pdb debugger after every exception.")
183 help="Disable auto calling the pdb debugger after every exception.")
184 ),
184 ),
185 (('-pprint',), dict(
185 (('-pprint',), dict(
186 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
186 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
187 help="Enable auto pretty printing of results.")
187 help="Enable auto pretty printing of results.")
188 ),
188 ),
189 (('-nopprint',), dict(
189 (('-nopprint',), dict(
190 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
190 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
191 help="Disable auto auto pretty printing of results.")
191 help="Disable auto auto pretty printing of results.")
192 ),
192 ),
193 (('-prompt_in1','-pi1'), dict(
193 (('-prompt_in1','-pi1'), dict(
194 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
194 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
195 help="Set the main input prompt ('In [\#]: ')",
195 help="Set the main input prompt ('In [\#]: ')",
196 metavar='InteractiveShell.prompt_in1')
196 metavar='InteractiveShell.prompt_in1')
197 ),
197 ),
198 (('-prompt_in2','-pi2'), dict(
198 (('-prompt_in2','-pi2'), dict(
199 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
199 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
200 help="Set the secondary input prompt (' .\D.: ')",
200 help="Set the secondary input prompt (' .\D.: ')",
201 metavar='InteractiveShell.prompt_in2')
201 metavar='InteractiveShell.prompt_in2')
202 ),
202 ),
203 (('-prompt_out','-po'), dict(
203 (('-prompt_out','-po'), dict(
204 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
204 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
205 help="Set the output prompt ('Out[\#]:')",
205 help="Set the output prompt ('Out[\#]:')",
206 metavar='InteractiveShell.prompt_out')
206 metavar='InteractiveShell.prompt_out')
207 ),
207 ),
208 (('-quick',), dict(
208 (('-quick',), dict(
209 action='store_true', dest='Global.quick', default=NoConfigDefault,
209 action='store_true', dest='Global.quick', default=NoConfigDefault,
210 help="Enable quick startup with no config files.")
210 help="Enable quick startup with no config files.")
211 ),
211 ),
212 (('-readline',), dict(
212 (('-readline',), dict(
213 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
213 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
214 help="Enable readline for command line usage.")
214 help="Enable readline for command line usage.")
215 ),
215 ),
216 (('-noreadline',), dict(
216 (('-noreadline',), dict(
217 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
217 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
218 help="Disable readline for command line usage.")
218 help="Disable readline for command line usage.")
219 ),
219 ),
220 (('-screen_length','-sl'), dict(
220 (('-screen_length','-sl'), dict(
221 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
221 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
222 help='Number of lines on screen, used to control printing of long strings.',
222 help='Number of lines on screen, used to control printing of long strings.',
223 metavar='InteractiveShell.screen_length')
223 metavar='InteractiveShell.screen_length')
224 ),
224 ),
225 (('-separate_in','-si'), dict(
225 (('-separate_in','-si'), dict(
226 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
226 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
227 help="Separator before input prompts. Default '\n'.",
227 help="Separator before input prompts. Default '\n'.",
228 metavar='InteractiveShell.separate_in')
228 metavar='InteractiveShell.separate_in')
229 ),
229 ),
230 (('-separate_out','-so'), dict(
230 (('-separate_out','-so'), dict(
231 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
231 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
232 help="Separator before output prompts. Default 0 (nothing).",
232 help="Separator before output prompts. Default 0 (nothing).",
233 metavar='InteractiveShell.separate_out')
233 metavar='InteractiveShell.separate_out')
234 ),
234 ),
235 (('-separate_out2','-so2'), dict(
235 (('-separate_out2','-so2'), dict(
236 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
236 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
237 help="Separator after output prompts. Default 0 (nonight).",
237 help="Separator after output prompts. Default 0 (nonight).",
238 metavar='InteractiveShell.separate_out2')
238 metavar='InteractiveShell.separate_out2')
239 ),
239 ),
240 (('-nosep',), dict(
240 (('-nosep',), dict(
241 action='store_true', dest='Global.nosep', default=NoConfigDefault,
241 action='store_true', dest='Global.nosep', default=NoConfigDefault,
242 help="Eliminate all spacing between prompts.")
242 help="Eliminate all spacing between prompts.")
243 ),
243 ),
244 (('-term_title',), dict(
244 (('-term_title',), dict(
245 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
245 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
246 help="Enable auto setting the terminal title.")
246 help="Enable auto setting the terminal title.")
247 ),
247 ),
248 (('-noterm_title',), dict(
248 (('-noterm_title',), dict(
249 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
249 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
250 help="Disable auto setting the terminal title.")
250 help="Disable auto setting the terminal title.")
251 ),
251 ),
252 (('-xmode',), dict(
252 (('-xmode',), dict(
253 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
253 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
254 help="Exception mode ('Plain','Context','Verbose')",
254 help="Exception mode ('Plain','Context','Verbose')",
255 metavar='InteractiveShell.xmode')
255 metavar='InteractiveShell.xmode')
256 ),
256 ),
257 (('-ext',), dict(
257 (('-ext',), dict(
258 type=str, dest='Global.extra_extension', default=NoConfigDefault,
258 type=str, dest='Global.extra_extension', default=NoConfigDefault,
259 help="The dotted module name of an IPython extension to load.",
259 help="The dotted module name of an IPython extension to load.",
260 metavar='Global.extra_extension')
260 metavar='Global.extra_extension')
261 ),
261 ),
262 (('-c',), dict(
262 (('-c',), dict(
263 type=str, dest='Global.code_to_run', default=NoConfigDefault,
263 type=str, dest='Global.code_to_run', default=NoConfigDefault,
264 help="Execute the given command string.",
264 help="Execute the given command string.",
265 metavar='Global.code_to_run')
265 metavar='Global.code_to_run')
266 ),
266 ),
267 (('-i',), dict(
267 (('-i',), dict(
268 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
268 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
269 help="If running code from the command line, become interactive afterwards.")
269 help="If running code from the command line, become interactive afterwards.")
270 ),
270 ),
271 (('-wthread',), dict(
271 (('-wthread',), dict(
272 action='store_true', dest='Global.wthread', default=NoConfigDefault,
272 action='store_true', dest='Global.wthread', default=NoConfigDefault,
273 help="Enable wxPython event loop integration.")
273 help="Enable wxPython event loop integration.")
274 ),
274 ),
275 (('-q4thread','-qthread'), dict(
275 (('-q4thread','-qthread'), dict(
276 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
276 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
277 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
277 help="Enable Qt4 event loop integration. Qt3 is no longer supported.")
278 ),
278 ),
279 (('-gthread',), dict(
279 (('-gthread',), dict(
280 action='store_true', dest='Global.gthread', default=NoConfigDefault,
280 action='store_true', dest='Global.gthread', default=NoConfigDefault,
281 help="Enable GTK event loop integration.")
281 help="Enable GTK event loop integration.")
282 ),
282 ),
283 # # These are only here to get the proper deprecation warnings
283 # # These are only here to get the proper deprecation warnings
284 (('-pylab',), dict(
284 (('-pylab',), dict(
285 action='store_true', dest='Global.pylab', default=NoConfigDefault,
285 action='store_true', dest='Global.pylab', default=NoConfigDefault,
286 help="Disabled. Pylab has been disabled until matplotlib supports this version of IPython.")
286 help="Disabled. Pylab has been disabled until matplotlib supports this version of IPython.")
287 )
287 )
288 )
288 )
289
289
290
290
291 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
291 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
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 class IPythonApp(Application):
298 class IPythonApp(Application):
299 name = 'ipython'
299 name = 'ipython'
300 config_file_name = _default_config_file_name
300 config_file_name = _default_config_file_name
301
301
302 def create_default_config(self):
302 def create_default_config(self):
303 super(IPythonApp, self).create_default_config()
303 super(IPythonApp, self).create_default_config()
304 self.default_config.Global.display_banner = True
304 self.default_config.Global.display_banner = True
305
305
306 # If the -c flag is given or a file is given to run at the cmd line
306 # If the -c flag is given or a file is given to run at the cmd line
307 # like "ipython foo.py", normally we exit without starting the main
307 # like "ipython foo.py", normally we exit without starting the main
308 # loop. The force_interact config variable allows a user to override
308 # loop. The force_interact config variable allows a user to override
309 # this and interact. It is also set by the -i cmd line flag, just
309 # this and interact. It is also set by the -i cmd line flag, just
310 # like Python.
310 # like Python.
311 self.default_config.Global.force_interact = False
311 self.default_config.Global.force_interact = False
312
312
313 # By default always interact by starting the IPython mainloop.
313 # By default always interact by starting the IPython mainloop.
314 self.default_config.Global.interact = True
314 self.default_config.Global.interact = True
315
315
316 # Let the parent class set the default, but each time log_level
316 # Let the parent class set the default, but each time log_level
317 # changes from config, we need to update self.log_level as that is
317 # changes from config, we need to update self.log_level as that is
318 # what updates the actual log level in self.log.
318 # what updates the actual log level in self.log.
319 self.default_config.Global.log_level = self.log_level
319 self.default_config.Global.log_level = self.log_level
320
320
321 # No GUI integration by default
321 # No GUI integration by default
322 self.default_config.Global.wthread = False
322 self.default_config.Global.wthread = False
323 self.default_config.Global.q4thread = False
323 self.default_config.Global.q4thread = False
324 self.default_config.Global.gthread = False
324 self.default_config.Global.gthread = False
325
325
326 def create_command_line_config(self):
326 def create_command_line_config(self):
327 """Create and return a command line config loader."""
327 """Create and return a command line config loader."""
328 return IPythonAppCLConfigLoader(
328 return IPythonAppCLConfigLoader(
329 description=ipython_desc,
329 description=ipython_desc,
330 version=release.version)
330 version=release.version)
331
331
332 def post_load_command_line_config(self):
332 def post_load_command_line_config(self):
333 """Do actions after loading cl config."""
333 """Do actions after loading cl config."""
334 clc = self.command_line_config
334 clc = self.command_line_config
335
335
336 # Display the deprecation warnings about threaded shells
336 # Display the deprecation warnings about threaded shells
337 if hasattr(clc.Global, 'pylab'):
337 if hasattr(clc.Global, 'pylab'):
338 pylab_warning()
338 pylab_warning()
339 del clc.Global['pylab']
339 del clc.Global['pylab']
340
340
341 def load_file_config(self):
341 def load_file_config(self):
342 if hasattr(self.command_line_config.Global, 'quick'):
342 if hasattr(self.command_line_config.Global, 'quick'):
343 if self.command_line_config.Global.quick:
343 if self.command_line_config.Global.quick:
344 self.file_config = Config()
344 self.file_config = Config()
345 return
345 return
346 super(IPythonApp, self).load_file_config()
346 super(IPythonApp, self).load_file_config()
347
347
348 def post_load_file_config(self):
348 def post_load_file_config(self):
349 if hasattr(self.command_line_config.Global, 'extra_extension'):
349 if hasattr(self.command_line_config.Global, 'extra_extension'):
350 if not hasattr(self.file_config.Global, 'extensions'):
350 if not hasattr(self.file_config.Global, 'extensions'):
351 self.file_config.Global.extensions = []
351 self.file_config.Global.extensions = []
352 self.file_config.Global.extensions.append(
352 self.file_config.Global.extensions.append(
353 self.command_line_config.Global.extra_extension)
353 self.command_line_config.Global.extra_extension)
354 del self.command_line_config.Global.extra_extension
354 del self.command_line_config.Global.extra_extension
355
355
356 def pre_construct(self):
356 def pre_construct(self):
357 config = self.master_config
357 config = self.master_config
358
358
359 if hasattr(config.Global, 'classic'):
359 if hasattr(config.Global, 'classic'):
360 if config.Global.classic:
360 if config.Global.classic:
361 config.InteractiveShell.cache_size = 0
361 config.InteractiveShell.cache_size = 0
362 config.InteractiveShell.pprint = 0
362 config.InteractiveShell.pprint = 0
363 config.InteractiveShell.prompt_in1 = '>>> '
363 config.InteractiveShell.prompt_in1 = '>>> '
364 config.InteractiveShell.prompt_in2 = '... '
364 config.InteractiveShell.prompt_in2 = '... '
365 config.InteractiveShell.prompt_out = ''
365 config.InteractiveShell.prompt_out = ''
366 config.InteractiveShell.separate_in = \
366 config.InteractiveShell.separate_in = \
367 config.InteractiveShell.separate_out = \
367 config.InteractiveShell.separate_out = \
368 config.InteractiveShell.separate_out2 = ''
368 config.InteractiveShell.separate_out2 = ''
369 config.InteractiveShell.colors = 'NoColor'
369 config.InteractiveShell.colors = 'NoColor'
370 config.InteractiveShell.xmode = 'Plain'
370 config.InteractiveShell.xmode = 'Plain'
371
371
372 if hasattr(config.Global, 'nosep'):
372 if hasattr(config.Global, 'nosep'):
373 if config.Global.nosep:
373 if config.Global.nosep:
374 config.InteractiveShell.separate_in = \
374 config.InteractiveShell.separate_in = \
375 config.InteractiveShell.separate_out = \
375 config.InteractiveShell.separate_out = \
376 config.InteractiveShell.separate_out2 = ''
376 config.InteractiveShell.separate_out2 = ''
377
377
378 # if there is code of files to run from the cmd line, don't interact
378 # if there is code of files to run from the cmd line, don't interact
379 # unless the -i flag (Global.force_interact) is true.
379 # unless the -i flag (Global.force_interact) is true.
380 code_to_run = config.Global.get('code_to_run','')
380 code_to_run = config.Global.get('code_to_run','')
381 file_to_run = False
381 file_to_run = False
382 if len(self.extra_args)>=1:
382 if len(self.extra_args)>=1:
383 if self.extra_args[0]:
383 if self.extra_args[0]:
384 file_to_run = True
384 file_to_run = True
385 if file_to_run or code_to_run:
385 if file_to_run or code_to_run:
386 if not config.Global.force_interact:
386 if not config.Global.force_interact:
387 config.Global.interact = False
387 config.Global.interact = False
388
388
389 def construct(self):
389 def construct(self):
390 # I am a little hesitant to put these into InteractiveShell itself.
390 # I am a little hesitant to put these into InteractiveShell itself.
391 # But that might be the place for them
391 # But that might be the place for them
392 sys.path.insert(0, '')
392 sys.path.insert(0, '')
393
393
394 # Create an InteractiveShell instance
394 # Create an InteractiveShell instance
395 self.shell = InteractiveShell(
395 self.shell = InteractiveShell(
396 parent=None,
396 parent=None,
397 config=self.master_config
397 config=self.master_config
398 )
398 )
399
399
400 def post_construct(self):
400 def post_construct(self):
401 """Do actions after construct, but before starting the app."""
401 """Do actions after construct, but before starting the app."""
402 config = self.master_config
402 config = self.master_config
403
403
404 # shell.display_banner should always be False for the terminal
404 # shell.display_banner should always be False for the terminal
405 # based app, because we call shell.show_banner() by hand below
405 # based app, because we call shell.show_banner() by hand below
406 # so the banner shows *before* all extension loading stuff.
406 # so the banner shows *before* all extension loading stuff.
407 self.shell.display_banner = False
407 self.shell.display_banner = False
408
408
409 if config.Global.display_banner and \
409 if config.Global.display_banner and \
410 config.Global.interact:
410 config.Global.interact:
411 self.shell.show_banner()
411 self.shell.show_banner()
412
412
413 # Make sure there is a space below the banner.
413 # Make sure there is a space below the banner.
414 if self.log_level <= logging.INFO: print
414 if self.log_level <= logging.INFO: print
415
415
416 # Now a variety of things that happen after the banner is printed.
416 self._enable_gui()
417 self._enable_gui()
417 self._load_extensions()
418 self._load_extensions()
418 self._run_exec_lines()
419 self._run_exec_lines()
419 self._run_exec_files()
420 self._run_exec_files()
420 self._run_cmd_line_code()
421 self._run_cmd_line_code()
421
422
422 def _enable_gui(self):
423 def _enable_gui(self):
423 """Enable GUI event loop integration."""
424 """Enable GUI event loop integration."""
424 config = self.master_config
425 config = self.master_config
425 try:
426 try:
426 # Enable GUI integration
427 # Enable GUI integration
427 if config.Global.wthread:
428 if config.Global.wthread:
428 self.log.info("Enabling wx GUI event loop integration")
429 self.log.info("Enabling wx GUI event loop integration")
429 inputhook.enable_wx(app=True)
430 inputhook.enable_wx(app=True)
430 elif config.Global.q4thread:
431 elif config.Global.q4thread:
431 self.log.info("Enabling Qt4 GUI event loop integration")
432 self.log.info("Enabling Qt4 GUI event loop integration")
432 inputhook.enable_qt4(app=True)
433 inputhook.enable_qt4(app=True)
433 elif config.Global.gthread:
434 elif config.Global.gthread:
434 self.log.info("Enabling GTK GUI event loop integration")
435 self.log.info("Enabling GTK GUI event loop integration")
435 inputhook.enable_gtk(app=True)
436 inputhook.enable_gtk(app=True)
436 except:
437 except:
437 self.log.warn("Error in enabling GUI event loop integration:")
438 self.log.warn("Error in enabling GUI event loop integration:")
438 self.shell.showtraceback()
439 self.shell.showtraceback()
439
440
440 def _load_extensions(self):
441 def _load_extensions(self):
441 """Load all IPython extensions in Global.extensions.
442 """Load all IPython extensions in Global.extensions.
442
443
443 This uses the :meth:`InteractiveShell.load_extensions` to load all
444 This uses the :meth:`InteractiveShell.load_extensions` to load all
444 the extensions listed in ``self.master_config.Global.extensions``.
445 the extensions listed in ``self.master_config.Global.extensions``.
445 """
446 """
446 try:
447 try:
447 if hasattr(self.master_config.Global, 'extensions'):
448 if hasattr(self.master_config.Global, 'extensions'):
448 self.log.debug("Loading IPython extensions...")
449 self.log.debug("Loading IPython extensions...")
449 extensions = self.master_config.Global.extensions
450 extensions = self.master_config.Global.extensions
450 for ext in extensions:
451 for ext in extensions:
451 try:
452 try:
452 self.log.info("Loading IPython extension: %s" % ext)
453 self.log.info("Loading IPython extension: %s" % ext)
453 self.shell.load_extension(ext)
454 self.shell.load_extension(ext)
454 except:
455 except:
455 self.log.warn("Error in loading extension: %s" % ext)
456 self.log.warn("Error in loading extension: %s" % ext)
456 self.shell.showtraceback()
457 self.shell.showtraceback()
457 except:
458 except:
458 self.log.warn("Unknown error in loading extensions:")
459 self.log.warn("Unknown error in loading extensions:")
459 self.shell.showtraceback()
460 self.shell.showtraceback()
460
461
461 def _run_exec_lines(self):
462 def _run_exec_lines(self):
462 """Run lines of code in Global.exec_lines in the user's namespace."""
463 """Run lines of code in Global.exec_lines in the user's namespace."""
463 try:
464 try:
464 if hasattr(self.master_config.Global, 'exec_lines'):
465 if hasattr(self.master_config.Global, 'exec_lines'):
465 self.log.debug("Running code from Global.exec_lines...")
466 self.log.debug("Running code from Global.exec_lines...")
466 exec_lines = self.master_config.Global.exec_lines
467 exec_lines = self.master_config.Global.exec_lines
467 for line in exec_lines:
468 for line in exec_lines:
468 try:
469 try:
469 self.log.info("Running code in user namespace: %s" % line)
470 self.log.info("Running code in user namespace: %s" % line)
470 self.shell.runlines(line)
471 self.shell.runlines(line)
471 except:
472 except:
472 self.log.warn("Error in executing line in user namespace: %s" % line)
473 self.log.warn("Error in executing line in user namespace: %s" % line)
473 self.shell.showtraceback()
474 self.shell.showtraceback()
474 except:
475 except:
475 self.log.warn("Unknown error in handling Global.exec_lines:")
476 self.log.warn("Unknown error in handling Global.exec_lines:")
476 self.shell.showtraceback()
477 self.shell.showtraceback()
477
478
478 def _exec_file(self, fname):
479 def _exec_file(self, fname):
479 full_filename = filefind(fname, ['.', self.ipythondir])
480 full_filename = filefind(fname, ['.', self.ipythondir])
480 if os.path.isfile(full_filename):
481 if os.path.isfile(full_filename):
481 if full_filename.endswith('.py'):
482 if full_filename.endswith('.py'):
482 self.log.info("Running file in user namespace: %s" % full_filename)
483 self.log.info("Running file in user namespace: %s" % full_filename)
483 self.shell.safe_execfile(full_filename, self.shell.user_ns)
484 self.shell.safe_execfile(full_filename, self.shell.user_ns)
484 elif full_filename.endswith('.ipy'):
485 elif full_filename.endswith('.ipy'):
485 self.log.info("Running file in user namespace: %s" % full_filename)
486 self.log.info("Running file in user namespace: %s" % full_filename)
486 self.shell.safe_execfile_ipy(full_filename)
487 self.shell.safe_execfile_ipy(full_filename)
487 else:
488 else:
488 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
489 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
489
490
490 def _run_exec_files(self):
491 def _run_exec_files(self):
491 try:
492 try:
492 if hasattr(self.master_config.Global, 'exec_files'):
493 if hasattr(self.master_config.Global, 'exec_files'):
493 self.log.debug("Running files in Global.exec_files...")
494 self.log.debug("Running files in Global.exec_files...")
494 exec_files = self.master_config.Global.exec_files
495 exec_files = self.master_config.Global.exec_files
495 for fname in exec_files:
496 for fname in exec_files:
496 self._exec_file(fname)
497 self._exec_file(fname)
497 except:
498 except:
498 self.log.warn("Unknown error in handling Global.exec_files:")
499 self.log.warn("Unknown error in handling Global.exec_files:")
499 self.shell.showtraceback()
500 self.shell.showtraceback()
500
501
501 def _run_cmd_line_code(self):
502 def _run_cmd_line_code(self):
502 if hasattr(self.master_config.Global, 'code_to_run'):
503 if hasattr(self.master_config.Global, 'code_to_run'):
503 line = self.master_config.Global.code_to_run
504 line = self.master_config.Global.code_to_run
504 try:
505 try:
505 self.log.info("Running code given at command line (-c): %s" % line)
506 self.log.info("Running code given at command line (-c): %s" % line)
506 self.shell.runlines(line)
507 self.shell.runlines(line)
507 except:
508 except:
508 self.log.warn("Error in executing line in user namespace: %s" % line)
509 self.log.warn("Error in executing line in user namespace: %s" % line)
509 self.shell.showtraceback()
510 self.shell.showtraceback()
510 return
511 return
511 # Like Python itself, ignore the second if the first of these is present
512 # Like Python itself, ignore the second if the first of these is present
512 try:
513 try:
513 fname = self.extra_args[0]
514 fname = self.extra_args[0]
514 except:
515 except:
515 pass
516 pass
516 else:
517 else:
517 try:
518 try:
518 self._exec_file(fname)
519 self._exec_file(fname)
519 except:
520 except:
520 self.log.warn("Error in executing file in user namespace: %s" % fname)
521 self.log.warn("Error in executing file in user namespace: %s" % fname)
521 self.shell.showtraceback()
522 self.shell.showtraceback()
522
523
523 def start_app(self):
524 def start_app(self):
524 if self.master_config.Global.interact:
525 if self.master_config.Global.interact:
525 self.log.debug("Starting IPython's mainloop...")
526 self.log.debug("Starting IPython's mainloop...")
526 self.shell.mainloop()
527 self.shell.mainloop()
527
528
528
529
529 def load_default_config(ipythondir=None):
530 def load_default_config(ipythondir=None):
530 """Load the default config file from the default ipythondir.
531 """Load the default config file from the default ipythondir.
531
532
532 This is useful for embedded shells.
533 This is useful for embedded shells.
533 """
534 """
534 if ipythondir is None:
535 if ipythondir is None:
535 ipythondir = get_ipython_dir()
536 ipythondir = get_ipython_dir()
536 cl = PyFileConfigLoader(_default_config_file_name, ipythondir)
537 cl = PyFileConfigLoader(_default_config_file_name, ipythondir)
537 config = cl.load_config()
538 config = cl.load_config()
538 return config
539 return config
539
540
540
541
541 def launch_new_instance():
542 def launch_new_instance():
542 """Create a run a full blown IPython instance"""
543 """Create a run a full blown IPython instance"""
543 app = IPythonApp()
544 app = IPythonApp()
544 app.start()
545 app.start()
545
546
General Comments 0
You need to be logged in to leave comments. Login now