Show More
@@ -1,664 +1,665 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The :class:`~IPython.core.application.Application` object for the command |
|
4 | The :class:`~IPython.core.application.Application` object for the command | |
5 | line :command:`ipython` program. |
|
5 | line :command:`ipython` program. | |
6 |
|
6 | |||
7 | Authors |
|
7 | Authors | |
8 | ------- |
|
8 | ------- | |
9 |
|
9 | |||
10 | * Brian Granger |
|
10 | * Brian Granger | |
11 | * Fernando Perez |
|
11 | * Fernando Perez | |
12 | """ |
|
12 | """ | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Copyright (C) 2008-2010 The IPython Development Team |
|
15 | # Copyright (C) 2008-2010 The IPython Development Team | |
16 | # |
|
16 | # | |
17 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
18 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 | # Imports |
|
22 | # Imports | |
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 |
|
24 | |||
25 | from __future__ import absolute_import |
|
25 | from __future__ import absolute_import | |
26 |
|
26 | |||
27 | import logging |
|
27 | import logging | |
28 | import os |
|
28 | import os | |
29 | import sys |
|
29 | import sys | |
30 |
|
30 | |||
31 | from IPython.core import release |
|
31 | from IPython.core import release | |
32 | from IPython.core.crashhandler import CrashHandler |
|
32 | from IPython.core.crashhandler import CrashHandler | |
33 | from IPython.core.application import Application, BaseAppConfigLoader |
|
33 | from IPython.core.application import Application, BaseAppConfigLoader | |
34 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell |
|
34 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell | |
35 | from IPython.config.loader import ( |
|
35 | from IPython.config.loader import ( | |
36 | Config, |
|
36 | Config, | |
37 | PyFileConfigLoader |
|
37 | PyFileConfigLoader | |
38 | ) |
|
38 | ) | |
39 | from IPython.lib import inputhook |
|
39 | from IPython.lib import inputhook | |
40 | from IPython.utils.path import filefind, get_ipython_dir |
|
40 | from IPython.utils.path import filefind, get_ipython_dir, check_for_old_config | |
41 | from IPython.core import usage |
|
41 | from IPython.core import usage | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Globals, utilities and helpers |
|
44 | # Globals, utilities and helpers | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | #: The default config file name for this application. |
|
47 | #: The default config file name for this application. | |
48 | default_config_file_name = u'ipython_config.py' |
|
48 | default_config_file_name = u'ipython_config.py' | |
49 |
|
49 | |||
50 |
|
50 | |||
51 | class IPAppConfigLoader(BaseAppConfigLoader): |
|
51 | class IPAppConfigLoader(BaseAppConfigLoader): | |
52 |
|
52 | |||
53 | def _add_arguments(self): |
|
53 | def _add_arguments(self): | |
54 | super(IPAppConfigLoader, self)._add_arguments() |
|
54 | super(IPAppConfigLoader, self)._add_arguments() | |
55 | paa = self.parser.add_argument |
|
55 | paa = self.parser.add_argument | |
56 | paa('-p', |
|
56 | paa('-p', | |
57 | '--profile', dest='Global.profile', type=unicode, |
|
57 | '--profile', dest='Global.profile', type=unicode, | |
58 | help= |
|
58 | help= | |
59 | """The string name of the ipython profile to be used. Assume that your |
|
59 | """The string name of the ipython profile to be used. Assume that your | |
60 | config file is ipython_config-<name>.py (looks in current dir first, |
|
60 | config file is ipython_config-<name>.py (looks in current dir first, | |
61 | then in IPYTHON_DIR). This is a quick way to keep and load multiple |
|
61 | then in IPYTHON_DIR). This is a quick way to keep and load multiple | |
62 | config files for different tasks, especially if include your basic one |
|
62 | config files for different tasks, especially if include your basic one | |
63 | in your more specialized ones. You can keep a basic |
|
63 | in your more specialized ones. You can keep a basic | |
64 | IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which |
|
64 | IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which | |
65 | include this one and load extra things for particular tasks.""", |
|
65 | include this one and load extra things for particular tasks.""", | |
66 | metavar='Global.profile') |
|
66 | metavar='Global.profile') | |
67 | paa('--config-file', |
|
67 | paa('--config-file', | |
68 | dest='Global.config_file', type=unicode, |
|
68 | dest='Global.config_file', type=unicode, | |
69 | help= |
|
69 | help= | |
70 | """Set the config file name to override default. Normally IPython |
|
70 | """Set the config file name to override default. Normally IPython | |
71 | loads ipython_config.py (from current directory) or |
|
71 | loads ipython_config.py (from current directory) or | |
72 | IPYTHON_DIR/ipython_config.py. If the loading of your config file |
|
72 | IPYTHON_DIR/ipython_config.py. If the loading of your config file | |
73 | fails, IPython starts with a bare bones configuration (no modules |
|
73 | fails, IPython starts with a bare bones configuration (no modules | |
74 | loaded at all).""", |
|
74 | loaded at all).""", | |
75 | metavar='Global.config_file') |
|
75 | metavar='Global.config_file') | |
76 | paa('--autocall', |
|
76 | paa('--autocall', | |
77 | dest='InteractiveShell.autocall', type=int, |
|
77 | dest='InteractiveShell.autocall', type=int, | |
78 | help= |
|
78 | help= | |
79 | """Make IPython automatically call any callable object even if you |
|
79 | """Make IPython automatically call any callable object even if you | |
80 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
80 | didn't type explicit parentheses. For example, 'str 43' becomes | |
81 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
81 | 'str(43)' automatically. The value can be '0' to disable the feature, | |
82 | '1' for 'smart' autocall, where it is not applied if there are no more |
|
82 | '1' for 'smart' autocall, where it is not applied if there are no more | |
83 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
83 | arguments on the line, and '2' for 'full' autocall, where all callable | |
84 | objects are automatically called (even if no arguments are present). |
|
84 | objects are automatically called (even if no arguments are present). | |
85 | The default is '1'.""", |
|
85 | The default is '1'.""", | |
86 | metavar='InteractiveShell.autocall') |
|
86 | metavar='InteractiveShell.autocall') | |
87 | paa('--autoindent', |
|
87 | paa('--autoindent', | |
88 | action='store_true', dest='InteractiveShell.autoindent', |
|
88 | action='store_true', dest='InteractiveShell.autoindent', | |
89 | help='Turn on autoindenting.') |
|
89 | help='Turn on autoindenting.') | |
90 | paa('--no-autoindent', |
|
90 | paa('--no-autoindent', | |
91 | action='store_false', dest='InteractiveShell.autoindent', |
|
91 | action='store_false', dest='InteractiveShell.autoindent', | |
92 | help='Turn off autoindenting.') |
|
92 | help='Turn off autoindenting.') | |
93 | paa('--automagic', |
|
93 | paa('--automagic', | |
94 | action='store_true', dest='InteractiveShell.automagic', |
|
94 | action='store_true', dest='InteractiveShell.automagic', | |
95 | help= |
|
95 | help= | |
96 | """Turn on the auto calling of magic commands. Type %%magic at the |
|
96 | """Turn on the auto calling of magic commands. Type %%magic at the | |
97 | IPython prompt for more information.""") |
|
97 | IPython prompt for more information.""") | |
98 | paa('--no-automagic', |
|
98 | paa('--no-automagic', | |
99 | action='store_false', dest='InteractiveShell.automagic', |
|
99 | action='store_false', dest='InteractiveShell.automagic', | |
100 | help='Turn off the auto calling of magic commands.') |
|
100 | help='Turn off the auto calling of magic commands.') | |
101 | paa('--autoedit-syntax', |
|
101 | paa('--autoedit-syntax', | |
102 | action='store_true', dest='TerminalInteractiveShell.autoedit_syntax', |
|
102 | action='store_true', dest='TerminalInteractiveShell.autoedit_syntax', | |
103 | help='Turn on auto editing of files with syntax errors.') |
|
103 | help='Turn on auto editing of files with syntax errors.') | |
104 | paa('--no-autoedit-syntax', |
|
104 | paa('--no-autoedit-syntax', | |
105 | action='store_false', dest='TerminalInteractiveShell.autoedit_syntax', |
|
105 | action='store_false', dest='TerminalInteractiveShell.autoedit_syntax', | |
106 | help='Turn off auto editing of files with syntax errors.') |
|
106 | help='Turn off auto editing of files with syntax errors.') | |
107 | paa('--banner', |
|
107 | paa('--banner', | |
108 | action='store_true', dest='Global.display_banner', |
|
108 | action='store_true', dest='Global.display_banner', | |
109 | help='Display a banner upon starting IPython.') |
|
109 | help='Display a banner upon starting IPython.') | |
110 | paa('--no-banner', |
|
110 | paa('--no-banner', | |
111 | action='store_false', dest='Global.display_banner', |
|
111 | action='store_false', dest='Global.display_banner', | |
112 | help="Don't display a banner upon starting IPython.") |
|
112 | help="Don't display a banner upon starting IPython.") | |
113 | paa('--cache-size', |
|
113 | paa('--cache-size', | |
114 | type=int, dest='InteractiveShell.cache_size', |
|
114 | type=int, dest='InteractiveShell.cache_size', | |
115 | help= |
|
115 | help= | |
116 | """Set the size of the output cache. The default is 1000, you can |
|
116 | """Set the size of the output cache. The default is 1000, you can | |
117 | change it permanently in your config file. Setting it to 0 completely |
|
117 | change it permanently in your config file. Setting it to 0 completely | |
118 | disables the caching system, and the minimum value accepted is 20 (if |
|
118 | disables the caching system, and the minimum value accepted is 20 (if | |
119 | you provide a value less than 20, it is reset to 0 and a warning is |
|
119 | you provide a value less than 20, it is reset to 0 and a warning is | |
120 | issued). This limit is defined because otherwise you'll spend more |
|
120 | issued). This limit is defined because otherwise you'll spend more | |
121 | time re-flushing a too small cache than working""", |
|
121 | time re-flushing a too small cache than working""", | |
122 | metavar='InteractiveShell.cache_size') |
|
122 | metavar='InteractiveShell.cache_size') | |
123 | paa('--classic', |
|
123 | paa('--classic', | |
124 | action='store_true', dest='Global.classic', |
|
124 | action='store_true', dest='Global.classic', | |
125 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
125 | help="Gives IPython a similar feel to the classic Python prompt.") | |
126 | paa('--colors', |
|
126 | paa('--colors', | |
127 | type=str, dest='InteractiveShell.colors', |
|
127 | type=str, dest='InteractiveShell.colors', | |
128 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
128 | help="Set the color scheme (NoColor, Linux, and LightBG).", | |
129 | metavar='InteractiveShell.colors') |
|
129 | metavar='InteractiveShell.colors') | |
130 | paa('--color-info', |
|
130 | paa('--color-info', | |
131 | action='store_true', dest='InteractiveShell.color_info', |
|
131 | action='store_true', dest='InteractiveShell.color_info', | |
132 | help= |
|
132 | help= | |
133 | """IPython can display information about objects via a set of func- |
|
133 | """IPython can display information about objects via a set of func- | |
134 | tions, and optionally can use colors for this, syntax highlighting |
|
134 | tions, and optionally can use colors for this, syntax highlighting | |
135 | source code and various other elements. However, because this |
|
135 | source code and various other elements. However, because this | |
136 | information is passed through a pager (like 'less') and many pagers get |
|
136 | information is passed through a pager (like 'less') and many pagers get | |
137 | confused with color codes, this option is off by default. You can test |
|
137 | confused with color codes, this option is off by default. You can test | |
138 | it and turn it on permanently in your ipython_config.py file if it |
|
138 | it and turn it on permanently in your ipython_config.py file if it | |
139 | works for you. Test it and turn it on permanently if it works with |
|
139 | works for you. Test it and turn it on permanently if it works with | |
140 | your system. The magic function %%color_info allows you to toggle this |
|
140 | your system. The magic function %%color_info allows you to toggle this | |
141 | inter- actively for testing.""") |
|
141 | inter- actively for testing.""") | |
142 | paa('--no-color-info', |
|
142 | paa('--no-color-info', | |
143 | action='store_false', dest='InteractiveShell.color_info', |
|
143 | action='store_false', dest='InteractiveShell.color_info', | |
144 | help="Disable using colors for info related things.") |
|
144 | help="Disable using colors for info related things.") | |
145 | paa('--confirm-exit', |
|
145 | paa('--confirm-exit', | |
146 | action='store_true', dest='TerminalInteractiveShell.confirm_exit', |
|
146 | action='store_true', dest='TerminalInteractiveShell.confirm_exit', | |
147 | help= |
|
147 | help= | |
148 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
148 | """Set to confirm when you try to exit IPython with an EOF (Control-D | |
149 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or |
|
149 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or | |
150 | '%%Exit', you can force a direct exit without any confirmation.""") |
|
150 | '%%Exit', you can force a direct exit without any confirmation.""") | |
151 | paa('--no-confirm-exit', |
|
151 | paa('--no-confirm-exit', | |
152 | action='store_false', dest='TerminalInteractiveShell.confirm_exit', |
|
152 | action='store_false', dest='TerminalInteractiveShell.confirm_exit', | |
153 | help="Don't prompt the user when exiting.") |
|
153 | help="Don't prompt the user when exiting.") | |
154 | paa('--deep-reload', |
|
154 | paa('--deep-reload', | |
155 | action='store_true', dest='InteractiveShell.deep_reload', |
|
155 | action='store_true', dest='InteractiveShell.deep_reload', | |
156 | help= |
|
156 | help= | |
157 | """Enable deep (recursive) reloading by default. IPython can use the |
|
157 | """Enable deep (recursive) reloading by default. IPython can use the | |
158 | deep_reload module which reloads changes in modules recursively (it |
|
158 | deep_reload module which reloads changes in modules recursively (it | |
159 | replaces the reload() function, so you don't need to change anything to |
|
159 | replaces the reload() function, so you don't need to change anything to | |
160 | use it). deep_reload() forces a full reload of modules whose code may |
|
160 | use it). deep_reload() forces a full reload of modules whose code may | |
161 | have changed, which the default reload() function does not. When |
|
161 | have changed, which the default reload() function does not. When | |
162 | deep_reload is off, IPython will use the normal reload(), but |
|
162 | deep_reload is off, IPython will use the normal reload(), but | |
163 | deep_reload will still be available as dreload(). This fea- ture is off |
|
163 | deep_reload will still be available as dreload(). This fea- ture is off | |
164 | by default [which means that you have both normal reload() and |
|
164 | by default [which means that you have both normal reload() and | |
165 | dreload()].""") |
|
165 | dreload()].""") | |
166 | paa('--no-deep-reload', |
|
166 | paa('--no-deep-reload', | |
167 | action='store_false', dest='InteractiveShell.deep_reload', |
|
167 | action='store_false', dest='InteractiveShell.deep_reload', | |
168 | help="Disable deep (recursive) reloading by default.") |
|
168 | help="Disable deep (recursive) reloading by default.") | |
169 | paa('--editor', |
|
169 | paa('--editor', | |
170 | type=str, dest='TerminalInteractiveShell.editor', |
|
170 | type=str, dest='TerminalInteractiveShell.editor', | |
171 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
171 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", | |
172 | metavar='TerminalInteractiveShell.editor') |
|
172 | metavar='TerminalInteractiveShell.editor') | |
173 | paa('--log','-l', |
|
173 | paa('--log','-l', | |
174 | action='store_true', dest='InteractiveShell.logstart', |
|
174 | action='store_true', dest='InteractiveShell.logstart', | |
175 | help="Start logging to the default log file (./ipython_log.py).") |
|
175 | help="Start logging to the default log file (./ipython_log.py).") | |
176 | paa('--logfile','-lf', |
|
176 | paa('--logfile','-lf', | |
177 | type=unicode, dest='InteractiveShell.logfile', |
|
177 | type=unicode, dest='InteractiveShell.logfile', | |
178 | help="Start logging to logfile with this name.", |
|
178 | help="Start logging to logfile with this name.", | |
179 | metavar='InteractiveShell.logfile') |
|
179 | metavar='InteractiveShell.logfile') | |
180 | paa('--log-append','-la', |
|
180 | paa('--log-append','-la', | |
181 | type=unicode, dest='InteractiveShell.logappend', |
|
181 | type=unicode, dest='InteractiveShell.logappend', | |
182 | help="Start logging to the given file in append mode.", |
|
182 | help="Start logging to the given file in append mode.", | |
183 | metavar='InteractiveShell.logfile') |
|
183 | metavar='InteractiveShell.logfile') | |
184 | paa('--pdb', |
|
184 | paa('--pdb', | |
185 | action='store_true', dest='InteractiveShell.pdb', |
|
185 | action='store_true', dest='InteractiveShell.pdb', | |
186 | help="Enable auto calling the pdb debugger after every exception.") |
|
186 | help="Enable auto calling the pdb debugger after every exception.") | |
187 | paa('--no-pdb', |
|
187 | paa('--no-pdb', | |
188 | action='store_false', dest='InteractiveShell.pdb', |
|
188 | action='store_false', dest='InteractiveShell.pdb', | |
189 | help="Disable auto calling the pdb debugger after every exception.") |
|
189 | help="Disable auto calling the pdb debugger after every exception.") | |
190 | paa('--pprint', |
|
190 | paa('--pprint', | |
191 | action='store_true', dest='PlainTextFormatter.pprint', |
|
191 | action='store_true', dest='PlainTextFormatter.pprint', | |
192 | help="Enable auto pretty printing of results.") |
|
192 | help="Enable auto pretty printing of results.") | |
193 | paa('--no-pprint', |
|
193 | paa('--no-pprint', | |
194 | action='store_false', dest='PlainTextFormatter.pprint', |
|
194 | action='store_false', dest='PlainTextFormatter.pprint', | |
195 | help="Disable auto auto pretty printing of results.") |
|
195 | help="Disable auto auto pretty printing of results.") | |
196 | paa('--prompt-in1','-pi1', |
|
196 | paa('--prompt-in1','-pi1', | |
197 | type=str, dest='InteractiveShell.prompt_in1', |
|
197 | type=str, dest='InteractiveShell.prompt_in1', | |
198 | help= |
|
198 | help= | |
199 | """Set the main input prompt ('In [\#]: '). Note that if you are using |
|
199 | """Set the main input prompt ('In [\#]: '). Note that if you are using | |
200 | numbered prompts, the number is represented with a '\#' in the string. |
|
200 | numbered prompts, the number is represented with a '\#' in the string. | |
201 | Don't forget to quote strings with spaces embedded in them. Most |
|
201 | Don't forget to quote strings with spaces embedded in them. Most | |
202 | bash-like escapes can be used to customize IPython's prompts, as well |
|
202 | bash-like escapes can be used to customize IPython's prompts, as well | |
203 | as a few additional ones which are IPython-spe- cific. All valid |
|
203 | as a few additional ones which are IPython-spe- cific. All valid | |
204 | prompt escapes are described in detail in the Customization section of |
|
204 | prompt escapes are described in detail in the Customization section of | |
205 | the IPython manual.""", |
|
205 | the IPython manual.""", | |
206 | metavar='InteractiveShell.prompt_in1') |
|
206 | metavar='InteractiveShell.prompt_in1') | |
207 | paa('--prompt-in2','-pi2', |
|
207 | paa('--prompt-in2','-pi2', | |
208 | type=str, dest='InteractiveShell.prompt_in2', |
|
208 | type=str, dest='InteractiveShell.prompt_in2', | |
209 | help= |
|
209 | help= | |
210 | """Set the secondary input prompt (' .\D.: '). Similar to the previous |
|
210 | """Set the secondary input prompt (' .\D.: '). Similar to the previous | |
211 | option, but used for the continuation prompts. The special sequence |
|
211 | option, but used for the continuation prompts. The special sequence | |
212 | '\D' is similar to '\#', but with all digits replaced by dots (so you |
|
212 | '\D' is similar to '\#', but with all digits replaced by dots (so you | |
213 | can have your continuation prompt aligned with your input prompt). |
|
213 | can have your continuation prompt aligned with your input prompt). | |
214 | Default: ' .\D.: ' (note three spaces at the start for alignment with |
|
214 | Default: ' .\D.: ' (note three spaces at the start for alignment with | |
215 | 'In [\#]')""", |
|
215 | 'In [\#]')""", | |
216 | metavar='InteractiveShell.prompt_in2') |
|
216 | metavar='InteractiveShell.prompt_in2') | |
217 | paa('--prompt-out','-po', |
|
217 | paa('--prompt-out','-po', | |
218 | type=str, dest='InteractiveShell.prompt_out', |
|
218 | type=str, dest='InteractiveShell.prompt_out', | |
219 | help="Set the output prompt ('Out[\#]:')", |
|
219 | help="Set the output prompt ('Out[\#]:')", | |
220 | metavar='InteractiveShell.prompt_out') |
|
220 | metavar='InteractiveShell.prompt_out') | |
221 | paa('--quick', |
|
221 | paa('--quick', | |
222 | action='store_true', dest='Global.quick', |
|
222 | action='store_true', dest='Global.quick', | |
223 | help="Enable quick startup with no config files.") |
|
223 | help="Enable quick startup with no config files.") | |
224 | paa('--readline', |
|
224 | paa('--readline', | |
225 | action='store_true', dest='InteractiveShell.readline_use', |
|
225 | action='store_true', dest='InteractiveShell.readline_use', | |
226 | help="Enable readline for command line usage.") |
|
226 | help="Enable readline for command line usage.") | |
227 | paa('--no-readline', |
|
227 | paa('--no-readline', | |
228 | action='store_false', dest='InteractiveShell.readline_use', |
|
228 | action='store_false', dest='InteractiveShell.readline_use', | |
229 | help="Disable readline for command line usage.") |
|
229 | help="Disable readline for command line usage.") | |
230 | paa('--screen-length','-sl', |
|
230 | paa('--screen-length','-sl', | |
231 | type=int, dest='TerminalInteractiveShell.screen_length', |
|
231 | type=int, dest='TerminalInteractiveShell.screen_length', | |
232 | help= |
|
232 | help= | |
233 | """Number of lines of your screen, used to control printing of very |
|
233 | """Number of lines of your screen, used to control printing of very | |
234 | long strings. Strings longer than this number of lines will be sent |
|
234 | long strings. Strings longer than this number of lines will be sent | |
235 | through a pager instead of directly printed. The default value for |
|
235 | through a pager instead of directly printed. The default value for | |
236 | this is 0, which means IPython will auto-detect your screen size every |
|
236 | this is 0, which means IPython will auto-detect your screen size every | |
237 | time it needs to print certain potentially long strings (this doesn't |
|
237 | time it needs to print certain potentially long strings (this doesn't | |
238 | change the behavior of the 'print' keyword, it's only triggered |
|
238 | change the behavior of the 'print' keyword, it's only triggered | |
239 | internally). If for some reason this isn't working well (it needs |
|
239 | internally). If for some reason this isn't working well (it needs | |
240 | curses support), specify it yourself. Otherwise don't change the |
|
240 | curses support), specify it yourself. Otherwise don't change the | |
241 | default.""", |
|
241 | default.""", | |
242 | metavar='TerminalInteractiveShell.screen_length') |
|
242 | metavar='TerminalInteractiveShell.screen_length') | |
243 | paa('--separate-in','-si', |
|
243 | paa('--separate-in','-si', | |
244 | type=str, dest='InteractiveShell.separate_in', |
|
244 | type=str, dest='InteractiveShell.separate_in', | |
245 | help="Separator before input prompts. Default '\\n'.", |
|
245 | help="Separator before input prompts. Default '\\n'.", | |
246 | metavar='InteractiveShell.separate_in') |
|
246 | metavar='InteractiveShell.separate_in') | |
247 | paa('--separate-out','-so', |
|
247 | paa('--separate-out','-so', | |
248 | type=str, dest='InteractiveShell.separate_out', |
|
248 | type=str, dest='InteractiveShell.separate_out', | |
249 | help="Separator before output prompts. Default 0 (nothing).", |
|
249 | help="Separator before output prompts. Default 0 (nothing).", | |
250 | metavar='InteractiveShell.separate_out') |
|
250 | metavar='InteractiveShell.separate_out') | |
251 | paa('--separate-out2','-so2', |
|
251 | paa('--separate-out2','-so2', | |
252 | type=str, dest='InteractiveShell.separate_out2', |
|
252 | type=str, dest='InteractiveShell.separate_out2', | |
253 | help="Separator after output prompts. Default 0 (nonight).", |
|
253 | help="Separator after output prompts. Default 0 (nonight).", | |
254 | metavar='InteractiveShell.separate_out2') |
|
254 | metavar='InteractiveShell.separate_out2') | |
255 | paa('--no-sep', |
|
255 | paa('--no-sep', | |
256 | action='store_true', dest='Global.nosep', |
|
256 | action='store_true', dest='Global.nosep', | |
257 | help="Eliminate all spacing between prompts.") |
|
257 | help="Eliminate all spacing between prompts.") | |
258 | paa('--term-title', |
|
258 | paa('--term-title', | |
259 | action='store_true', dest='TerminalInteractiveShell.term_title', |
|
259 | action='store_true', dest='TerminalInteractiveShell.term_title', | |
260 | help="Enable auto setting the terminal title.") |
|
260 | help="Enable auto setting the terminal title.") | |
261 | paa('--no-term-title', |
|
261 | paa('--no-term-title', | |
262 | action='store_false', dest='TerminalInteractiveShell.term_title', |
|
262 | action='store_false', dest='TerminalInteractiveShell.term_title', | |
263 | help="Disable auto setting the terminal title.") |
|
263 | help="Disable auto setting the terminal title.") | |
264 | paa('--xmode', |
|
264 | paa('--xmode', | |
265 | type=str, dest='InteractiveShell.xmode', |
|
265 | type=str, dest='InteractiveShell.xmode', | |
266 | help= |
|
266 | help= | |
267 | """Exception reporting mode ('Plain','Context','Verbose'). Plain: |
|
267 | """Exception reporting mode ('Plain','Context','Verbose'). Plain: | |
268 | similar to python's normal traceback printing. Context: prints 5 lines |
|
268 | similar to python's normal traceback printing. Context: prints 5 lines | |
269 | of context source code around each line in the traceback. Verbose: |
|
269 | of context source code around each line in the traceback. Verbose: | |
270 | similar to Context, but additionally prints the variables currently |
|
270 | similar to Context, but additionally prints the variables currently | |
271 | visible where the exception happened (shortening their strings if too |
|
271 | visible where the exception happened (shortening their strings if too | |
272 | long). This can potentially be very slow, if you happen to have a huge |
|
272 | long). This can potentially be very slow, if you happen to have a huge | |
273 | data structure whose string representation is complex to compute. |
|
273 | data structure whose string representation is complex to compute. | |
274 | Your computer may appear to freeze for a while with cpu usage at 100%%. |
|
274 | Your computer may appear to freeze for a while with cpu usage at 100%%. | |
275 | If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting |
|
275 | If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting | |
276 | it more than once). |
|
276 | it more than once). | |
277 | """, |
|
277 | """, | |
278 | metavar='InteractiveShell.xmode') |
|
278 | metavar='InteractiveShell.xmode') | |
279 | paa('--ext', |
|
279 | paa('--ext', | |
280 | type=str, dest='Global.extra_extension', |
|
280 | type=str, dest='Global.extra_extension', | |
281 | help="The dotted module name of an IPython extension to load.", |
|
281 | help="The dotted module name of an IPython extension to load.", | |
282 | metavar='Global.extra_extension') |
|
282 | metavar='Global.extra_extension') | |
283 | paa('-c', |
|
283 | paa('-c', | |
284 | type=str, dest='Global.code_to_run', |
|
284 | type=str, dest='Global.code_to_run', | |
285 | help="Execute the given command string.", |
|
285 | help="Execute the given command string.", | |
286 | metavar='Global.code_to_run') |
|
286 | metavar='Global.code_to_run') | |
287 | paa('-i', |
|
287 | paa('-i', | |
288 | action='store_true', dest='Global.force_interact', |
|
288 | action='store_true', dest='Global.force_interact', | |
289 | help= |
|
289 | help= | |
290 | "If running code from the command line, become interactive afterwards.") |
|
290 | "If running code from the command line, become interactive afterwards.") | |
291 |
|
291 | |||
292 | # Options to start with GUI control enabled from the beginning |
|
292 | # Options to start with GUI control enabled from the beginning | |
293 | paa('--gui', |
|
293 | paa('--gui', | |
294 | type=str, dest='Global.gui', |
|
294 | type=str, dest='Global.gui', | |
295 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk').", |
|
295 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk').", | |
296 | metavar='gui-mode') |
|
296 | metavar='gui-mode') | |
297 | paa('--pylab','-pylab', |
|
297 | paa('--pylab','-pylab', | |
298 | type=str, dest='Global.pylab', |
|
298 | type=str, dest='Global.pylab', | |
299 | nargs='?', const='auto', metavar='gui-mode', |
|
299 | nargs='?', const='auto', metavar='gui-mode', | |
300 | help="Pre-load matplotlib and numpy for interactive use. "+ |
|
300 | help="Pre-load matplotlib and numpy for interactive use. "+ | |
301 | "If no value is given, the gui backend is matplotlib's, else use "+ |
|
301 | "If no value is given, the gui backend is matplotlib's, else use "+ | |
302 | "one of: ['tk', 'qt', 'wx', 'gtk', 'osx'].") |
|
302 | "one of: ['tk', 'qt', 'wx', 'gtk', 'osx'].") | |
303 |
|
303 | |||
304 | # Legacy GUI options. Leave them in for backwards compatibility, but the |
|
304 | # Legacy GUI options. Leave them in for backwards compatibility, but the | |
305 | # 'thread' names are really a misnomer now. |
|
305 | # 'thread' names are really a misnomer now. | |
306 | paa('--wthread', '-wthread', |
|
306 | paa('--wthread', '-wthread', | |
307 | action='store_true', dest='Global.wthread', |
|
307 | action='store_true', dest='Global.wthread', | |
308 | help= |
|
308 | help= | |
309 | """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""") |
|
309 | """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""") | |
310 | paa('--q4thread', '--qthread', '-q4thread', '-qthread', |
|
310 | paa('--q4thread', '--qthread', '-q4thread', '-qthread', | |
311 | action='store_true', dest='Global.q4thread', |
|
311 | action='store_true', dest='Global.q4thread', | |
312 | help= |
|
312 | help= | |
313 | """Enable Qt4 event loop integration. Qt3 is no longer supported. |
|
313 | """Enable Qt4 event loop integration. Qt3 is no longer supported. | |
314 | (DEPRECATED, use --gui qt)""") |
|
314 | (DEPRECATED, use --gui qt)""") | |
315 | paa('--gthread', '-gthread', |
|
315 | paa('--gthread', '-gthread', | |
316 | action='store_true', dest='Global.gthread', |
|
316 | action='store_true', dest='Global.gthread', | |
317 | help= |
|
317 | help= | |
318 | """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""") |
|
318 | """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""") | |
319 |
|
319 | |||
320 |
|
320 | |||
321 | #----------------------------------------------------------------------------- |
|
321 | #----------------------------------------------------------------------------- | |
322 | # Crash handler for this application |
|
322 | # Crash handler for this application | |
323 | #----------------------------------------------------------------------------- |
|
323 | #----------------------------------------------------------------------------- | |
324 |
|
324 | |||
325 | _message_template = """\ |
|
325 | _message_template = """\ | |
326 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
326 | Oops, $self.app_name crashed. We do our best to make it stable, but... | |
327 |
|
327 | |||
328 | A crash report was automatically generated with the following information: |
|
328 | A crash report was automatically generated with the following information: | |
329 | - A verbatim copy of the crash traceback. |
|
329 | - A verbatim copy of the crash traceback. | |
330 | - A copy of your input history during this session. |
|
330 | - A copy of your input history during this session. | |
331 | - Data on your current $self.app_name configuration. |
|
331 | - Data on your current $self.app_name configuration. | |
332 |
|
332 | |||
333 | It was left in the file named: |
|
333 | It was left in the file named: | |
334 | \t'$self.crash_report_fname' |
|
334 | \t'$self.crash_report_fname' | |
335 | If you can email this file to the developers, the information in it will help |
|
335 | If you can email this file to the developers, the information in it will help | |
336 | them in understanding and correcting the problem. |
|
336 | them in understanding and correcting the problem. | |
337 |
|
337 | |||
338 | You can mail it to: $self.contact_name at $self.contact_email |
|
338 | You can mail it to: $self.contact_name at $self.contact_email | |
339 | with the subject '$self.app_name Crash Report'. |
|
339 | with the subject '$self.app_name Crash Report'. | |
340 |
|
340 | |||
341 | If you want to do it now, the following command will work (under Unix): |
|
341 | If you want to do it now, the following command will work (under Unix): | |
342 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
342 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname | |
343 |
|
343 | |||
344 | To ensure accurate tracking of this issue, please file a report about it at: |
|
344 | To ensure accurate tracking of this issue, please file a report about it at: | |
345 | $self.bug_tracker |
|
345 | $self.bug_tracker | |
346 | """ |
|
346 | """ | |
347 |
|
347 | |||
348 | class IPAppCrashHandler(CrashHandler): |
|
348 | class IPAppCrashHandler(CrashHandler): | |
349 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
349 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" | |
350 |
|
350 | |||
351 | message_template = _message_template |
|
351 | message_template = _message_template | |
352 |
|
352 | |||
353 | def __init__(self, app): |
|
353 | def __init__(self, app): | |
354 | contact_name = release.authors['Fernando'][0] |
|
354 | contact_name = release.authors['Fernando'][0] | |
355 | contact_email = release.authors['Fernando'][1] |
|
355 | contact_email = release.authors['Fernando'][1] | |
356 | bug_tracker = 'http://github.com/ipython/ipython/issues' |
|
356 | bug_tracker = 'http://github.com/ipython/ipython/issues' | |
357 | super(IPAppCrashHandler,self).__init__( |
|
357 | super(IPAppCrashHandler,self).__init__( | |
358 | app, contact_name, contact_email, bug_tracker |
|
358 | app, contact_name, contact_email, bug_tracker | |
359 | ) |
|
359 | ) | |
360 |
|
360 | |||
361 | def make_report(self,traceback): |
|
361 | def make_report(self,traceback): | |
362 | """Return a string containing a crash report.""" |
|
362 | """Return a string containing a crash report.""" | |
363 |
|
363 | |||
364 | sec_sep = self.section_sep |
|
364 | sec_sep = self.section_sep | |
365 | # Start with parent report |
|
365 | # Start with parent report | |
366 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
366 | report = [super(IPAppCrashHandler, self).make_report(traceback)] | |
367 | # Add interactive-specific info we may have |
|
367 | # Add interactive-specific info we may have | |
368 | rpt_add = report.append |
|
368 | rpt_add = report.append | |
369 | try: |
|
369 | try: | |
370 | rpt_add(sec_sep+"History of session input:") |
|
370 | rpt_add(sec_sep+"History of session input:") | |
371 | for line in self.app.shell.user_ns['_ih']: |
|
371 | for line in self.app.shell.user_ns['_ih']: | |
372 | rpt_add(line) |
|
372 | rpt_add(line) | |
373 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
373 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
374 | rpt_add(self.app.shell._last_input_line+'\n') |
|
374 | rpt_add(self.app.shell._last_input_line+'\n') | |
375 | except: |
|
375 | except: | |
376 | pass |
|
376 | pass | |
377 |
|
377 | |||
378 | return ''.join(report) |
|
378 | return ''.join(report) | |
379 |
|
379 | |||
380 |
|
380 | |||
381 | #----------------------------------------------------------------------------- |
|
381 | #----------------------------------------------------------------------------- | |
382 | # Main classes and functions |
|
382 | # Main classes and functions | |
383 | #----------------------------------------------------------------------------- |
|
383 | #----------------------------------------------------------------------------- | |
384 |
|
384 | |||
385 | class IPythonApp(Application): |
|
385 | class IPythonApp(Application): | |
386 | name = u'ipython' |
|
386 | name = u'ipython' | |
387 | #: argparse formats better the 'usage' than the 'description' field |
|
387 | #: argparse formats better the 'usage' than the 'description' field | |
388 | description = None |
|
388 | description = None | |
389 | usage = usage.cl_usage |
|
389 | usage = usage.cl_usage | |
390 | command_line_loader = IPAppConfigLoader |
|
390 | command_line_loader = IPAppConfigLoader | |
391 | default_config_file_name = default_config_file_name |
|
391 | default_config_file_name = default_config_file_name | |
392 | crash_handler_class = IPAppCrashHandler |
|
392 | crash_handler_class = IPAppCrashHandler | |
393 |
|
393 | |||
394 | def create_default_config(self): |
|
394 | def create_default_config(self): | |
395 | super(IPythonApp, self).create_default_config() |
|
395 | super(IPythonApp, self).create_default_config() | |
396 | # Eliminate multiple lookups |
|
396 | # Eliminate multiple lookups | |
397 | Global = self.default_config.Global |
|
397 | Global = self.default_config.Global | |
398 |
|
398 | |||
399 | # Set all default values |
|
399 | # Set all default values | |
400 | Global.display_banner = True |
|
400 | Global.display_banner = True | |
401 |
|
401 | |||
402 | # If the -c flag is given or a file is given to run at the cmd line |
|
402 | # If the -c flag is given or a file is given to run at the cmd line | |
403 | # like "ipython foo.py", normally we exit without starting the main |
|
403 | # like "ipython foo.py", normally we exit without starting the main | |
404 | # loop. The force_interact config variable allows a user to override |
|
404 | # loop. The force_interact config variable allows a user to override | |
405 | # this and interact. It is also set by the -i cmd line flag, just |
|
405 | # this and interact. It is also set by the -i cmd line flag, just | |
406 | # like Python. |
|
406 | # like Python. | |
407 | Global.force_interact = False |
|
407 | Global.force_interact = False | |
408 |
|
408 | |||
409 | # By default always interact by starting the IPython mainloop. |
|
409 | # By default always interact by starting the IPython mainloop. | |
410 | Global.interact = True |
|
410 | Global.interact = True | |
411 |
|
411 | |||
412 | # No GUI integration by default |
|
412 | # No GUI integration by default | |
413 | Global.gui = False |
|
413 | Global.gui = False | |
414 | # Pylab off by default |
|
414 | # Pylab off by default | |
415 | Global.pylab = False |
|
415 | Global.pylab = False | |
416 |
|
416 | |||
417 | # Deprecated versions of gui support that used threading, we support |
|
417 | # Deprecated versions of gui support that used threading, we support | |
418 | # them just for bacwards compatibility as an alternate spelling for |
|
418 | # them just for bacwards compatibility as an alternate spelling for | |
419 | # '--gui X' |
|
419 | # '--gui X' | |
420 | Global.qthread = False |
|
420 | Global.qthread = False | |
421 | Global.q4thread = False |
|
421 | Global.q4thread = False | |
422 | Global.wthread = False |
|
422 | Global.wthread = False | |
423 | Global.gthread = False |
|
423 | Global.gthread = False | |
424 |
|
424 | |||
425 | def load_file_config(self): |
|
425 | def load_file_config(self): | |
426 | if hasattr(self.command_line_config.Global, 'quick'): |
|
426 | if hasattr(self.command_line_config.Global, 'quick'): | |
427 | if self.command_line_config.Global.quick: |
|
427 | if self.command_line_config.Global.quick: | |
428 | self.file_config = Config() |
|
428 | self.file_config = Config() | |
429 | return |
|
429 | return | |
430 | super(IPythonApp, self).load_file_config() |
|
430 | super(IPythonApp, self).load_file_config() | |
431 |
|
431 | |||
432 | def post_load_file_config(self): |
|
432 | def post_load_file_config(self): | |
433 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
433 | if hasattr(self.command_line_config.Global, 'extra_extension'): | |
434 | if not hasattr(self.file_config.Global, 'extensions'): |
|
434 | if not hasattr(self.file_config.Global, 'extensions'): | |
435 | self.file_config.Global.extensions = [] |
|
435 | self.file_config.Global.extensions = [] | |
436 | self.file_config.Global.extensions.append( |
|
436 | self.file_config.Global.extensions.append( | |
437 | self.command_line_config.Global.extra_extension) |
|
437 | self.command_line_config.Global.extra_extension) | |
438 | del self.command_line_config.Global.extra_extension |
|
438 | del self.command_line_config.Global.extra_extension | |
439 |
|
439 | |||
440 | def pre_construct(self): |
|
440 | def pre_construct(self): | |
441 | config = self.master_config |
|
441 | config = self.master_config | |
442 |
|
442 | |||
443 | if hasattr(config.Global, 'classic'): |
|
443 | if hasattr(config.Global, 'classic'): | |
444 | if config.Global.classic: |
|
444 | if config.Global.classic: | |
445 | config.InteractiveShell.cache_size = 0 |
|
445 | config.InteractiveShell.cache_size = 0 | |
446 | config.PlainTextFormatter.pprint = False |
|
446 | config.PlainTextFormatter.pprint = False | |
447 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
447 | config.InteractiveShell.prompt_in1 = '>>> ' | |
448 | config.InteractiveShell.prompt_in2 = '... ' |
|
448 | config.InteractiveShell.prompt_in2 = '... ' | |
449 | config.InteractiveShell.prompt_out = '' |
|
449 | config.InteractiveShell.prompt_out = '' | |
450 | config.InteractiveShell.separate_in = \ |
|
450 | config.InteractiveShell.separate_in = \ | |
451 | config.InteractiveShell.separate_out = \ |
|
451 | config.InteractiveShell.separate_out = \ | |
452 | config.InteractiveShell.separate_out2 = '' |
|
452 | config.InteractiveShell.separate_out2 = '' | |
453 | config.InteractiveShell.colors = 'NoColor' |
|
453 | config.InteractiveShell.colors = 'NoColor' | |
454 | config.InteractiveShell.xmode = 'Plain' |
|
454 | config.InteractiveShell.xmode = 'Plain' | |
455 |
|
455 | |||
456 | if hasattr(config.Global, 'nosep'): |
|
456 | if hasattr(config.Global, 'nosep'): | |
457 | if config.Global.nosep: |
|
457 | if config.Global.nosep: | |
458 | config.InteractiveShell.separate_in = \ |
|
458 | config.InteractiveShell.separate_in = \ | |
459 | config.InteractiveShell.separate_out = \ |
|
459 | config.InteractiveShell.separate_out = \ | |
460 | config.InteractiveShell.separate_out2 = '' |
|
460 | config.InteractiveShell.separate_out2 = '' | |
461 |
|
461 | |||
462 | # if there is code of files to run from the cmd line, don't interact |
|
462 | # if there is code of files to run from the cmd line, don't interact | |
463 | # unless the -i flag (Global.force_interact) is true. |
|
463 | # unless the -i flag (Global.force_interact) is true. | |
464 | code_to_run = config.Global.get('code_to_run','') |
|
464 | code_to_run = config.Global.get('code_to_run','') | |
465 | file_to_run = False |
|
465 | file_to_run = False | |
466 | if self.extra_args and self.extra_args[0]: |
|
466 | if self.extra_args and self.extra_args[0]: | |
467 | file_to_run = True |
|
467 | file_to_run = True | |
468 | if file_to_run or code_to_run: |
|
468 | if file_to_run or code_to_run: | |
469 | if not config.Global.force_interact: |
|
469 | if not config.Global.force_interact: | |
470 | config.Global.interact = False |
|
470 | config.Global.interact = False | |
471 |
|
471 | |||
472 | def construct(self): |
|
472 | def construct(self): | |
473 | # I am a little hesitant to put these into InteractiveShell itself. |
|
473 | # I am a little hesitant to put these into InteractiveShell itself. | |
474 | # But that might be the place for them |
|
474 | # But that might be the place for them | |
475 | sys.path.insert(0, '') |
|
475 | sys.path.insert(0, '') | |
476 |
|
476 | |||
477 | # Create an InteractiveShell instance. |
|
477 | # Create an InteractiveShell instance. | |
478 | self.shell = TerminalInteractiveShell.instance(config=self.master_config) |
|
478 | self.shell = TerminalInteractiveShell.instance(config=self.master_config) | |
479 |
|
479 | |||
480 | def post_construct(self): |
|
480 | def post_construct(self): | |
481 | """Do actions after construct, but before starting the app.""" |
|
481 | """Do actions after construct, but before starting the app.""" | |
482 | config = self.master_config |
|
482 | config = self.master_config | |
483 |
|
483 | |||
484 | # shell.display_banner should always be False for the terminal |
|
484 | # shell.display_banner should always be False for the terminal | |
485 | # based app, because we call shell.show_banner() by hand below |
|
485 | # based app, because we call shell.show_banner() by hand below | |
486 | # so the banner shows *before* all extension loading stuff. |
|
486 | # so the banner shows *before* all extension loading stuff. | |
487 | self.shell.display_banner = False |
|
487 | self.shell.display_banner = False | |
488 | if config.Global.display_banner and \ |
|
488 | if config.Global.display_banner and \ | |
489 | config.Global.interact: |
|
489 | config.Global.interact: | |
490 | self.shell.show_banner() |
|
490 | self.shell.show_banner() | |
491 |
|
491 | |||
492 | # Make sure there is a space below the banner. |
|
492 | # Make sure there is a space below the banner. | |
493 | if self.log_level <= logging.INFO: print |
|
493 | if self.log_level <= logging.INFO: print | |
494 |
|
494 | |||
495 | # Now a variety of things that happen after the banner is printed. |
|
495 | # Now a variety of things that happen after the banner is printed. | |
496 | self._enable_gui_pylab() |
|
496 | self._enable_gui_pylab() | |
497 | self._load_extensions() |
|
497 | self._load_extensions() | |
498 | self._run_exec_lines() |
|
498 | self._run_exec_lines() | |
499 | self._run_exec_files() |
|
499 | self._run_exec_files() | |
500 | self._run_cmd_line_code() |
|
500 | self._run_cmd_line_code() | |
501 |
|
501 | |||
502 | def _enable_gui_pylab(self): |
|
502 | def _enable_gui_pylab(self): | |
503 | """Enable GUI event loop integration, taking pylab into account.""" |
|
503 | """Enable GUI event loop integration, taking pylab into account.""" | |
504 | Global = self.master_config.Global |
|
504 | Global = self.master_config.Global | |
505 |
|
505 | |||
506 | # Select which gui to use |
|
506 | # Select which gui to use | |
507 | if Global.gui: |
|
507 | if Global.gui: | |
508 | gui = Global.gui |
|
508 | gui = Global.gui | |
509 | # The following are deprecated, but there's likely to be a lot of use |
|
509 | # The following are deprecated, but there's likely to be a lot of use | |
510 | # of this form out there, so we might as well support it for now. But |
|
510 | # of this form out there, so we might as well support it for now. But | |
511 | # the --gui option above takes precedence. |
|
511 | # the --gui option above takes precedence. | |
512 | elif Global.wthread: |
|
512 | elif Global.wthread: | |
513 | gui = inputhook.GUI_WX |
|
513 | gui = inputhook.GUI_WX | |
514 | elif Global.qthread: |
|
514 | elif Global.qthread: | |
515 | gui = inputhook.GUI_QT |
|
515 | gui = inputhook.GUI_QT | |
516 | elif Global.gthread: |
|
516 | elif Global.gthread: | |
517 | gui = inputhook.GUI_GTK |
|
517 | gui = inputhook.GUI_GTK | |
518 | else: |
|
518 | else: | |
519 | gui = None |
|
519 | gui = None | |
520 |
|
520 | |||
521 | # Using --pylab will also require gui activation, though which toolkit |
|
521 | # Using --pylab will also require gui activation, though which toolkit | |
522 | # to use may be chosen automatically based on mpl configuration. |
|
522 | # to use may be chosen automatically based on mpl configuration. | |
523 | if Global.pylab: |
|
523 | if Global.pylab: | |
524 | activate = self.shell.enable_pylab |
|
524 | activate = self.shell.enable_pylab | |
525 | if Global.pylab == 'auto': |
|
525 | if Global.pylab == 'auto': | |
526 | gui = None |
|
526 | gui = None | |
527 | else: |
|
527 | else: | |
528 | gui = Global.pylab |
|
528 | gui = Global.pylab | |
529 | else: |
|
529 | else: | |
530 | # Enable only GUI integration, no pylab |
|
530 | # Enable only GUI integration, no pylab | |
531 | activate = inputhook.enable_gui |
|
531 | activate = inputhook.enable_gui | |
532 |
|
532 | |||
533 | if gui or Global.pylab: |
|
533 | if gui or Global.pylab: | |
534 | try: |
|
534 | try: | |
535 | self.log.info("Enabling GUI event loop integration, " |
|
535 | self.log.info("Enabling GUI event loop integration, " | |
536 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) |
|
536 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) | |
537 | activate(gui) |
|
537 | activate(gui) | |
538 | except: |
|
538 | except: | |
539 | self.log.warn("Error in enabling GUI event loop integration:") |
|
539 | self.log.warn("Error in enabling GUI event loop integration:") | |
540 | self.shell.showtraceback() |
|
540 | self.shell.showtraceback() | |
541 |
|
541 | |||
542 | def _load_extensions(self): |
|
542 | def _load_extensions(self): | |
543 | """Load all IPython extensions in Global.extensions. |
|
543 | """Load all IPython extensions in Global.extensions. | |
544 |
|
544 | |||
545 | This uses the :meth:`ExtensionManager.load_extensions` to load all |
|
545 | This uses the :meth:`ExtensionManager.load_extensions` to load all | |
546 | the extensions listed in ``self.master_config.Global.extensions``. |
|
546 | the extensions listed in ``self.master_config.Global.extensions``. | |
547 | """ |
|
547 | """ | |
548 | try: |
|
548 | try: | |
549 | if hasattr(self.master_config.Global, 'extensions'): |
|
549 | if hasattr(self.master_config.Global, 'extensions'): | |
550 | self.log.debug("Loading IPython extensions...") |
|
550 | self.log.debug("Loading IPython extensions...") | |
551 | extensions = self.master_config.Global.extensions |
|
551 | extensions = self.master_config.Global.extensions | |
552 | for ext in extensions: |
|
552 | for ext in extensions: | |
553 | try: |
|
553 | try: | |
554 | self.log.info("Loading IPython extension: %s" % ext) |
|
554 | self.log.info("Loading IPython extension: %s" % ext) | |
555 | self.shell.extension_manager.load_extension(ext) |
|
555 | self.shell.extension_manager.load_extension(ext) | |
556 | except: |
|
556 | except: | |
557 | self.log.warn("Error in loading extension: %s" % ext) |
|
557 | self.log.warn("Error in loading extension: %s" % ext) | |
558 | self.shell.showtraceback() |
|
558 | self.shell.showtraceback() | |
559 | except: |
|
559 | except: | |
560 | self.log.warn("Unknown error in loading extensions:") |
|
560 | self.log.warn("Unknown error in loading extensions:") | |
561 | self.shell.showtraceback() |
|
561 | self.shell.showtraceback() | |
562 |
|
562 | |||
563 | def _run_exec_lines(self): |
|
563 | def _run_exec_lines(self): | |
564 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
564 | """Run lines of code in Global.exec_lines in the user's namespace.""" | |
565 | try: |
|
565 | try: | |
566 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
566 | if hasattr(self.master_config.Global, 'exec_lines'): | |
567 | self.log.debug("Running code from Global.exec_lines...") |
|
567 | self.log.debug("Running code from Global.exec_lines...") | |
568 | exec_lines = self.master_config.Global.exec_lines |
|
568 | exec_lines = self.master_config.Global.exec_lines | |
569 | for line in exec_lines: |
|
569 | for line in exec_lines: | |
570 | try: |
|
570 | try: | |
571 | self.log.info("Running code in user namespace: %s" % |
|
571 | self.log.info("Running code in user namespace: %s" % | |
572 | line) |
|
572 | line) | |
573 | self.shell.run_cell(line, store_history=False) |
|
573 | self.shell.run_cell(line, store_history=False) | |
574 | except: |
|
574 | except: | |
575 | self.log.warn("Error in executing line in user " |
|
575 | self.log.warn("Error in executing line in user " | |
576 | "namespace: %s" % line) |
|
576 | "namespace: %s" % line) | |
577 | self.shell.showtraceback() |
|
577 | self.shell.showtraceback() | |
578 | except: |
|
578 | except: | |
579 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
579 | self.log.warn("Unknown error in handling Global.exec_lines:") | |
580 | self.shell.showtraceback() |
|
580 | self.shell.showtraceback() | |
581 |
|
581 | |||
582 | def _exec_file(self, fname): |
|
582 | def _exec_file(self, fname): | |
583 | full_filename = filefind(fname, [u'.', self.ipython_dir]) |
|
583 | full_filename = filefind(fname, [u'.', self.ipython_dir]) | |
584 | if os.path.isfile(full_filename): |
|
584 | if os.path.isfile(full_filename): | |
585 | if full_filename.endswith(u'.py'): |
|
585 | if full_filename.endswith(u'.py'): | |
586 | self.log.info("Running file in user namespace: %s" % |
|
586 | self.log.info("Running file in user namespace: %s" % | |
587 | full_filename) |
|
587 | full_filename) | |
588 | # Ensure that __file__ is always defined to match Python behavior |
|
588 | # Ensure that __file__ is always defined to match Python behavior | |
589 | self.shell.user_ns['__file__'] = fname |
|
589 | self.shell.user_ns['__file__'] = fname | |
590 | try: |
|
590 | try: | |
591 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
591 | self.shell.safe_execfile(full_filename, self.shell.user_ns) | |
592 | finally: |
|
592 | finally: | |
593 | del self.shell.user_ns['__file__'] |
|
593 | del self.shell.user_ns['__file__'] | |
594 | elif full_filename.endswith('.ipy'): |
|
594 | elif full_filename.endswith('.ipy'): | |
595 | self.log.info("Running file in user namespace: %s" % |
|
595 | self.log.info("Running file in user namespace: %s" % | |
596 | full_filename) |
|
596 | full_filename) | |
597 | self.shell.safe_execfile_ipy(full_filename) |
|
597 | self.shell.safe_execfile_ipy(full_filename) | |
598 | else: |
|
598 | else: | |
599 | self.log.warn("File does not have a .py or .ipy extension: <%s>" |
|
599 | self.log.warn("File does not have a .py or .ipy extension: <%s>" | |
600 | % full_filename) |
|
600 | % full_filename) | |
601 | def _run_exec_files(self): |
|
601 | def _run_exec_files(self): | |
602 | try: |
|
602 | try: | |
603 | if hasattr(self.master_config.Global, 'exec_files'): |
|
603 | if hasattr(self.master_config.Global, 'exec_files'): | |
604 | self.log.debug("Running files in Global.exec_files...") |
|
604 | self.log.debug("Running files in Global.exec_files...") | |
605 | exec_files = self.master_config.Global.exec_files |
|
605 | exec_files = self.master_config.Global.exec_files | |
606 | for fname in exec_files: |
|
606 | for fname in exec_files: | |
607 | self._exec_file(fname) |
|
607 | self._exec_file(fname) | |
608 | except: |
|
608 | except: | |
609 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
609 | self.log.warn("Unknown error in handling Global.exec_files:") | |
610 | self.shell.showtraceback() |
|
610 | self.shell.showtraceback() | |
611 |
|
611 | |||
612 | def _run_cmd_line_code(self): |
|
612 | def _run_cmd_line_code(self): | |
613 | if hasattr(self.master_config.Global, 'code_to_run'): |
|
613 | if hasattr(self.master_config.Global, 'code_to_run'): | |
614 | line = self.master_config.Global.code_to_run |
|
614 | line = self.master_config.Global.code_to_run | |
615 | try: |
|
615 | try: | |
616 | self.log.info("Running code given at command line (-c): %s" % |
|
616 | self.log.info("Running code given at command line (-c): %s" % | |
617 | line) |
|
617 | line) | |
618 | self.shell.run_cell(line, store_history=False) |
|
618 | self.shell.run_cell(line, store_history=False) | |
619 | except: |
|
619 | except: | |
620 | self.log.warn("Error in executing line in user namespace: %s" % |
|
620 | self.log.warn("Error in executing line in user namespace: %s" % | |
621 | line) |
|
621 | line) | |
622 | self.shell.showtraceback() |
|
622 | self.shell.showtraceback() | |
623 | return |
|
623 | return | |
624 | # Like Python itself, ignore the second if the first of these is present |
|
624 | # Like Python itself, ignore the second if the first of these is present | |
625 | try: |
|
625 | try: | |
626 | fname = self.extra_args[0] |
|
626 | fname = self.extra_args[0] | |
627 | except: |
|
627 | except: | |
628 | pass |
|
628 | pass | |
629 | else: |
|
629 | else: | |
630 | try: |
|
630 | try: | |
631 | self._exec_file(fname) |
|
631 | self._exec_file(fname) | |
632 | except: |
|
632 | except: | |
633 | self.log.warn("Error in executing file in user namespace: %s" % |
|
633 | self.log.warn("Error in executing file in user namespace: %s" % | |
634 | fname) |
|
634 | fname) | |
635 | self.shell.showtraceback() |
|
635 | self.shell.showtraceback() | |
636 |
|
636 | |||
637 | def start_app(self): |
|
637 | def start_app(self): | |
|
638 | check_for_old_config(self.ipython_dir) | |||
638 | if self.master_config.Global.interact: |
|
639 | if self.master_config.Global.interact: | |
639 | self.log.debug("Starting IPython's mainloop...") |
|
640 | self.log.debug("Starting IPython's mainloop...") | |
640 | self.shell.mainloop() |
|
641 | self.shell.mainloop() | |
641 | else: |
|
642 | else: | |
642 | self.log.debug("IPython not interactive, start_app is no-op...") |
|
643 | self.log.debug("IPython not interactive, start_app is no-op...") | |
643 |
|
644 | |||
644 |
|
645 | |||
645 | def load_default_config(ipython_dir=None): |
|
646 | def load_default_config(ipython_dir=None): | |
646 | """Load the default config file from the default ipython_dir. |
|
647 | """Load the default config file from the default ipython_dir. | |
647 |
|
648 | |||
648 | This is useful for embedded shells. |
|
649 | This is useful for embedded shells. | |
649 | """ |
|
650 | """ | |
650 | if ipython_dir is None: |
|
651 | if ipython_dir is None: | |
651 | ipython_dir = get_ipython_dir() |
|
652 | ipython_dir = get_ipython_dir() | |
652 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) |
|
653 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) | |
653 | config = cl.load_config() |
|
654 | config = cl.load_config() | |
654 | return config |
|
655 | return config | |
655 |
|
656 | |||
656 |
|
657 | |||
657 | def launch_new_instance(): |
|
658 | def launch_new_instance(): | |
658 | """Create and run a full blown IPython instance""" |
|
659 | """Create and run a full blown IPython instance""" | |
659 | app = IPythonApp() |
|
660 | app = IPythonApp() | |
660 | app.start() |
|
661 | app.start() | |
661 |
|
662 | |||
662 |
|
663 | |||
663 | if __name__ == '__main__': |
|
664 | if __name__ == '__main__': | |
664 | launch_new_instance() |
|
665 | launch_new_instance() |
@@ -1,401 +1,421 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | Utilities for path handling. |
|
3 | Utilities for path handling. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
7 | # Copyright (C) 2008-2009 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import os |
|
17 | import os | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | import IPython |
|
20 | import IPython | |
|
21 | from IPython.utils import warn | |||
21 | from IPython.utils.process import system |
|
22 | from IPython.utils.process import system | |
22 | from IPython.utils.importstring import import_item |
|
23 | from IPython.utils.importstring import import_item | |
23 |
|
24 | |||
24 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
25 | # Code |
|
26 | # Code | |
26 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
27 |
|
28 | |||
28 | fs_encoding = sys.getfilesystemencoding() |
|
29 | fs_encoding = sys.getfilesystemencoding() | |
29 |
|
30 | |||
30 | def _cast_unicode(s, enc=None): |
|
31 | def _cast_unicode(s, enc=None): | |
31 | """Turn 8-bit strings into unicode.""" |
|
32 | """Turn 8-bit strings into unicode.""" | |
32 | if isinstance(s, bytes): |
|
33 | if isinstance(s, bytes): | |
33 | enc = enc or sys.getdefaultencoding() |
|
34 | enc = enc or sys.getdefaultencoding() | |
34 | return s.decode(enc) |
|
35 | return s.decode(enc) | |
35 | return s |
|
36 | return s | |
36 |
|
37 | |||
37 |
|
38 | |||
38 | def _get_long_path_name(path): |
|
39 | def _get_long_path_name(path): | |
39 | """Dummy no-op.""" |
|
40 | """Dummy no-op.""" | |
40 | return path |
|
41 | return path | |
41 |
|
42 | |||
42 | if sys.platform == 'win32': |
|
43 | if sys.platform == 'win32': | |
43 | def _get_long_path_name(path): |
|
44 | def _get_long_path_name(path): | |
44 | """Get a long path name (expand ~) on Windows using ctypes. |
|
45 | """Get a long path name (expand ~) on Windows using ctypes. | |
45 |
|
46 | |||
46 | Examples |
|
47 | Examples | |
47 | -------- |
|
48 | -------- | |
48 |
|
49 | |||
49 | >>> get_long_path_name('c:\\docume~1') |
|
50 | >>> get_long_path_name('c:\\docume~1') | |
50 | u'c:\\\\Documents and Settings' |
|
51 | u'c:\\\\Documents and Settings' | |
51 |
|
52 | |||
52 | """ |
|
53 | """ | |
53 | try: |
|
54 | try: | |
54 | import ctypes |
|
55 | import ctypes | |
55 | except ImportError: |
|
56 | except ImportError: | |
56 | raise ImportError('you need to have ctypes installed for this to work') |
|
57 | raise ImportError('you need to have ctypes installed for this to work') | |
57 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
58 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW | |
58 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
59 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, | |
59 | ctypes.c_uint ] |
|
60 | ctypes.c_uint ] | |
60 |
|
61 | |||
61 | buf = ctypes.create_unicode_buffer(260) |
|
62 | buf = ctypes.create_unicode_buffer(260) | |
62 | rv = _GetLongPathName(path, buf, 260) |
|
63 | rv = _GetLongPathName(path, buf, 260) | |
63 | if rv == 0 or rv > 260: |
|
64 | if rv == 0 or rv > 260: | |
64 | return path |
|
65 | return path | |
65 | else: |
|
66 | else: | |
66 | return buf.value |
|
67 | return buf.value | |
67 |
|
68 | |||
68 |
|
69 | |||
69 | def get_long_path_name(path): |
|
70 | def get_long_path_name(path): | |
70 | """Expand a path into its long form. |
|
71 | """Expand a path into its long form. | |
71 |
|
72 | |||
72 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
73 | On Windows this expands any ~ in the paths. On other platforms, it is | |
73 | a null operation. |
|
74 | a null operation. | |
74 | """ |
|
75 | """ | |
75 | return _get_long_path_name(path) |
|
76 | return _get_long_path_name(path) | |
76 |
|
77 | |||
77 |
|
78 | |||
78 | def get_py_filename(name): |
|
79 | def get_py_filename(name): | |
79 | """Return a valid python filename in the current directory. |
|
80 | """Return a valid python filename in the current directory. | |
80 |
|
81 | |||
81 | If the given name is not a file, it adds '.py' and searches again. |
|
82 | If the given name is not a file, it adds '.py' and searches again. | |
82 | Raises IOError with an informative message if the file isn't found.""" |
|
83 | Raises IOError with an informative message if the file isn't found.""" | |
83 |
|
84 | |||
84 | name = os.path.expanduser(name) |
|
85 | name = os.path.expanduser(name) | |
85 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
86 | if not os.path.isfile(name) and not name.endswith('.py'): | |
86 | name += '.py' |
|
87 | name += '.py' | |
87 | if os.path.isfile(name): |
|
88 | if os.path.isfile(name): | |
88 | return name |
|
89 | return name | |
89 | else: |
|
90 | else: | |
90 | raise IOError,'File `%s` not found.' % name |
|
91 | raise IOError,'File `%s` not found.' % name | |
91 |
|
92 | |||
92 |
|
93 | |||
93 | def filefind(filename, path_dirs=None): |
|
94 | def filefind(filename, path_dirs=None): | |
94 | """Find a file by looking through a sequence of paths. |
|
95 | """Find a file by looking through a sequence of paths. | |
95 |
|
96 | |||
96 | This iterates through a sequence of paths looking for a file and returns |
|
97 | This iterates through a sequence of paths looking for a file and returns | |
97 | the full, absolute path of the first occurence of the file. If no set of |
|
98 | the full, absolute path of the first occurence of the file. If no set of | |
98 | path dirs is given, the filename is tested as is, after running through |
|
99 | path dirs is given, the filename is tested as is, after running through | |
99 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
100 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: | |
100 |
|
101 | |||
101 | filefind('myfile.txt') |
|
102 | filefind('myfile.txt') | |
102 |
|
103 | |||
103 | will find the file in the current working dir, but:: |
|
104 | will find the file in the current working dir, but:: | |
104 |
|
105 | |||
105 | filefind('~/myfile.txt') |
|
106 | filefind('~/myfile.txt') | |
106 |
|
107 | |||
107 | Will find the file in the users home directory. This function does not |
|
108 | Will find the file in the users home directory. This function does not | |
108 | automatically try any paths, such as the cwd or the user's home directory. |
|
109 | automatically try any paths, such as the cwd or the user's home directory. | |
109 |
|
110 | |||
110 | Parameters |
|
111 | Parameters | |
111 | ---------- |
|
112 | ---------- | |
112 | filename : str |
|
113 | filename : str | |
113 | The filename to look for. |
|
114 | The filename to look for. | |
114 | path_dirs : str, None or sequence of str |
|
115 | path_dirs : str, None or sequence of str | |
115 | The sequence of paths to look for the file in. If None, the filename |
|
116 | The sequence of paths to look for the file in. If None, the filename | |
116 | need to be absolute or be in the cwd. If a string, the string is |
|
117 | need to be absolute or be in the cwd. If a string, the string is | |
117 | put into a sequence and the searched. If a sequence, walk through |
|
118 | put into a sequence and the searched. If a sequence, walk through | |
118 | each element and join with ``filename``, calling :func:`expandvars` |
|
119 | each element and join with ``filename``, calling :func:`expandvars` | |
119 | and :func:`expanduser` before testing for existence. |
|
120 | and :func:`expanduser` before testing for existence. | |
120 |
|
121 | |||
121 | Returns |
|
122 | Returns | |
122 | ------- |
|
123 | ------- | |
123 | Raises :exc:`IOError` or returns absolute path to file. |
|
124 | Raises :exc:`IOError` or returns absolute path to file. | |
124 | """ |
|
125 | """ | |
125 |
|
126 | |||
126 | # If paths are quoted, abspath gets confused, strip them... |
|
127 | # If paths are quoted, abspath gets confused, strip them... | |
127 | filename = filename.strip('"').strip("'") |
|
128 | filename = filename.strip('"').strip("'") | |
128 | # If the input is an absolute path, just check it exists |
|
129 | # If the input is an absolute path, just check it exists | |
129 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
130 | if os.path.isabs(filename) and os.path.isfile(filename): | |
130 | return filename |
|
131 | return filename | |
131 |
|
132 | |||
132 | if path_dirs is None: |
|
133 | if path_dirs is None: | |
133 | path_dirs = ("",) |
|
134 | path_dirs = ("",) | |
134 | elif isinstance(path_dirs, basestring): |
|
135 | elif isinstance(path_dirs, basestring): | |
135 | path_dirs = (path_dirs,) |
|
136 | path_dirs = (path_dirs,) | |
136 |
|
137 | |||
137 | for path in path_dirs: |
|
138 | for path in path_dirs: | |
138 | if path == '.': path = os.getcwd() |
|
139 | if path == '.': path = os.getcwd() | |
139 | testname = expand_path(os.path.join(path, filename)) |
|
140 | testname = expand_path(os.path.join(path, filename)) | |
140 | if os.path.isfile(testname): |
|
141 | if os.path.isfile(testname): | |
141 | return os.path.abspath(testname) |
|
142 | return os.path.abspath(testname) | |
142 |
|
143 | |||
143 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
144 | raise IOError("File %r does not exist in any of the search paths: %r" % | |
144 | (filename, path_dirs) ) |
|
145 | (filename, path_dirs) ) | |
145 |
|
146 | |||
146 |
|
147 | |||
147 | class HomeDirError(Exception): |
|
148 | class HomeDirError(Exception): | |
148 | pass |
|
149 | pass | |
149 |
|
150 | |||
150 |
|
151 | |||
151 | def get_home_dir(): |
|
152 | def get_home_dir(): | |
152 | """Return the closest possible equivalent to a 'home' directory. |
|
153 | """Return the closest possible equivalent to a 'home' directory. | |
153 |
|
154 | |||
154 | * On POSIX, we try $HOME. |
|
155 | * On POSIX, we try $HOME. | |
155 | * On Windows we try: |
|
156 | * On Windows we try: | |
156 | - %HOMESHARE% |
|
157 | - %HOMESHARE% | |
157 | - %HOMEDRIVE\%HOMEPATH% |
|
158 | - %HOMEDRIVE\%HOMEPATH% | |
158 | - %USERPROFILE% |
|
159 | - %USERPROFILE% | |
159 | - Registry hack for My Documents |
|
160 | - Registry hack for My Documents | |
160 | - %HOME%: rare, but some people with unix-like setups may have defined it |
|
161 | - %HOME%: rare, but some people with unix-like setups may have defined it | |
161 | * On Dos C:\ |
|
162 | * On Dos C:\ | |
162 |
|
163 | |||
163 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
164 | Currently only Posix and NT are implemented, a HomeDirError exception is | |
164 | raised for all other OSes. |
|
165 | raised for all other OSes. | |
165 | """ |
|
166 | """ | |
166 |
|
167 | |||
167 | isdir = os.path.isdir |
|
168 | isdir = os.path.isdir | |
168 | env = os.environ |
|
169 | env = os.environ | |
169 |
|
170 | |||
170 | # first, check py2exe distribution root directory for _ipython. |
|
171 | # first, check py2exe distribution root directory for _ipython. | |
171 | # This overrides all. Normally does not exist. |
|
172 | # This overrides all. Normally does not exist. | |
172 |
|
173 | |||
173 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
174 | if hasattr(sys, "frozen"): #Is frozen by py2exe | |
174 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
175 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file | |
175 | root, rest = IPython.__file__.lower().split('library.zip') |
|
176 | root, rest = IPython.__file__.lower().split('library.zip') | |
176 | else: |
|
177 | else: | |
177 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
178 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") | |
178 | root=os.path.abspath(root).rstrip('\\') |
|
179 | root=os.path.abspath(root).rstrip('\\') | |
179 | if isdir(os.path.join(root, '_ipython')): |
|
180 | if isdir(os.path.join(root, '_ipython')): | |
180 | os.environ["IPYKITROOT"] = root |
|
181 | os.environ["IPYKITROOT"] = root | |
181 | return _cast_unicode(root, fs_encoding) |
|
182 | return _cast_unicode(root, fs_encoding) | |
182 |
|
183 | |||
183 | if os.name == 'posix': |
|
184 | if os.name == 'posix': | |
184 | # Linux, Unix, AIX, OS X |
|
185 | # Linux, Unix, AIX, OS X | |
185 | try: |
|
186 | try: | |
186 | homedir = env['HOME'] |
|
187 | homedir = env['HOME'] | |
187 | except KeyError: |
|
188 | except KeyError: | |
188 | # Last-ditch attempt at finding a suitable $HOME, on systems where |
|
189 | # Last-ditch attempt at finding a suitable $HOME, on systems where | |
189 | # it may not be defined in the environment but the system shell |
|
190 | # it may not be defined in the environment but the system shell | |
190 | # still knows it - reported once as: |
|
191 | # still knows it - reported once as: | |
191 | # https://github.com/ipython/ipython/issues/154 |
|
192 | # https://github.com/ipython/ipython/issues/154 | |
192 | from subprocess import Popen, PIPE |
|
193 | from subprocess import Popen, PIPE | |
193 | homedir = Popen('echo $HOME', shell=True, |
|
194 | homedir = Popen('echo $HOME', shell=True, | |
194 | stdout=PIPE).communicate()[0].strip() |
|
195 | stdout=PIPE).communicate()[0].strip() | |
195 | if homedir: |
|
196 | if homedir: | |
196 | return _cast_unicode(homedir, fs_encoding) |
|
197 | return _cast_unicode(homedir, fs_encoding) | |
197 | else: |
|
198 | else: | |
198 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') |
|
199 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') | |
199 | else: |
|
200 | else: | |
200 | return _cast_unicode(homedir, fs_encoding) |
|
201 | return _cast_unicode(homedir, fs_encoding) | |
201 | elif os.name == 'nt': |
|
202 | elif os.name == 'nt': | |
202 | # Now for win9x, XP, Vista, 7? |
|
203 | # Now for win9x, XP, Vista, 7? | |
203 | # For some strange reason all of these return 'nt' for os.name. |
|
204 | # For some strange reason all of these return 'nt' for os.name. | |
204 | # First look for a network home directory. This will return the UNC |
|
205 | # First look for a network home directory. This will return the UNC | |
205 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This |
|
206 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This | |
206 | # is needed when running IPython on cluster where all paths have to |
|
207 | # is needed when running IPython on cluster where all paths have to | |
207 | # be UNC. |
|
208 | # be UNC. | |
208 | try: |
|
209 | try: | |
209 | homedir = env['HOMESHARE'] |
|
210 | homedir = env['HOMESHARE'] | |
210 | except KeyError: |
|
211 | except KeyError: | |
211 | pass |
|
212 | pass | |
212 | else: |
|
213 | else: | |
213 | if isdir(homedir): |
|
214 | if isdir(homedir): | |
214 | return _cast_unicode(homedir, fs_encoding) |
|
215 | return _cast_unicode(homedir, fs_encoding) | |
215 |
|
216 | |||
216 | # Now look for a local home directory |
|
217 | # Now look for a local home directory | |
217 | try: |
|
218 | try: | |
218 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
219 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) | |
219 | except KeyError: |
|
220 | except KeyError: | |
220 | pass |
|
221 | pass | |
221 | else: |
|
222 | else: | |
222 | if isdir(homedir): |
|
223 | if isdir(homedir): | |
223 | return _cast_unicode(homedir, fs_encoding) |
|
224 | return _cast_unicode(homedir, fs_encoding) | |
224 |
|
225 | |||
225 | # Now the users profile directory |
|
226 | # Now the users profile directory | |
226 | try: |
|
227 | try: | |
227 | homedir = os.path.join(env['USERPROFILE']) |
|
228 | homedir = os.path.join(env['USERPROFILE']) | |
228 | except KeyError: |
|
229 | except KeyError: | |
229 | pass |
|
230 | pass | |
230 | else: |
|
231 | else: | |
231 | if isdir(homedir): |
|
232 | if isdir(homedir): | |
232 | return _cast_unicode(homedir, fs_encoding) |
|
233 | return _cast_unicode(homedir, fs_encoding) | |
233 |
|
234 | |||
234 | # Use the registry to get the 'My Documents' folder. |
|
235 | # Use the registry to get the 'My Documents' folder. | |
235 | try: |
|
236 | try: | |
236 | import _winreg as wreg |
|
237 | import _winreg as wreg | |
237 | key = wreg.OpenKey( |
|
238 | key = wreg.OpenKey( | |
238 | wreg.HKEY_CURRENT_USER, |
|
239 | wreg.HKEY_CURRENT_USER, | |
239 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
240 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" | |
240 | ) |
|
241 | ) | |
241 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
242 | homedir = wreg.QueryValueEx(key,'Personal')[0] | |
242 | key.Close() |
|
243 | key.Close() | |
243 | except: |
|
244 | except: | |
244 | pass |
|
245 | pass | |
245 | else: |
|
246 | else: | |
246 | if isdir(homedir): |
|
247 | if isdir(homedir): | |
247 | return _cast_unicode(homedir, fs_encoding) |
|
248 | return _cast_unicode(homedir, fs_encoding) | |
248 |
|
249 | |||
249 | # A user with a lot of unix tools in win32 may have defined $HOME. |
|
250 | # A user with a lot of unix tools in win32 may have defined $HOME. | |
250 | # Try this as a last ditch option. |
|
251 | # Try this as a last ditch option. | |
251 | try: |
|
252 | try: | |
252 | homedir = env['HOME'] |
|
253 | homedir = env['HOME'] | |
253 | except KeyError: |
|
254 | except KeyError: | |
254 | pass |
|
255 | pass | |
255 | else: |
|
256 | else: | |
256 | if isdir(homedir): |
|
257 | if isdir(homedir): | |
257 | return _cast_unicode(homedir, fs_encoding) |
|
258 | return _cast_unicode(homedir, fs_encoding) | |
258 |
|
259 | |||
259 | # If all else fails, raise HomeDirError |
|
260 | # If all else fails, raise HomeDirError | |
260 | raise HomeDirError('No valid home directory could be found') |
|
261 | raise HomeDirError('No valid home directory could be found') | |
261 | elif os.name == 'dos': |
|
262 | elif os.name == 'dos': | |
262 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
263 | # Desperate, may do absurd things in classic MacOS. May work under DOS. | |
263 | return u'C:\\' |
|
264 | return u'C:\\' | |
264 | else: |
|
265 | else: | |
265 | raise HomeDirError('No valid home directory could be found for your OS') |
|
266 | raise HomeDirError('No valid home directory could be found for your OS') | |
266 |
|
267 | |||
267 | def get_xdg_dir(): |
|
268 | def get_xdg_dir(): | |
268 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. |
|
269 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. | |
269 |
|
270 | |||
270 | This is only for posix (Linux,Unix,OS X, etc) systems. |
|
271 | This is only for posix (Linux,Unix,OS X, etc) systems. | |
271 | """ |
|
272 | """ | |
272 |
|
273 | |||
273 | isdir = os.path.isdir |
|
274 | isdir = os.path.isdir | |
274 | env = os.environ |
|
275 | env = os.environ | |
275 |
|
276 | |||
276 | if os.name == 'posix': |
|
277 | if os.name == 'posix': | |
277 | # Linux, Unix, AIX, OS X |
|
278 | # Linux, Unix, AIX, OS X | |
278 | # use ~/.config if not set OR empty |
|
279 | # use ~/.config if not set OR empty | |
279 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') |
|
280 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') | |
280 | if xdg and isdir(xdg): |
|
281 | if xdg and isdir(xdg): | |
281 | return _cast_unicode(xdg, fs_encoding) |
|
282 | return _cast_unicode(xdg, fs_encoding) | |
282 |
|
283 | |||
283 | return None |
|
284 | return None | |
284 |
|
285 | |||
285 |
|
286 | |||
286 | def get_ipython_dir(): |
|
287 | def get_ipython_dir(): | |
287 | """Get the IPython directory for this platform and user. |
|
288 | """Get the IPython directory for this platform and user. | |
288 |
|
289 | |||
289 | This uses the logic in `get_home_dir` to find the home directory |
|
290 | This uses the logic in `get_home_dir` to find the home directory | |
290 | and the adds .ipython to the end of the path. |
|
291 | and the adds .ipython to the end of the path. | |
291 | """ |
|
292 | """ | |
292 |
|
293 | |||
293 | env = os.environ |
|
294 | env = os.environ | |
294 | pjoin = os.path.join |
|
295 | pjoin = os.path.join | |
295 | exists = os.path.exists |
|
296 | exists = os.path.exists | |
296 |
|
297 | |||
297 | ipdir_def = '.ipython' |
|
298 | ipdir_def = '.ipython' | |
298 | xdg_def = 'ipython' |
|
299 | xdg_def = 'ipython' | |
299 |
|
300 | |||
300 | home_dir = get_home_dir() |
|
301 | home_dir = get_home_dir() | |
301 | xdg_dir = get_xdg_dir() |
|
302 | xdg_dir = get_xdg_dir() | |
302 | # import pdb; pdb.set_trace() # dbg |
|
303 | # import pdb; pdb.set_trace() # dbg | |
303 | ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None)) |
|
304 | ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None)) | |
304 | if ipdir is None: |
|
305 | if ipdir is None: | |
305 | # not set explicitly, use XDG_CONFIG_HOME or HOME |
|
306 | # not set explicitly, use XDG_CONFIG_HOME or HOME | |
306 | home_ipdir = pjoin(home_dir, ipdir_def) |
|
307 | home_ipdir = pjoin(home_dir, ipdir_def) | |
307 | if xdg_dir: |
|
308 | if xdg_dir: | |
308 | # use XDG, as long as the user isn't already |
|
309 | # use XDG, as long as the user isn't already | |
309 | # using $HOME/.ipython and *not* XDG/ipython |
|
310 | # using $HOME/.ipython and *not* XDG/ipython | |
310 |
|
311 | |||
311 | xdg_ipdir = pjoin(xdg_dir, xdg_def) |
|
312 | xdg_ipdir = pjoin(xdg_dir, xdg_def) | |
312 |
|
313 | |||
313 | if exists(xdg_ipdir) or not exists(home_ipdir): |
|
314 | if exists(xdg_ipdir) or not exists(home_ipdir): | |
314 | ipdir = xdg_ipdir |
|
315 | ipdir = xdg_ipdir | |
315 |
|
316 | |||
316 | if ipdir is None: |
|
317 | if ipdir is None: | |
317 | # not using XDG |
|
318 | # not using XDG | |
318 | ipdir = home_ipdir |
|
319 | ipdir = home_ipdir | |
319 |
|
320 | |||
320 | return _cast_unicode(ipdir, fs_encoding) |
|
321 | return _cast_unicode(ipdir, fs_encoding) | |
321 |
|
322 | |||
322 |
|
323 | |||
323 | def get_ipython_package_dir(): |
|
324 | def get_ipython_package_dir(): | |
324 | """Get the base directory where IPython itself is installed.""" |
|
325 | """Get the base directory where IPython itself is installed.""" | |
325 | ipdir = os.path.dirname(IPython.__file__) |
|
326 | ipdir = os.path.dirname(IPython.__file__) | |
326 | return _cast_unicode(ipdir, fs_encoding) |
|
327 | return _cast_unicode(ipdir, fs_encoding) | |
327 |
|
328 | |||
328 |
|
329 | |||
329 | def get_ipython_module_path(module_str): |
|
330 | def get_ipython_module_path(module_str): | |
330 | """Find the path to an IPython module in this version of IPython. |
|
331 | """Find the path to an IPython module in this version of IPython. | |
331 |
|
332 | |||
332 | This will always find the version of the module that is in this importable |
|
333 | This will always find the version of the module that is in this importable | |
333 | IPython package. This will always return the path to the ``.py`` |
|
334 | IPython package. This will always return the path to the ``.py`` | |
334 | version of the module. |
|
335 | version of the module. | |
335 | """ |
|
336 | """ | |
336 | if module_str == 'IPython': |
|
337 | if module_str == 'IPython': | |
337 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
338 | return os.path.join(get_ipython_package_dir(), '__init__.py') | |
338 | mod = import_item(module_str) |
|
339 | mod = import_item(module_str) | |
339 | the_path = mod.__file__.replace('.pyc', '.py') |
|
340 | the_path = mod.__file__.replace('.pyc', '.py') | |
340 | the_path = the_path.replace('.pyo', '.py') |
|
341 | the_path = the_path.replace('.pyo', '.py') | |
341 | return _cast_unicode(the_path, fs_encoding) |
|
342 | return _cast_unicode(the_path, fs_encoding) | |
342 |
|
343 | |||
343 |
|
344 | |||
344 | def expand_path(s): |
|
345 | def expand_path(s): | |
345 | """Expand $VARS and ~names in a string, like a shell |
|
346 | """Expand $VARS and ~names in a string, like a shell | |
346 |
|
347 | |||
347 | :Examples: |
|
348 | :Examples: | |
348 |
|
349 | |||
349 | In [2]: os.environ['FOO']='test' |
|
350 | In [2]: os.environ['FOO']='test' | |
350 |
|
351 | |||
351 | In [3]: expand_path('variable FOO is $FOO') |
|
352 | In [3]: expand_path('variable FOO is $FOO') | |
352 | Out[3]: 'variable FOO is test' |
|
353 | Out[3]: 'variable FOO is test' | |
353 | """ |
|
354 | """ | |
354 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
355 | # This is a pretty subtle hack. When expand user is given a UNC path | |
355 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
356 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes | |
356 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
357 | # the $ to get (\\server\share\%username%). I think it considered $ | |
357 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
358 | # alone an empty var. But, we need the $ to remains there (it indicates | |
358 | # a hidden share). |
|
359 | # a hidden share). | |
359 | if os.name=='nt': |
|
360 | if os.name=='nt': | |
360 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
361 | s = s.replace('$\\', 'IPYTHON_TEMP') | |
361 | s = os.path.expandvars(os.path.expanduser(s)) |
|
362 | s = os.path.expandvars(os.path.expanduser(s)) | |
362 | if os.name=='nt': |
|
363 | if os.name=='nt': | |
363 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
364 | s = s.replace('IPYTHON_TEMP', '$\\') | |
364 | return s |
|
365 | return s | |
365 |
|
366 | |||
366 |
|
367 | |||
367 | def target_outdated(target,deps): |
|
368 | def target_outdated(target,deps): | |
368 | """Determine whether a target is out of date. |
|
369 | """Determine whether a target is out of date. | |
369 |
|
370 | |||
370 | target_outdated(target,deps) -> 1/0 |
|
371 | target_outdated(target,deps) -> 1/0 | |
371 |
|
372 | |||
372 | deps: list of filenames which MUST exist. |
|
373 | deps: list of filenames which MUST exist. | |
373 | target: single filename which may or may not exist. |
|
374 | target: single filename which may or may not exist. | |
374 |
|
375 | |||
375 | If target doesn't exist or is older than any file listed in deps, return |
|
376 | If target doesn't exist or is older than any file listed in deps, return | |
376 | true, otherwise return false. |
|
377 | true, otherwise return false. | |
377 | """ |
|
378 | """ | |
378 | try: |
|
379 | try: | |
379 | target_time = os.path.getmtime(target) |
|
380 | target_time = os.path.getmtime(target) | |
380 | except os.error: |
|
381 | except os.error: | |
381 | return 1 |
|
382 | return 1 | |
382 | for dep in deps: |
|
383 | for dep in deps: | |
383 | dep_time = os.path.getmtime(dep) |
|
384 | dep_time = os.path.getmtime(dep) | |
384 | if dep_time > target_time: |
|
385 | if dep_time > target_time: | |
385 | #print "For target",target,"Dep failed:",dep # dbg |
|
386 | #print "For target",target,"Dep failed:",dep # dbg | |
386 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
387 | #print "times (dep,tar):",dep_time,target_time # dbg | |
387 | return 1 |
|
388 | return 1 | |
388 | return 0 |
|
389 | return 0 | |
389 |
|
390 | |||
390 |
|
391 | |||
391 | def target_update(target,deps,cmd): |
|
392 | def target_update(target,deps,cmd): | |
392 | """Update a target with a given command given a list of dependencies. |
|
393 | """Update a target with a given command given a list of dependencies. | |
393 |
|
394 | |||
394 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
395 | target_update(target,deps,cmd) -> runs cmd if target is outdated. | |
395 |
|
396 | |||
396 | This is just a wrapper around target_outdated() which calls the given |
|
397 | This is just a wrapper around target_outdated() which calls the given | |
397 | command if target is outdated.""" |
|
398 | command if target is outdated.""" | |
398 |
|
399 | |||
399 | if target_outdated(target,deps): |
|
400 | if target_outdated(target,deps): | |
400 | system(cmd) |
|
401 | system(cmd) | |
401 |
|
402 | |||
|
403 | def check_for_old_config(ipython_dir=None): | |||
|
404 | """Check for old config files, and present a warning if they exist. | |||
|
405 | ||||
|
406 | A link to the docs of the new config is included in the message. | |||
|
407 | ||||
|
408 | This should mitigate confusion with the transition to the new | |||
|
409 | config system in 0.11. | |||
|
410 | """ | |||
|
411 | if ipython_dir is None: | |||
|
412 | ipython_dir = get_ipython_dir() | |||
|
413 | ||||
|
414 | old_configs = ['ipy_user_conf.py', 'ipythonrc'] | |||
|
415 | for cfg in old_configs: | |||
|
416 | f = os.path.join(ipython_dir, cfg) | |||
|
417 | if os.path.exists(f): | |||
|
418 | warn.warn("""Found old IPython config file %r. | |||
|
419 | The IPython configuration system has changed as of 0.11, and this file will be ignored. | |||
|
420 | See http://ipython.github.com/ipython-doc/dev/config for details on the new config system. | |||
|
421 | The current default config file is 'ipython_config.py'"""%f) |
General Comments 0
You need to be logged in to leave comments.
Login now