##// END OF EJS Templates
exec_files works when specified in config file...
MinRK -
Show More
@@ -1,249 +1,253 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A mixin for :class:`~IPython.core.application.Application` classes that
4 A mixin for :class:`~IPython.core.application.Application` classes that
5 launch InteractiveShell instances, load extensions, etc.
5 launch InteractiveShell instances, load extensions, etc.
6
6
7 Authors
7 Authors
8 -------
8 -------
9
9
10 * Min Ragan-Kelley
10 * Min Ragan-Kelley
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 from __future__ import absolute_import
24 from __future__ import absolute_import
25
25
26 import os
26 import os
27 import sys
27 import sys
28
28
29 from IPython.config.application import boolean_flag
29 from IPython.config.application import boolean_flag
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.config.loader import Config
31 from IPython.config.loader import Config
32 from IPython.utils.path import filefind
32 from IPython.utils.path import filefind
33 from IPython.utils.traitlets import Unicode, Instance, List
33 from IPython.utils.traitlets import Unicode, Instance, List
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Aliases and Flags
36 # Aliases and Flags
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 shell_flags = {}
39 shell_flags = {}
40
40
41 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
41 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
42 addflag('autoindent', 'InteractiveShell.autoindent',
42 addflag('autoindent', 'InteractiveShell.autoindent',
43 'Turn on autoindenting.', 'Turn off autoindenting.'
43 'Turn on autoindenting.', 'Turn off autoindenting.'
44 )
44 )
45 addflag('automagic', 'InteractiveShell.automagic',
45 addflag('automagic', 'InteractiveShell.automagic',
46 """Turn on the auto calling of magic commands. Type %%magic at the
46 """Turn on the auto calling of magic commands. Type %%magic at the
47 IPython prompt for more information.""",
47 IPython prompt for more information.""",
48 'Turn off the auto calling of magic commands.'
48 'Turn off the auto calling of magic commands.'
49 )
49 )
50 addflag('pdb', 'InteractiveShell.pdb',
50 addflag('pdb', 'InteractiveShell.pdb',
51 "Enable auto calling the pdb debugger after every exception.",
51 "Enable auto calling the pdb debugger after every exception.",
52 "Disable auto calling the pdb debugger after every exception."
52 "Disable auto calling the pdb debugger after every exception."
53 )
53 )
54 addflag('pprint', 'PlainTextFormatter.pprint',
54 addflag('pprint', 'PlainTextFormatter.pprint',
55 "Enable auto pretty printing of results.",
55 "Enable auto pretty printing of results.",
56 "Disable auto auto pretty printing of results."
56 "Disable auto auto pretty printing of results."
57 )
57 )
58 addflag('color-info', 'InteractiveShell.color_info',
58 addflag('color-info', 'InteractiveShell.color_info',
59 """IPython can display information about objects via a set of func-
59 """IPython can display information about objects via a set of func-
60 tions, and optionally can use colors for this, syntax highlighting
60 tions, and optionally can use colors for this, syntax highlighting
61 source code and various other elements. However, because this
61 source code and various other elements. However, because this
62 information is passed through a pager (like 'less') and many pagers get
62 information is passed through a pager (like 'less') and many pagers get
63 confused with color codes, this option is off by default. You can test
63 confused with color codes, this option is off by default. You can test
64 it and turn it on permanently in your ipython_config.py file if it
64 it and turn it on permanently in your ipython_config.py file if it
65 works for you. Test it and turn it on permanently if it works with
65 works for you. Test it and turn it on permanently if it works with
66 your system. The magic function %%color_info allows you to toggle this
66 your system. The magic function %%color_info allows you to toggle this
67 interactively for testing.""",
67 interactively for testing.""",
68 "Disable using colors for info related things."
68 "Disable using colors for info related things."
69 )
69 )
70 addflag('deep-reload', 'InteractiveShell.deep_reload',
70 addflag('deep-reload', 'InteractiveShell.deep_reload',
71 """Enable deep (recursive) reloading by default. IPython can use the
71 """Enable deep (recursive) reloading by default. IPython can use the
72 deep_reload module which reloads changes in modules recursively (it
72 deep_reload module which reloads changes in modules recursively (it
73 replaces the reload() function, so you don't need to change anything to
73 replaces the reload() function, so you don't need to change anything to
74 use it). deep_reload() forces a full reload of modules whose code may
74 use it). deep_reload() forces a full reload of modules whose code may
75 have changed, which the default reload() function does not. When
75 have changed, which the default reload() function does not. When
76 deep_reload is off, IPython will use the normal reload(), but
76 deep_reload is off, IPython will use the normal reload(), but
77 deep_reload will still be available as dreload(). This feature is off
77 deep_reload will still be available as dreload(). This feature is off
78 by default [which means that you have both normal reload() and
78 by default [which means that you have both normal reload() and
79 dreload()].""",
79 dreload()].""",
80 "Disable deep (recursive) reloading by default."
80 "Disable deep (recursive) reloading by default."
81 )
81 )
82 nosep_config = Config()
82 nosep_config = Config()
83 nosep_config.InteractiveShell.separate_in = ''
83 nosep_config.InteractiveShell.separate_in = ''
84 nosep_config.InteractiveShell.separate_out = ''
84 nosep_config.InteractiveShell.separate_out = ''
85 nosep_config.InteractiveShell.separate_out2 = ''
85 nosep_config.InteractiveShell.separate_out2 = ''
86
86
87 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
87 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
88
88
89
89
90 # it's possible we don't want short aliases for *all* of these:
90 # it's possible we don't want short aliases for *all* of these:
91 shell_aliases = dict(
91 shell_aliases = dict(
92 autocall='InteractiveShell.autocall',
92 autocall='InteractiveShell.autocall',
93 cache_size='InteractiveShell.cache_size',
93 cache_size='InteractiveShell.cache_size',
94 colors='InteractiveShell.colors',
94 colors='InteractiveShell.colors',
95 logfile='InteractiveShell.logfile',
95 logfile='InteractiveShell.logfile',
96 logappend='InteractiveShell.logappend',
96 logappend='InteractiveShell.logappend',
97 c='InteractiveShellApp.code_to_run',
97 c='InteractiveShellApp.code_to_run',
98 ext='InteractiveShellApp.extra_extension',
98 ext='InteractiveShellApp.extra_extension',
99 )
99 )
100
100
101 #-----------------------------------------------------------------------------
101 #-----------------------------------------------------------------------------
102 # Main classes and functions
102 # Main classes and functions
103 #-----------------------------------------------------------------------------
103 #-----------------------------------------------------------------------------
104
104
105 class InteractiveShellApp(Configurable):
105 class InteractiveShellApp(Configurable):
106 """A Mixin for applications that start InteractiveShell instances.
106 """A Mixin for applications that start InteractiveShell instances.
107
107
108 Provides configurables for loading extensions and executing files
108 Provides configurables for loading extensions and executing files
109 as part of configuring a Shell environment.
109 as part of configuring a Shell environment.
110
110
111 Provides init_extensions() and init_code() methods, to be called
111 Provides init_extensions() and init_code() methods, to be called
112 after init_shell(), which must be implemented by subclasses.
112 after init_shell(), which must be implemented by subclasses.
113 """
113 """
114 extensions = List(Unicode, config=True,
114 extensions = List(Unicode, config=True,
115 help="A list of dotted module names of IPython extensions to load."
115 help="A list of dotted module names of IPython extensions to load."
116 )
116 )
117 extra_extension = Unicode('', config=True,
117 extra_extension = Unicode('', config=True,
118 help="dotted module name of an IPython extension to load."
118 help="dotted module name of an IPython extension to load."
119 )
119 )
120 def _extra_extension_changed(self, name, old, new):
120 def _extra_extension_changed(self, name, old, new):
121 if new:
121 if new:
122 # add to self.extensions
122 # add to self.extensions
123 self.extensions.append(new)
123 self.extensions.append(new)
124
124
125 exec_files = List(Unicode, config=True,
125 exec_files = List(Unicode, config=True,
126 help="""List of files to run at IPython startup."""
126 help="""List of files to run at IPython startup."""
127 )
127 )
128 file_to_run = Unicode('', config=True,
128 file_to_run = Unicode('', config=True,
129 help="""A file to be run""")
129 help="""A file to be run""")
130
130
131 exec_lines = List(Unicode, config=True,
131 exec_lines = List(Unicode, config=True,
132 help="""lines of code to run at IPython startup."""
132 help="""lines of code to run at IPython startup."""
133 )
133 )
134 code_to_run = Unicode('', config=True,
134 code_to_run = Unicode('', config=True,
135 help="Execute the given command string."
135 help="Execute the given command string."
136 )
136 )
137 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
137 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
138
138
139 def init_shell(self):
139 def init_shell(self):
140 raise NotImplementedError("Override in subclasses")
140 raise NotImplementedError("Override in subclasses")
141
141
142 def init_extensions(self):
142 def init_extensions(self):
143 """Load all IPython extensions in IPythonApp.extensions.
143 """Load all IPython extensions in IPythonApp.extensions.
144
144
145 This uses the :meth:`ExtensionManager.load_extensions` to load all
145 This uses the :meth:`ExtensionManager.load_extensions` to load all
146 the extensions listed in ``self.extensions``.
146 the extensions listed in ``self.extensions``.
147 """
147 """
148 if not self.extensions:
148 if not self.extensions:
149 return
149 return
150 try:
150 try:
151 self.log.debug("Loading IPython extensions...")
151 self.log.debug("Loading IPython extensions...")
152 extensions = self.extensions
152 extensions = self.extensions
153 for ext in extensions:
153 for ext in extensions:
154 try:
154 try:
155 self.log.info("Loading IPython extension: %s" % ext)
155 self.log.info("Loading IPython extension: %s" % ext)
156 self.shell.extension_manager.load_extension(ext)
156 self.shell.extension_manager.load_extension(ext)
157 except:
157 except:
158 self.log.warn("Error in loading extension: %s" % ext)
158 self.log.warn("Error in loading extension: %s" % ext)
159 self.shell.showtraceback()
159 self.shell.showtraceback()
160 except:
160 except:
161 self.log.warn("Unknown error in loading extensions:")
161 self.log.warn("Unknown error in loading extensions:")
162 self.shell.showtraceback()
162 self.shell.showtraceback()
163
163
164 def init_code(self):
164 def init_code(self):
165 """run the pre-flight code, specified via exec_lines"""
165 """run the pre-flight code, specified via exec_lines"""
166 self._run_exec_lines()
166 self._run_exec_lines()
167 self._run_exec_files()
167 self._run_exec_files()
168 self._run_cmd_line_code()
168 self._run_cmd_line_code()
169
169
170 def _run_exec_lines(self):
170 def _run_exec_lines(self):
171 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
171 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
172 if not self.exec_lines:
172 if not self.exec_lines:
173 return
173 return
174 try:
174 try:
175 self.log.debug("Running code from IPythonApp.exec_lines...")
175 self.log.debug("Running code from IPythonApp.exec_lines...")
176 for line in self.exec_lines:
176 for line in self.exec_lines:
177 try:
177 try:
178 self.log.info("Running code in user namespace: %s" %
178 self.log.info("Running code in user namespace: %s" %
179 line)
179 line)
180 self.shell.run_cell(line, store_history=False)
180 self.shell.run_cell(line, store_history=False)
181 except:
181 except:
182 self.log.warn("Error in executing line in user "
182 self.log.warn("Error in executing line in user "
183 "namespace: %s" % line)
183 "namespace: %s" % line)
184 self.shell.showtraceback()
184 self.shell.showtraceback()
185 except:
185 except:
186 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
186 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
187 self.shell.showtraceback()
187 self.shell.showtraceback()
188
188
189 def _exec_file(self, fname):
189 def _exec_file(self, fname):
190 try:
190 full_filename = filefind(fname, [u'.', self.ipython_dir])
191 full_filename = filefind(fname, [u'.', self.ipython_dir])
192 except IOError as e:
193 self.log.warn("File not found: %r"%fname)
194 return
191 # Make sure that the running script gets a proper sys.argv as if it
195 # Make sure that the running script gets a proper sys.argv as if it
192 # were run from a system shell.
196 # were run from a system shell.
193 save_argv = sys.argv
197 save_argv = sys.argv
194 sys.argv = sys.argv[sys.argv.index(fname):]
198 sys.argv = [full_filename] + self.extra_args[1:]
195 try:
199 try:
196 if os.path.isfile(full_filename):
200 if os.path.isfile(full_filename):
197 if full_filename.endswith('.ipy'):
201 if full_filename.endswith('.ipy'):
198 self.log.info("Running file in user namespace: %s" %
202 self.log.info("Running file in user namespace: %s" %
199 full_filename)
203 full_filename)
200 self.shell.safe_execfile_ipy(full_filename)
204 self.shell.safe_execfile_ipy(full_filename)
201 else:
205 else:
202 # default to python, even without extension
206 # default to python, even without extension
203 self.log.info("Running file in user namespace: %s" %
207 self.log.info("Running file in user namespace: %s" %
204 full_filename)
208 full_filename)
205 # Ensure that __file__ is always defined to match Python behavior
209 # Ensure that __file__ is always defined to match Python behavior
206 self.shell.user_ns['__file__'] = fname
210 self.shell.user_ns['__file__'] = fname
207 try:
211 try:
208 self.shell.safe_execfile(full_filename, self.shell.user_ns)
212 self.shell.safe_execfile(full_filename, self.shell.user_ns)
209 finally:
213 finally:
210 del self.shell.user_ns['__file__']
214 del self.shell.user_ns['__file__']
211 finally:
215 finally:
212 sys.argv = save_argv
216 sys.argv = save_argv
213
217
214 def _run_exec_files(self):
218 def _run_exec_files(self):
215 """Run files from IPythonApp.exec_files"""
219 """Run files from IPythonApp.exec_files"""
216 if not self.exec_files:
220 if not self.exec_files:
217 return
221 return
218
222
219 self.log.debug("Running files in IPythonApp.exec_files...")
223 self.log.debug("Running files in IPythonApp.exec_files...")
220 try:
224 try:
221 for fname in self.exec_files:
225 for fname in self.exec_files:
222 self._exec_file(fname)
226 self._exec_file(fname)
223 except:
227 except:
224 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
228 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
225 self.shell.showtraceback()
229 self.shell.showtraceback()
226
230
227 def _run_cmd_line_code(self):
231 def _run_cmd_line_code(self):
228 """Run code or file specified at the command-line"""
232 """Run code or file specified at the command-line"""
229 if self.code_to_run:
233 if self.code_to_run:
230 line = self.code_to_run
234 line = self.code_to_run
231 try:
235 try:
232 self.log.info("Running code given at command line (c=): %s" %
236 self.log.info("Running code given at command line (c=): %s" %
233 line)
237 line)
234 self.shell.run_cell(line, store_history=False)
238 self.shell.run_cell(line, store_history=False)
235 except:
239 except:
236 self.log.warn("Error in executing line in user namespace: %s" %
240 self.log.warn("Error in executing line in user namespace: %s" %
237 line)
241 line)
238 self.shell.showtraceback()
242 self.shell.showtraceback()
239
243
240 # Like Python itself, ignore the second if the first of these is present
244 # Like Python itself, ignore the second if the first of these is present
241 elif self.file_to_run:
245 elif self.file_to_run:
242 fname = self.file_to_run
246 fname = self.file_to_run
243 try:
247 try:
244 self._exec_file(fname)
248 self._exec_file(fname)
245 except:
249 except:
246 self.log.warn("Error in executing file in user namespace: %s" %
250 self.log.warn("Error in executing file in user namespace: %s" %
247 fname)
251 fname)
248 self.shell.showtraceback()
252 self.shell.showtraceback()
249
253
General Comments 0
You need to be logged in to leave comments. Login now