Show More
@@ -1,360 +1,357 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | A mixin for :class:`~IPython.core.application.Application` classes that |
|
3 | A mixin for :class:`~IPython.core.application.Application` classes that | |
4 | launch InteractiveShell instances, load extensions, etc. |
|
4 | launch InteractiveShell instances, load extensions, etc. | |
5 |
|
5 | |||
6 | Authors |
|
6 | Authors | |
7 | ------- |
|
7 | ------- | |
8 |
|
8 | |||
9 | * Min Ragan-Kelley |
|
9 | * Min Ragan-Kelley | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2011 The IPython Development Team |
|
13 | # Copyright (C) 2008-2011 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | from __future__ import absolute_import |
|
23 | from __future__ import absolute_import | |
24 |
|
24 | |||
25 | import glob |
|
25 | import glob | |
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.core import pylabtools |
|
32 | from IPython.core import pylabtools | |
33 | from IPython.utils import py3compat |
|
33 | from IPython.utils import py3compat | |
34 | from IPython.utils.path import filefind |
|
34 | from IPython.utils.path import filefind | |
35 | from IPython.utils.traitlets import ( |
|
35 | from IPython.utils.traitlets import ( | |
36 | Unicode, Instance, List, Bool, CaselessStrEnum |
|
36 | Unicode, Instance, List, Bool, CaselessStrEnum | |
37 | ) |
|
37 | ) | |
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Aliases and Flags |
|
40 | # Aliases and Flags | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 |
|
42 | |||
43 | shell_flags = {} |
|
43 | shell_flags = {} | |
44 |
|
44 | |||
45 | addflag = lambda *args: shell_flags.update(boolean_flag(*args)) |
|
45 | addflag = lambda *args: shell_flags.update(boolean_flag(*args)) | |
46 | addflag('autoindent', 'InteractiveShell.autoindent', |
|
46 | addflag('autoindent', 'InteractiveShell.autoindent', | |
47 | 'Turn on autoindenting.', 'Turn off autoindenting.' |
|
47 | 'Turn on autoindenting.', 'Turn off autoindenting.' | |
48 | ) |
|
48 | ) | |
49 | addflag('automagic', 'InteractiveShell.automagic', |
|
49 | addflag('automagic', 'InteractiveShell.automagic', | |
50 | """Turn on the auto calling of magic commands. Type %%magic at the |
|
50 | """Turn on the auto calling of magic commands. Type %%magic at the | |
51 | IPython prompt for more information.""", |
|
51 | IPython prompt for more information.""", | |
52 | 'Turn off the auto calling of magic commands.' |
|
52 | 'Turn off the auto calling of magic commands.' | |
53 | ) |
|
53 | ) | |
54 | addflag('pdb', 'InteractiveShell.pdb', |
|
54 | addflag('pdb', 'InteractiveShell.pdb', | |
55 | "Enable auto calling the pdb debugger after every exception.", |
|
55 | "Enable auto calling the pdb debugger after every exception.", | |
56 | "Disable auto calling the pdb debugger after every exception." |
|
56 | "Disable auto calling the pdb debugger after every exception." | |
57 | ) |
|
57 | ) | |
58 | # pydb flag doesn't do any config, as core.debugger switches on import, |
|
58 | # pydb flag doesn't do any config, as core.debugger switches on import, | |
59 | # which is before parsing. This just allows the flag to be passed. |
|
59 | # which is before parsing. This just allows the flag to be passed. | |
60 | shell_flags.update(dict( |
|
60 | shell_flags.update(dict( | |
61 | pydb = ({}, |
|
61 | pydb = ({}, | |
62 | """Use the third party 'pydb' package as debugger, instead of pdb. |
|
62 | """Use the third party 'pydb' package as debugger, instead of pdb. | |
63 | Requires that pydb is installed.""" |
|
63 | Requires that pydb is installed.""" | |
64 | ) |
|
64 | ) | |
65 | )) |
|
65 | )) | |
66 | addflag('pprint', 'PlainTextFormatter.pprint', |
|
66 | addflag('pprint', 'PlainTextFormatter.pprint', | |
67 | "Enable auto pretty printing of results.", |
|
67 | "Enable auto pretty printing of results.", | |
68 | "Disable auto auto pretty printing of results." |
|
68 | "Disable auto auto pretty printing of results." | |
69 | ) |
|
69 | ) | |
70 | addflag('color-info', 'InteractiveShell.color_info', |
|
70 | addflag('color-info', 'InteractiveShell.color_info', | |
71 | """IPython can display information about objects via a set of func- |
|
71 | """IPython can display information about objects via a set of func- | |
72 | tions, and optionally can use colors for this, syntax highlighting |
|
72 | tions, and optionally can use colors for this, syntax highlighting | |
73 | source code and various other elements. However, because this |
|
73 | source code and various other elements. However, because this | |
74 | information is passed through a pager (like 'less') and many pagers get |
|
74 | information is passed through a pager (like 'less') and many pagers get | |
75 | confused with color codes, this option is off by default. You can test |
|
75 | confused with color codes, this option is off by default. You can test | |
76 | it and turn it on permanently in your ipython_config.py file if it |
|
76 | it and turn it on permanently in your ipython_config.py file if it | |
77 | works for you. Test it and turn it on permanently if it works with |
|
77 | works for you. Test it and turn it on permanently if it works with | |
78 | your system. The magic function %%color_info allows you to toggle this |
|
78 | your system. The magic function %%color_info allows you to toggle this | |
79 | interactively for testing.""", |
|
79 | interactively for testing.""", | |
80 | "Disable using colors for info related things." |
|
80 | "Disable using colors for info related things." | |
81 | ) |
|
81 | ) | |
82 | addflag('deep-reload', 'InteractiveShell.deep_reload', |
|
82 | addflag('deep-reload', 'InteractiveShell.deep_reload', | |
83 | """Enable deep (recursive) reloading by default. IPython can use the |
|
83 | """Enable deep (recursive) reloading by default. IPython can use the | |
84 | deep_reload module which reloads changes in modules recursively (it |
|
84 | deep_reload module which reloads changes in modules recursively (it | |
85 | replaces the reload() function, so you don't need to change anything to |
|
85 | replaces the reload() function, so you don't need to change anything to | |
86 | use it). deep_reload() forces a full reload of modules whose code may |
|
86 | use it). deep_reload() forces a full reload of modules whose code may | |
87 | have changed, which the default reload() function does not. When |
|
87 | have changed, which the default reload() function does not. When | |
88 | deep_reload is off, IPython will use the normal reload(), but |
|
88 | deep_reload is off, IPython will use the normal reload(), but | |
89 | deep_reload will still be available as dreload(). This feature is off |
|
89 | deep_reload will still be available as dreload(). This feature is off | |
90 | by default [which means that you have both normal reload() and |
|
90 | by default [which means that you have both normal reload() and | |
91 | dreload()].""", |
|
91 | dreload()].""", | |
92 | "Disable deep (recursive) reloading by default." |
|
92 | "Disable deep (recursive) reloading by default." | |
93 | ) |
|
93 | ) | |
94 | nosep_config = Config() |
|
94 | nosep_config = Config() | |
95 | nosep_config.InteractiveShell.separate_in = '' |
|
95 | nosep_config.InteractiveShell.separate_in = '' | |
96 | nosep_config.InteractiveShell.separate_out = '' |
|
96 | nosep_config.InteractiveShell.separate_out = '' | |
97 | nosep_config.InteractiveShell.separate_out2 = '' |
|
97 | nosep_config.InteractiveShell.separate_out2 = '' | |
98 |
|
98 | |||
99 | shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.") |
|
99 | shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.") | |
100 | shell_flags['pylab'] = ( |
|
100 | shell_flags['pylab'] = ( | |
101 | {'InteractiveShellApp' : {'pylab' : 'auto'}}, |
|
101 | {'InteractiveShellApp' : {'pylab' : 'auto'}}, | |
102 | """Pre-load matplotlib and numpy for interactive use with |
|
102 | """Pre-load matplotlib and numpy for interactive use with | |
103 | the default matplotlib backend.""" |
|
103 | the default matplotlib backend.""" | |
104 | ) |
|
104 | ) | |
105 |
|
105 | |||
106 | # it's possible we don't want short aliases for *all* of these: |
|
106 | # it's possible we don't want short aliases for *all* of these: | |
107 | shell_aliases = dict( |
|
107 | shell_aliases = dict( | |
108 | autocall='InteractiveShell.autocall', |
|
108 | autocall='InteractiveShell.autocall', | |
109 | colors='InteractiveShell.colors', |
|
109 | colors='InteractiveShell.colors', | |
110 | logfile='InteractiveShell.logfile', |
|
110 | logfile='InteractiveShell.logfile', | |
111 | logappend='InteractiveShell.logappend', |
|
111 | logappend='InteractiveShell.logappend', | |
112 | c='InteractiveShellApp.code_to_run', |
|
112 | c='InteractiveShellApp.code_to_run', | |
113 | m='InteractiveShellApp.module_to_run', |
|
113 | m='InteractiveShellApp.module_to_run', | |
114 | ext='InteractiveShellApp.extra_extension', |
|
114 | ext='InteractiveShellApp.extra_extension', | |
115 | gui='InteractiveShellApp.gui', |
|
115 | gui='InteractiveShellApp.gui', | |
116 | pylab='InteractiveShellApp.pylab', |
|
116 | pylab='InteractiveShellApp.pylab', | |
117 | ) |
|
117 | ) | |
118 | shell_aliases['cache-size'] = 'InteractiveShell.cache_size' |
|
118 | shell_aliases['cache-size'] = 'InteractiveShell.cache_size' | |
119 |
|
119 | |||
120 | #----------------------------------------------------------------------------- |
|
120 | #----------------------------------------------------------------------------- | |
121 | # Main classes and functions |
|
121 | # Main classes and functions | |
122 | #----------------------------------------------------------------------------- |
|
122 | #----------------------------------------------------------------------------- | |
123 |
|
123 | |||
124 | class InteractiveShellApp(Configurable): |
|
124 | class InteractiveShellApp(Configurable): | |
125 | """A Mixin for applications that start InteractiveShell instances. |
|
125 | """A Mixin for applications that start InteractiveShell instances. | |
126 |
|
126 | |||
127 | Provides configurables for loading extensions and executing files |
|
127 | Provides configurables for loading extensions and executing files | |
128 | as part of configuring a Shell environment. |
|
128 | as part of configuring a Shell environment. | |
129 |
|
129 | |||
130 | The following methods should be called by the :meth:`initialize` method |
|
130 | The following methods should be called by the :meth:`initialize` method | |
131 | of the subclass: |
|
131 | of the subclass: | |
132 |
|
132 | |||
133 | - :meth:`init_path` |
|
133 | - :meth:`init_path` | |
134 | - :meth:`init_shell` (to be implemented by the subclass) |
|
134 | - :meth:`init_shell` (to be implemented by the subclass) | |
135 | - :meth:`init_gui_pylab` |
|
135 | - :meth:`init_gui_pylab` | |
136 | - :meth:`init_extensions` |
|
136 | - :meth:`init_extensions` | |
137 | - :meth:`init_code` |
|
137 | - :meth:`init_code` | |
138 | """ |
|
138 | """ | |
139 | extensions = List(Unicode, config=True, |
|
139 | extensions = List(Unicode, config=True, | |
140 | help="A list of dotted module names of IPython extensions to load." |
|
140 | help="A list of dotted module names of IPython extensions to load." | |
141 | ) |
|
141 | ) | |
142 | extra_extension = Unicode('', config=True, |
|
142 | extra_extension = Unicode('', config=True, | |
143 | help="dotted module name of an IPython extension to load." |
|
143 | help="dotted module name of an IPython extension to load." | |
144 | ) |
|
144 | ) | |
145 | def _extra_extension_changed(self, name, old, new): |
|
145 | def _extra_extension_changed(self, name, old, new): | |
146 | if new: |
|
146 | if new: | |
147 | # add to self.extensions |
|
147 | # add to self.extensions | |
148 | self.extensions.append(new) |
|
148 | self.extensions.append(new) | |
149 |
|
149 | |||
150 | # Extensions that are always loaded (not configurable) |
|
150 | # Extensions that are always loaded (not configurable) | |
151 | default_extensions = List(Unicode, [u'storemagic'], config=False) |
|
151 | default_extensions = List(Unicode, [u'storemagic'], config=False) | |
152 |
|
152 | |||
153 | exec_files = List(Unicode, config=True, |
|
153 | exec_files = List(Unicode, config=True, | |
154 | help="""List of files to run at IPython startup.""" |
|
154 | help="""List of files to run at IPython startup.""" | |
155 | ) |
|
155 | ) | |
156 | file_to_run = Unicode('', config=True, |
|
156 | file_to_run = Unicode('', config=True, | |
157 | help="""A file to be run""") |
|
157 | help="""A file to be run""") | |
158 |
|
158 | |||
159 | exec_lines = List(Unicode, config=True, |
|
159 | exec_lines = List(Unicode, config=True, | |
160 | help="""lines of code to run at IPython startup.""" |
|
160 | help="""lines of code to run at IPython startup.""" | |
161 | ) |
|
161 | ) | |
162 | code_to_run = Unicode('', config=True, |
|
162 | code_to_run = Unicode('', config=True, | |
163 | help="Execute the given command string." |
|
163 | help="Execute the given command string." | |
164 | ) |
|
164 | ) | |
165 | module_to_run = Unicode('', config=True, |
|
165 | module_to_run = Unicode('', config=True, | |
166 | help="Run the module as a script." |
|
166 | help="Run the module as a script." | |
167 | ) |
|
167 | ) | |
168 | gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx'), config=True, |
|
168 | gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx'), config=True, | |
169 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx')." |
|
169 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx')." | |
170 | ) |
|
170 | ) | |
171 | pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'], |
|
171 | pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'], | |
172 | config=True, |
|
172 | config=True, | |
173 | help="""Pre-load matplotlib and numpy for interactive use, |
|
173 | help="""Pre-load matplotlib and numpy for interactive use, | |
174 | selecting a particular matplotlib backend and loop integration. |
|
174 | selecting a particular matplotlib backend and loop integration. | |
175 | """ |
|
175 | """ | |
176 | ) |
|
176 | ) | |
177 | pylab_import_all = Bool(True, config=True, |
|
177 | pylab_import_all = Bool(True, config=True, | |
178 | help="""If true, an 'import *' is done from numpy and pylab, |
|
178 | help="""If true, an 'import *' is done from numpy and pylab, | |
179 | when using pylab""" |
|
179 | when using pylab""" | |
180 | ) |
|
180 | ) | |
181 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
181 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
182 |
|
182 | |||
183 | def init_path(self): |
|
183 | def init_path(self): | |
184 | """Add current working directory, '', to sys.path""" |
|
184 | """Add current working directory, '', to sys.path""" | |
185 | if sys.path[0] != '': |
|
185 | if sys.path[0] != '': | |
186 | sys.path.insert(0, '') |
|
186 | sys.path.insert(0, '') | |
187 |
|
187 | |||
188 | def init_shell(self): |
|
188 | def init_shell(self): | |
189 | raise NotImplementedError("Override in subclasses") |
|
189 | raise NotImplementedError("Override in subclasses") | |
190 |
|
190 | |||
191 | def init_gui_pylab(self): |
|
191 | def init_gui_pylab(self): | |
192 | """Enable GUI event loop integration, taking pylab into account.""" |
|
192 | """Enable GUI event loop integration, taking pylab into account.""" | |
193 | if self.gui or self.pylab: |
|
193 | if self.gui or self.pylab: | |
194 | shell = self.shell |
|
194 | shell = self.shell | |
195 | try: |
|
195 | try: | |
196 | if self.pylab: |
|
196 | if self.pylab: | |
197 | gui, backend = pylabtools.find_gui_and_backend(self.pylab) |
|
197 | gui, backend = pylabtools.find_gui_and_backend(self.pylab) | |
198 | self.log.info("Enabling GUI event loop integration, " |
|
198 | self.log.info("Enabling GUI event loop integration, " | |
199 | "toolkit=%s, pylab=%s" % (gui, self.pylab)) |
|
199 | "toolkit=%s, pylab=%s" % (gui, self.pylab)) | |
200 | shell.enable_pylab(gui, import_all=self.pylab_import_all) |
|
200 | shell.enable_pylab(gui, import_all=self.pylab_import_all) | |
201 | else: |
|
201 | else: | |
202 | self.log.info("Enabling GUI event loop integration, " |
|
202 | self.log.info("Enabling GUI event loop integration, " | |
203 | "toolkit=%s" % self.gui) |
|
203 | "toolkit=%s" % self.gui) | |
204 | shell.enable_gui(self.gui) |
|
204 | shell.enable_gui(self.gui) | |
205 | except Exception: |
|
205 | except Exception: | |
206 | self.log.warn("GUI event loop or pylab initialization failed") |
|
206 | self.log.warn("GUI event loop or pylab initialization failed") | |
207 | self.shell.showtraceback() |
|
207 | self.shell.showtraceback() | |
208 |
|
208 | |||
209 | def init_extensions(self): |
|
209 | def init_extensions(self): | |
210 | """Load all IPython extensions in IPythonApp.extensions. |
|
210 | """Load all IPython extensions in IPythonApp.extensions. | |
211 |
|
211 | |||
212 | This uses the :meth:`ExtensionManager.load_extensions` to load all |
|
212 | This uses the :meth:`ExtensionManager.load_extensions` to load all | |
213 | the extensions listed in ``self.extensions``. |
|
213 | the extensions listed in ``self.extensions``. | |
214 | """ |
|
214 | """ | |
215 | try: |
|
215 | try: | |
216 | self.log.debug("Loading IPython extensions...") |
|
216 | self.log.debug("Loading IPython extensions...") | |
217 | extensions = self.default_extensions + self.extensions |
|
217 | extensions = self.default_extensions + self.extensions | |
218 | for ext in extensions: |
|
218 | for ext in extensions: | |
219 | try: |
|
219 | try: | |
220 | self.log.info("Loading IPython extension: %s" % ext) |
|
220 | self.log.info("Loading IPython extension: %s" % ext) | |
221 | self.shell.extension_manager.load_extension(ext) |
|
221 | self.shell.extension_manager.load_extension(ext) | |
222 | except: |
|
222 | except: | |
223 | self.log.warn("Error in loading extension: %s" % ext + |
|
223 | self.log.warn("Error in loading extension: %s" % ext + | |
224 | "\nCheck your config files in %s" % self.profile_dir.location |
|
224 | "\nCheck your config files in %s" % self.profile_dir.location | |
225 | ) |
|
225 | ) | |
226 | self.shell.showtraceback() |
|
226 | self.shell.showtraceback() | |
227 | except: |
|
227 | except: | |
228 | self.log.warn("Unknown error in loading extensions:") |
|
228 | self.log.warn("Unknown error in loading extensions:") | |
229 | self.shell.showtraceback() |
|
229 | self.shell.showtraceback() | |
230 |
|
230 | |||
231 | def init_code(self): |
|
231 | def init_code(self): | |
232 | """run the pre-flight code, specified via exec_lines""" |
|
232 | """run the pre-flight code, specified via exec_lines""" | |
233 | self._run_startup_files() |
|
233 | self._run_startup_files() | |
234 | self._run_exec_lines() |
|
234 | self._run_exec_lines() | |
235 | self._run_exec_files() |
|
235 | self._run_exec_files() | |
236 | self._run_cmd_line_code() |
|
236 | self._run_cmd_line_code() | |
237 | self._run_module() |
|
237 | self._run_module() | |
238 |
|
238 | |||
239 | # flush output, so itwon't be attached to the first cell |
|
239 | # flush output, so itwon't be attached to the first cell | |
240 | sys.stdout.flush() |
|
240 | sys.stdout.flush() | |
241 | sys.stderr.flush() |
|
241 | sys.stderr.flush() | |
242 |
|
242 | |||
243 | # Hide variables defined here from %who etc. |
|
243 | # Hide variables defined here from %who etc. | |
244 | self.shell.user_ns_hidden.update(self.shell.user_ns) |
|
244 | self.shell.user_ns_hidden.update(self.shell.user_ns) | |
245 |
|
245 | |||
246 | def _run_exec_lines(self): |
|
246 | def _run_exec_lines(self): | |
247 | """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" |
|
247 | """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" | |
248 | if not self.exec_lines: |
|
248 | if not self.exec_lines: | |
249 | return |
|
249 | return | |
250 | try: |
|
250 | try: | |
251 | self.log.debug("Running code from IPythonApp.exec_lines...") |
|
251 | self.log.debug("Running code from IPythonApp.exec_lines...") | |
252 | for line in self.exec_lines: |
|
252 | for line in self.exec_lines: | |
253 | try: |
|
253 | try: | |
254 | self.log.info("Running code in user namespace: %s" % |
|
254 | self.log.info("Running code in user namespace: %s" % | |
255 | line) |
|
255 | line) | |
256 | self.shell.run_cell(line, store_history=False) |
|
256 | self.shell.run_cell(line, store_history=False) | |
257 | except: |
|
257 | except: | |
258 | self.log.warn("Error in executing line in user " |
|
258 | self.log.warn("Error in executing line in user " | |
259 | "namespace: %s" % line) |
|
259 | "namespace: %s" % line) | |
260 | self.shell.showtraceback() |
|
260 | self.shell.showtraceback() | |
261 | except: |
|
261 | except: | |
262 | self.log.warn("Unknown error in handling IPythonApp.exec_lines:") |
|
262 | self.log.warn("Unknown error in handling IPythonApp.exec_lines:") | |
263 | self.shell.showtraceback() |
|
263 | self.shell.showtraceback() | |
264 |
|
264 | |||
265 | def _exec_file(self, fname): |
|
265 | def _exec_file(self, fname): | |
266 | try: |
|
266 | try: | |
267 | full_filename = filefind(fname, [u'.', self.ipython_dir]) |
|
267 | full_filename = filefind(fname, [u'.', self.ipython_dir]) | |
268 | except IOError as e: |
|
268 | except IOError as e: | |
269 | self.log.warn("File not found: %r"%fname) |
|
269 | self.log.warn("File not found: %r"%fname) | |
270 | return |
|
270 | return | |
271 | # Make sure that the running script gets a proper sys.argv as if it |
|
271 | # Make sure that the running script gets a proper sys.argv as if it | |
272 | # were run from a system shell. |
|
272 | # were run from a system shell. | |
273 | save_argv = sys.argv |
|
273 | save_argv = sys.argv | |
274 | sys.argv = [full_filename] + self.extra_args[1:] |
|
274 | sys.argv = [full_filename] + self.extra_args[1:] | |
275 | # protect sys.argv from potential unicode strings on Python 2: |
|
275 | # protect sys.argv from potential unicode strings on Python 2: | |
276 | if not py3compat.PY3: |
|
276 | if not py3compat.PY3: | |
277 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
277 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
278 | try: |
|
278 | try: | |
279 | if os.path.isfile(full_filename): |
|
279 | if os.path.isfile(full_filename): | |
|
280 | self.log.info("Running file in user namespace: %s" % full_filename) | |||
|
281 | # Ensure that __file__ is always defined to match Python behavior | |||
|
282 | self.shell.user_ns['__file__'] = fname | |||
|
283 | try: | |||
280 | if full_filename.endswith('.ipy'): |
|
284 | if full_filename.endswith('.ipy'): | |
281 | self.log.info("Running file in user namespace: %s" % |
|
|||
282 | full_filename) |
|
|||
283 | self.shell.safe_execfile_ipy(full_filename) |
|
285 | self.shell.safe_execfile_ipy(full_filename) | |
284 | else: |
|
286 | else: | |
285 | # default to python, even without extension |
|
287 | # default to python, even without extension | |
286 | self.log.info("Running file in user namespace: %s" % |
|
|||
287 | full_filename) |
|
|||
288 | # Ensure that __file__ is always defined to match Python behavior |
|
|||
289 | self.shell.user_ns['__file__'] = fname |
|
|||
290 | try: |
|
|||
291 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
288 | self.shell.safe_execfile(full_filename, self.shell.user_ns) | |
292 |
|
|
289 | finally: | |
293 |
|
|
290 | del self.shell.user_ns['__file__'] | |
294 | finally: |
|
291 | finally: | |
295 | sys.argv = save_argv |
|
292 | sys.argv = save_argv | |
296 |
|
293 | |||
297 | def _run_startup_files(self): |
|
294 | def _run_startup_files(self): | |
298 | """Run files from profile startup directory""" |
|
295 | """Run files from profile startup directory""" | |
299 | startup_dir = self.profile_dir.startup_dir |
|
296 | startup_dir = self.profile_dir.startup_dir | |
300 | startup_files = glob.glob(os.path.join(startup_dir, '*.py')) |
|
297 | startup_files = glob.glob(os.path.join(startup_dir, '*.py')) | |
301 | startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) |
|
298 | startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) | |
302 | if not startup_files: |
|
299 | if not startup_files: | |
303 | return |
|
300 | return | |
304 |
|
301 | |||
305 | self.log.debug("Running startup files from %s...", startup_dir) |
|
302 | self.log.debug("Running startup files from %s...", startup_dir) | |
306 | try: |
|
303 | try: | |
307 | for fname in sorted(startup_files): |
|
304 | for fname in sorted(startup_files): | |
308 | self._exec_file(fname) |
|
305 | self._exec_file(fname) | |
309 | except: |
|
306 | except: | |
310 | self.log.warn("Unknown error in handling startup files:") |
|
307 | self.log.warn("Unknown error in handling startup files:") | |
311 | self.shell.showtraceback() |
|
308 | self.shell.showtraceback() | |
312 |
|
309 | |||
313 | def _run_exec_files(self): |
|
310 | def _run_exec_files(self): | |
314 | """Run files from IPythonApp.exec_files""" |
|
311 | """Run files from IPythonApp.exec_files""" | |
315 | if not self.exec_files: |
|
312 | if not self.exec_files: | |
316 | return |
|
313 | return | |
317 |
|
314 | |||
318 | self.log.debug("Running files in IPythonApp.exec_files...") |
|
315 | self.log.debug("Running files in IPythonApp.exec_files...") | |
319 | try: |
|
316 | try: | |
320 | for fname in self.exec_files: |
|
317 | for fname in self.exec_files: | |
321 | self._exec_file(fname) |
|
318 | self._exec_file(fname) | |
322 | except: |
|
319 | except: | |
323 | self.log.warn("Unknown error in handling IPythonApp.exec_files:") |
|
320 | self.log.warn("Unknown error in handling IPythonApp.exec_files:") | |
324 | self.shell.showtraceback() |
|
321 | self.shell.showtraceback() | |
325 |
|
322 | |||
326 | def _run_cmd_line_code(self): |
|
323 | def _run_cmd_line_code(self): | |
327 | """Run code or file specified at the command-line""" |
|
324 | """Run code or file specified at the command-line""" | |
328 | if self.code_to_run: |
|
325 | if self.code_to_run: | |
329 | line = self.code_to_run |
|
326 | line = self.code_to_run | |
330 | try: |
|
327 | try: | |
331 | self.log.info("Running code given at command line (c=): %s" % |
|
328 | self.log.info("Running code given at command line (c=): %s" % | |
332 | line) |
|
329 | line) | |
333 | self.shell.run_cell(line, store_history=False) |
|
330 | self.shell.run_cell(line, store_history=False) | |
334 | except: |
|
331 | except: | |
335 | self.log.warn("Error in executing line in user namespace: %s" % |
|
332 | self.log.warn("Error in executing line in user namespace: %s" % | |
336 | line) |
|
333 | line) | |
337 | self.shell.showtraceback() |
|
334 | self.shell.showtraceback() | |
338 |
|
335 | |||
339 | # Like Python itself, ignore the second if the first of these is present |
|
336 | # Like Python itself, ignore the second if the first of these is present | |
340 | elif self.file_to_run: |
|
337 | elif self.file_to_run: | |
341 | fname = self.file_to_run |
|
338 | fname = self.file_to_run | |
342 | try: |
|
339 | try: | |
343 | self._exec_file(fname) |
|
340 | self._exec_file(fname) | |
344 | except: |
|
341 | except: | |
345 | self.log.warn("Error in executing file in user namespace: %s" % |
|
342 | self.log.warn("Error in executing file in user namespace: %s" % | |
346 | fname) |
|
343 | fname) | |
347 | self.shell.showtraceback() |
|
344 | self.shell.showtraceback() | |
348 |
|
345 | |||
349 | def _run_module(self): |
|
346 | def _run_module(self): | |
350 | """Run module specified at the command-line.""" |
|
347 | """Run module specified at the command-line.""" | |
351 | if self.module_to_run: |
|
348 | if self.module_to_run: | |
352 | # Make sure that the module gets a proper sys.argv as if it were |
|
349 | # Make sure that the module gets a proper sys.argv as if it were | |
353 | # run using `python -m`. |
|
350 | # run using `python -m`. | |
354 | save_argv = sys.argv |
|
351 | save_argv = sys.argv | |
355 | sys.argv = [sys.executable] + self.extra_args |
|
352 | sys.argv = [sys.executable] + self.extra_args | |
356 | try: |
|
353 | try: | |
357 | self.shell.safe_run_module(self.module_to_run, |
|
354 | self.shell.safe_run_module(self.module_to_run, | |
358 | self.shell.user_ns) |
|
355 | self.shell.user_ns) | |
359 | finally: |
|
356 | finally: | |
360 | sys.argv = save_argv |
|
357 | sys.argv = save_argv |
General Comments 0
You need to be logged in to leave comments.
Login now