##// END OF EJS Templates
add ignore_old_config configurable...
MinRK -
Show More
@@ -1,161 +1,165 b''
1 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # If you still use multiple versions of IPytho on the same machine,
15 # set this to True to suppress warnings about old configuration files
16 # c.Global.ignore_old_config = False
17
14 # Set this to determine the detail of what is logged at startup.
18 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
19 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
20 # c.Global.log_level = 20
17
21
18 # This should be a list of importable Python modules that have an
22 # This should be a list of importable Python modules that have an
19 # load_ipython_extension(ip) method. This method gets called when the extension
23 # load_ipython_extension(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
24 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
25 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
26 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
27 # c.Global.extensions = [
24 # 'myextension'
28 # 'myextension'
25 # ]
29 # ]
26
30
27 # These lines are run in IPython in the user's namespace after extensions
31 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
32 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
33 # c.Global.exec_lines = [
30 # 'import numpy',
34 # 'import numpy',
31 # 'a = 10; b = 20',
35 # 'a = 10; b = 20',
32 # '1/0'
36 # '1/0'
33 # ]
37 # ]
34
38
35 # These files are run in IPython in the user's namespace. Files with a .py
39 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
40 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
41 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
42 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
43 # c.Global.exec_files = [
40 # 'mycode.py',
44 # 'mycode.py',
41 # 'fancy.ipy'
45 # 'fancy.ipy'
42 # ]
46 # ]
43
47
44 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
45 # InteractiveShell options
49 # InteractiveShell options
46 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
47
51
48 # c.InteractiveShell.autocall = 1
52 # c.InteractiveShell.autocall = 1
49
53
50 # c.TerminalInteractiveShell.autoedit_syntax = False
54 # c.TerminalInteractiveShell.autoedit_syntax = False
51
55
52 # c.InteractiveShell.autoindent = True
56 # c.InteractiveShell.autoindent = True
53
57
54 # c.InteractiveShell.automagic = False
58 # c.InteractiveShell.automagic = False
55
59
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
60 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
61
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
62 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59
63
60 # c.InteractiveShell.cache_size = 1000
64 # c.InteractiveShell.cache_size = 1000
61
65
62 # c.InteractiveShell.colors = 'LightBG'
66 # c.InteractiveShell.colors = 'LightBG'
63
67
64 # c.InteractiveShell.color_info = True
68 # c.InteractiveShell.color_info = True
65
69
66 # c.TerminalInteractiveShell.confirm_exit = True
70 # c.TerminalInteractiveShell.confirm_exit = True
67
71
68 # c.InteractiveShell.deep_reload = False
72 # c.InteractiveShell.deep_reload = False
69
73
70 # c.TerminalInteractiveShell.editor = 'nano'
74 # c.TerminalInteractiveShell.editor = 'nano'
71
75
72 # c.InteractiveShell.logstart = True
76 # c.InteractiveShell.logstart = True
73
77
74 # c.InteractiveShell.logfile = u'ipython_log.py'
78 # c.InteractiveShell.logfile = u'ipython_log.py'
75
79
76 # c.InteractiveShell.logappend = u'mylog.py'
80 # c.InteractiveShell.logappend = u'mylog.py'
77
81
78 # c.InteractiveShell.object_info_string_level = 0
82 # c.InteractiveShell.object_info_string_level = 0
79
83
80 # c.TerminalInteractiveShell.pager = 'less'
84 # c.TerminalInteractiveShell.pager = 'less'
81
85
82 # c.InteractiveShell.pdb = False
86 # c.InteractiveShell.pdb = False
83
87
84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
88 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
89 # c.InteractiveShell.prompt_in2 = ' .\D.: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
90 # c.InteractiveShell.prompt_out = 'Out[\#]: '
87 # c.InteractiveShell.prompts_pad_left = True
91 # c.InteractiveShell.prompts_pad_left = True
88
92
89 # c.InteractiveShell.quiet = False
93 # c.InteractiveShell.quiet = False
90
94
91 # c.InteractiveShell.history_length = 10000
95 # c.InteractiveShell.history_length = 10000
92
96
93 # Readline
97 # Readline
94 # c.InteractiveShell.readline_use = True
98 # c.InteractiveShell.readline_use = True
95
99
96 # c.InteractiveShell.readline_parse_and_bind = [
100 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
101 # 'tab: complete',
98 # '"\C-l": possible-completions',
102 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
103 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
104 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
105 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
106 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
107 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
108 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
109 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
110 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
111 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
112 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
113 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
114 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
115 # '"\C-u": unix-line-discard',
112 # ]
116 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
117 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
118 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
119 # c.InteractiveShell.readline_omit__names = 0
116
120
117 # c.TerminalInteractiveShell.screen_length = 0
121 # c.TerminalInteractiveShell.screen_length = 0
118
122
119 # c.InteractiveShell.separate_in = '\n'
123 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
124 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
125 # c.InteractiveShell.separate_out2 = ''
122
126
123 # c.TerminalInteractiveShell.term_title = False
127 # c.TerminalInteractiveShell.term_title = False
124
128
125 # c.InteractiveShell.wildcards_case_sensitive = True
129 # c.InteractiveShell.wildcards_case_sensitive = True
126
130
127 # c.InteractiveShell.xmode = 'Context'
131 # c.InteractiveShell.xmode = 'Context'
128
132
129 #-----------------------------------------------------------------------------
133 #-----------------------------------------------------------------------------
130 # Formatter and display options
134 # Formatter and display options
131 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
132
136
133 # c.PlainTextFormatter.pprint = True
137 # c.PlainTextFormatter.pprint = True
134
138
135 #-----------------------------------------------------------------------------
139 #-----------------------------------------------------------------------------
136 # PrefilterManager options
140 # PrefilterManager options
137 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
138
142
139 # c.PrefilterManager.multi_line_specials = True
143 # c.PrefilterManager.multi_line_specials = True
140
144
141 #-----------------------------------------------------------------------------
145 #-----------------------------------------------------------------------------
142 # AliasManager options
146 # AliasManager options
143 #-----------------------------------------------------------------------------
147 #-----------------------------------------------------------------------------
144
148
145 # Do this to disable all defaults
149 # Do this to disable all defaults
146 # c.AliasManager.default_aliases = []
150 # c.AliasManager.default_aliases = []
147
151
148 # c.AliasManager.user_aliases = [
152 # c.AliasManager.user_aliases = [
149 # ('foo', 'echo Hi')
153 # ('foo', 'echo Hi')
150 # ]
154 # ]
151
155
152 #-----------------------------------------------------------------------------
156 #-----------------------------------------------------------------------------
153 # HistoryManager options
157 # HistoryManager options
154 #-----------------------------------------------------------------------------
158 #-----------------------------------------------------------------------------
155
159
156 # Enable logging output as well as input to the database.
160 # Enable logging output as well as input to the database.
157 # c.HistoryManager.db_log_output = False
161 # c.HistoryManager.db_log_output = False
158
162
159 # Only write to the database every n commands - this can save disk
163 # Only write to the database every n commands - this can save disk
160 # access (and hence power) over the default of writing on every command.
164 # access (and hence power) over the default of writing on every command.
161 # c.HistoryManager.db_cache_size = 0
165 # c.HistoryManager.db_cache_size = 0
@@ -1,665 +1,666 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, check_for_old_config
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 not getattr(self.master_config.Global, 'ignore_old_config', False):
639 check_for_old_config(self.ipython_dir)
639 if self.master_config.Global.interact:
640 if self.master_config.Global.interact:
640 self.log.debug("Starting IPython's mainloop...")
641 self.log.debug("Starting IPython's mainloop...")
641 self.shell.mainloop()
642 self.shell.mainloop()
642 else:
643 else:
643 self.log.debug("IPython not interactive, start_app is no-op...")
644 self.log.debug("IPython not interactive, start_app is no-op...")
644
645
645
646
646 def load_default_config(ipython_dir=None):
647 def load_default_config(ipython_dir=None):
647 """Load the default config file from the default ipython_dir.
648 """Load the default config file from the default ipython_dir.
648
649
649 This is useful for embedded shells.
650 This is useful for embedded shells.
650 """
651 """
651 if ipython_dir is None:
652 if ipython_dir is None:
652 ipython_dir = get_ipython_dir()
653 ipython_dir = get_ipython_dir()
653 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
654 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
654 config = cl.load_config()
655 config = cl.load_config()
655 return config
656 return config
656
657
657
658
658 def launch_new_instance():
659 def launch_new_instance():
659 """Create and run a full blown IPython instance"""
660 """Create and run a full blown IPython instance"""
660 app = IPythonApp()
661 app = IPythonApp()
661 app.start()
662 app.start()
662
663
663
664
664 if __name__ == '__main__':
665 if __name__ == '__main__':
665 launch_new_instance()
666 launch_new_instance()
@@ -1,421 +1,423 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 import warn
22 from IPython.utils.process import system
22 from IPython.utils.process import system
23 from IPython.utils.importstring import import_item
23 from IPython.utils.importstring import import_item
24
24
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 # Code
26 # Code
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28
28
29 fs_encoding = sys.getfilesystemencoding()
29 fs_encoding = sys.getfilesystemencoding()
30
30
31 def _cast_unicode(s, enc=None):
31 def _cast_unicode(s, enc=None):
32 """Turn 8-bit strings into unicode."""
32 """Turn 8-bit strings into unicode."""
33 if isinstance(s, bytes):
33 if isinstance(s, bytes):
34 enc = enc or sys.getdefaultencoding()
34 enc = enc or sys.getdefaultencoding()
35 return s.decode(enc)
35 return s.decode(enc)
36 return s
36 return s
37
37
38
38
39 def _get_long_path_name(path):
39 def _get_long_path_name(path):
40 """Dummy no-op."""
40 """Dummy no-op."""
41 return path
41 return path
42
42
43 if sys.platform == 'win32':
43 if sys.platform == 'win32':
44 def _get_long_path_name(path):
44 def _get_long_path_name(path):
45 """Get a long path name (expand ~) on Windows using ctypes.
45 """Get a long path name (expand ~) on Windows using ctypes.
46
46
47 Examples
47 Examples
48 --------
48 --------
49
49
50 >>> get_long_path_name('c:\\docume~1')
50 >>> get_long_path_name('c:\\docume~1')
51 u'c:\\\\Documents and Settings'
51 u'c:\\\\Documents and Settings'
52
52
53 """
53 """
54 try:
54 try:
55 import ctypes
55 import ctypes
56 except ImportError:
56 except ImportError:
57 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')
58 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
58 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
59 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
59 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
60 ctypes.c_uint ]
60 ctypes.c_uint ]
61
61
62 buf = ctypes.create_unicode_buffer(260)
62 buf = ctypes.create_unicode_buffer(260)
63 rv = _GetLongPathName(path, buf, 260)
63 rv = _GetLongPathName(path, buf, 260)
64 if rv == 0 or rv > 260:
64 if rv == 0 or rv > 260:
65 return path
65 return path
66 else:
66 else:
67 return buf.value
67 return buf.value
68
68
69
69
70 def get_long_path_name(path):
70 def get_long_path_name(path):
71 """Expand a path into its long form.
71 """Expand a path into its long form.
72
72
73 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
74 a null operation.
74 a null operation.
75 """
75 """
76 return _get_long_path_name(path)
76 return _get_long_path_name(path)
77
77
78
78
79 def get_py_filename(name):
79 def get_py_filename(name):
80 """Return a valid python filename in the current directory.
80 """Return a valid python filename in the current directory.
81
81
82 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.
83 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."""
84
84
85 name = os.path.expanduser(name)
85 name = os.path.expanduser(name)
86 if not os.path.isfile(name) and not name.endswith('.py'):
86 if not os.path.isfile(name) and not name.endswith('.py'):
87 name += '.py'
87 name += '.py'
88 if os.path.isfile(name):
88 if os.path.isfile(name):
89 return name
89 return name
90 else:
90 else:
91 raise IOError,'File `%s` not found.' % name
91 raise IOError,'File `%s` not found.' % name
92
92
93
93
94 def filefind(filename, path_dirs=None):
94 def filefind(filename, path_dirs=None):
95 """Find a file by looking through a sequence of paths.
95 """Find a file by looking through a sequence of paths.
96
96
97 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
98 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
99 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
100 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
100 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
101
101
102 filefind('myfile.txt')
102 filefind('myfile.txt')
103
103
104 will find the file in the current working dir, but::
104 will find the file in the current working dir, but::
105
105
106 filefind('~/myfile.txt')
106 filefind('~/myfile.txt')
107
107
108 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
109 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.
110
110
111 Parameters
111 Parameters
112 ----------
112 ----------
113 filename : str
113 filename : str
114 The filename to look for.
114 The filename to look for.
115 path_dirs : str, None or sequence of str
115 path_dirs : str, None or sequence of str
116 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
117 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
118 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
119 each element and join with ``filename``, calling :func:`expandvars`
119 each element and join with ``filename``, calling :func:`expandvars`
120 and :func:`expanduser` before testing for existence.
120 and :func:`expanduser` before testing for existence.
121
121
122 Returns
122 Returns
123 -------
123 -------
124 Raises :exc:`IOError` or returns absolute path to file.
124 Raises :exc:`IOError` or returns absolute path to file.
125 """
125 """
126
126
127 # If paths are quoted, abspath gets confused, strip them...
127 # If paths are quoted, abspath gets confused, strip them...
128 filename = filename.strip('"').strip("'")
128 filename = filename.strip('"').strip("'")
129 # If the input is an absolute path, just check it exists
129 # If the input is an absolute path, just check it exists
130 if os.path.isabs(filename) and os.path.isfile(filename):
130 if os.path.isabs(filename) and os.path.isfile(filename):
131 return filename
131 return filename
132
132
133 if path_dirs is None:
133 if path_dirs is None:
134 path_dirs = ("",)
134 path_dirs = ("",)
135 elif isinstance(path_dirs, basestring):
135 elif isinstance(path_dirs, basestring):
136 path_dirs = (path_dirs,)
136 path_dirs = (path_dirs,)
137
137
138 for path in path_dirs:
138 for path in path_dirs:
139 if path == '.': path = os.getcwd()
139 if path == '.': path = os.getcwd()
140 testname = expand_path(os.path.join(path, filename))
140 testname = expand_path(os.path.join(path, filename))
141 if os.path.isfile(testname):
141 if os.path.isfile(testname):
142 return os.path.abspath(testname)
142 return os.path.abspath(testname)
143
143
144 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" %
145 (filename, path_dirs) )
145 (filename, path_dirs) )
146
146
147
147
148 class HomeDirError(Exception):
148 class HomeDirError(Exception):
149 pass
149 pass
150
150
151
151
152 def get_home_dir():
152 def get_home_dir():
153 """Return the closest possible equivalent to a 'home' directory.
153 """Return the closest possible equivalent to a 'home' directory.
154
154
155 * On POSIX, we try $HOME.
155 * On POSIX, we try $HOME.
156 * On Windows we try:
156 * On Windows we try:
157 - %HOMESHARE%
157 - %HOMESHARE%
158 - %HOMEDRIVE\%HOMEPATH%
158 - %HOMEDRIVE\%HOMEPATH%
159 - %USERPROFILE%
159 - %USERPROFILE%
160 - Registry hack for My Documents
160 - Registry hack for My Documents
161 - %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
162 * On Dos C:\
162 * On Dos C:\
163
163
164 Currently only Posix and NT are implemented, a HomeDirError exception is
164 Currently only Posix and NT are implemented, a HomeDirError exception is
165 raised for all other OSes.
165 raised for all other OSes.
166 """
166 """
167
167
168 isdir = os.path.isdir
168 isdir = os.path.isdir
169 env = os.environ
169 env = os.environ
170
170
171 # first, check py2exe distribution root directory for _ipython.
171 # first, check py2exe distribution root directory for _ipython.
172 # This overrides all. Normally does not exist.
172 # This overrides all. Normally does not exist.
173
173
174 if hasattr(sys, "frozen"): #Is frozen by py2exe
174 if hasattr(sys, "frozen"): #Is frozen by py2exe
175 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
176 root, rest = IPython.__file__.lower().split('library.zip')
176 root, rest = IPython.__file__.lower().split('library.zip')
177 else:
177 else:
178 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
178 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
179 root=os.path.abspath(root).rstrip('\\')
179 root=os.path.abspath(root).rstrip('\\')
180 if isdir(os.path.join(root, '_ipython')):
180 if isdir(os.path.join(root, '_ipython')):
181 os.environ["IPYKITROOT"] = root
181 os.environ["IPYKITROOT"] = root
182 return _cast_unicode(root, fs_encoding)
182 return _cast_unicode(root, fs_encoding)
183
183
184 if os.name == 'posix':
184 if os.name == 'posix':
185 # Linux, Unix, AIX, OS X
185 # Linux, Unix, AIX, OS X
186 try:
186 try:
187 homedir = env['HOME']
187 homedir = env['HOME']
188 except KeyError:
188 except KeyError:
189 # Last-ditch attempt at finding a suitable $HOME, on systems where
189 # Last-ditch attempt at finding a suitable $HOME, on systems where
190 # 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
191 # still knows it - reported once as:
191 # still knows it - reported once as:
192 # https://github.com/ipython/ipython/issues/154
192 # https://github.com/ipython/ipython/issues/154
193 from subprocess import Popen, PIPE
193 from subprocess import Popen, PIPE
194 homedir = Popen('echo $HOME', shell=True,
194 homedir = Popen('echo $HOME', shell=True,
195 stdout=PIPE).communicate()[0].strip()
195 stdout=PIPE).communicate()[0].strip()
196 if homedir:
196 if homedir:
197 return _cast_unicode(homedir, fs_encoding)
197 return _cast_unicode(homedir, fs_encoding)
198 else:
198 else:
199 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
199 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
200 else:
200 else:
201 return _cast_unicode(homedir, fs_encoding)
201 return _cast_unicode(homedir, fs_encoding)
202 elif os.name == 'nt':
202 elif os.name == 'nt':
203 # Now for win9x, XP, Vista, 7?
203 # Now for win9x, XP, Vista, 7?
204 # 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.
205 # 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
206 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
206 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
207 # 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
208 # be UNC.
208 # be UNC.
209 try:
209 try:
210 homedir = env['HOMESHARE']
210 homedir = env['HOMESHARE']
211 except KeyError:
211 except KeyError:
212 pass
212 pass
213 else:
213 else:
214 if isdir(homedir):
214 if isdir(homedir):
215 return _cast_unicode(homedir, fs_encoding)
215 return _cast_unicode(homedir, fs_encoding)
216
216
217 # Now look for a local home directory
217 # Now look for a local home directory
218 try:
218 try:
219 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
219 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
220 except KeyError:
220 except KeyError:
221 pass
221 pass
222 else:
222 else:
223 if isdir(homedir):
223 if isdir(homedir):
224 return _cast_unicode(homedir, fs_encoding)
224 return _cast_unicode(homedir, fs_encoding)
225
225
226 # Now the users profile directory
226 # Now the users profile directory
227 try:
227 try:
228 homedir = os.path.join(env['USERPROFILE'])
228 homedir = os.path.join(env['USERPROFILE'])
229 except KeyError:
229 except KeyError:
230 pass
230 pass
231 else:
231 else:
232 if isdir(homedir):
232 if isdir(homedir):
233 return _cast_unicode(homedir, fs_encoding)
233 return _cast_unicode(homedir, fs_encoding)
234
234
235 # Use the registry to get the 'My Documents' folder.
235 # Use the registry to get the 'My Documents' folder.
236 try:
236 try:
237 import _winreg as wreg
237 import _winreg as wreg
238 key = wreg.OpenKey(
238 key = wreg.OpenKey(
239 wreg.HKEY_CURRENT_USER,
239 wreg.HKEY_CURRENT_USER,
240 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
240 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
241 )
241 )
242 homedir = wreg.QueryValueEx(key,'Personal')[0]
242 homedir = wreg.QueryValueEx(key,'Personal')[0]
243 key.Close()
243 key.Close()
244 except:
244 except:
245 pass
245 pass
246 else:
246 else:
247 if isdir(homedir):
247 if isdir(homedir):
248 return _cast_unicode(homedir, fs_encoding)
248 return _cast_unicode(homedir, fs_encoding)
249
249
250 # 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.
251 # Try this as a last ditch option.
251 # Try this as a last ditch option.
252 try:
252 try:
253 homedir = env['HOME']
253 homedir = env['HOME']
254 except KeyError:
254 except KeyError:
255 pass
255 pass
256 else:
256 else:
257 if isdir(homedir):
257 if isdir(homedir):
258 return _cast_unicode(homedir, fs_encoding)
258 return _cast_unicode(homedir, fs_encoding)
259
259
260 # If all else fails, raise HomeDirError
260 # If all else fails, raise HomeDirError
261 raise HomeDirError('No valid home directory could be found')
261 raise HomeDirError('No valid home directory could be found')
262 elif os.name == 'dos':
262 elif os.name == 'dos':
263 # 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.
264 return u'C:\\'
264 return u'C:\\'
265 else:
265 else:
266 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')
267
267
268 def get_xdg_dir():
268 def get_xdg_dir():
269 """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.
270
270
271 This is only for posix (Linux,Unix,OS X, etc) systems.
271 This is only for posix (Linux,Unix,OS X, etc) systems.
272 """
272 """
273
273
274 isdir = os.path.isdir
274 isdir = os.path.isdir
275 env = os.environ
275 env = os.environ
276
276
277 if os.name == 'posix':
277 if os.name == 'posix':
278 # Linux, Unix, AIX, OS X
278 # Linux, Unix, AIX, OS X
279 # use ~/.config if not set OR empty
279 # use ~/.config if not set OR empty
280 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')
281 if xdg and isdir(xdg):
281 if xdg and isdir(xdg):
282 return _cast_unicode(xdg, fs_encoding)
282 return _cast_unicode(xdg, fs_encoding)
283
283
284 return None
284 return None
285
285
286
286
287 def get_ipython_dir():
287 def get_ipython_dir():
288 """Get the IPython directory for this platform and user.
288 """Get the IPython directory for this platform and user.
289
289
290 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
291 and the adds .ipython to the end of the path.
291 and the adds .ipython to the end of the path.
292 """
292 """
293
293
294 env = os.environ
294 env = os.environ
295 pjoin = os.path.join
295 pjoin = os.path.join
296 exists = os.path.exists
296 exists = os.path.exists
297
297
298 ipdir_def = '.ipython'
298 ipdir_def = '.ipython'
299 xdg_def = 'ipython'
299 xdg_def = 'ipython'
300
300
301 home_dir = get_home_dir()
301 home_dir = get_home_dir()
302 xdg_dir = get_xdg_dir()
302 xdg_dir = get_xdg_dir()
303 # import pdb; pdb.set_trace() # dbg
303 # import pdb; pdb.set_trace() # dbg
304 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
304 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
305 if ipdir is None:
305 if ipdir is None:
306 # not set explicitly, use XDG_CONFIG_HOME or HOME
306 # not set explicitly, use XDG_CONFIG_HOME or HOME
307 home_ipdir = pjoin(home_dir, ipdir_def)
307 home_ipdir = pjoin(home_dir, ipdir_def)
308 if xdg_dir:
308 if xdg_dir:
309 # use XDG, as long as the user isn't already
309 # use XDG, as long as the user isn't already
310 # using $HOME/.ipython and *not* XDG/ipython
310 # using $HOME/.ipython and *not* XDG/ipython
311
311
312 xdg_ipdir = pjoin(xdg_dir, xdg_def)
312 xdg_ipdir = pjoin(xdg_dir, xdg_def)
313
313
314 if exists(xdg_ipdir) or not exists(home_ipdir):
314 if exists(xdg_ipdir) or not exists(home_ipdir):
315 ipdir = xdg_ipdir
315 ipdir = xdg_ipdir
316
316
317 if ipdir is None:
317 if ipdir is None:
318 # not using XDG
318 # not using XDG
319 ipdir = home_ipdir
319 ipdir = home_ipdir
320
320
321 return _cast_unicode(ipdir, fs_encoding)
321 return _cast_unicode(ipdir, fs_encoding)
322
322
323
323
324 def get_ipython_package_dir():
324 def get_ipython_package_dir():
325 """Get the base directory where IPython itself is installed."""
325 """Get the base directory where IPython itself is installed."""
326 ipdir = os.path.dirname(IPython.__file__)
326 ipdir = os.path.dirname(IPython.__file__)
327 return _cast_unicode(ipdir, fs_encoding)
327 return _cast_unicode(ipdir, fs_encoding)
328
328
329
329
330 def get_ipython_module_path(module_str):
330 def get_ipython_module_path(module_str):
331 """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.
332
332
333 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
334 IPython package. This will always return the path to the ``.py``
334 IPython package. This will always return the path to the ``.py``
335 version of the module.
335 version of the module.
336 """
336 """
337 if module_str == 'IPython':
337 if module_str == 'IPython':
338 return os.path.join(get_ipython_package_dir(), '__init__.py')
338 return os.path.join(get_ipython_package_dir(), '__init__.py')
339 mod = import_item(module_str)
339 mod = import_item(module_str)
340 the_path = mod.__file__.replace('.pyc', '.py')
340 the_path = mod.__file__.replace('.pyc', '.py')
341 the_path = the_path.replace('.pyo', '.py')
341 the_path = the_path.replace('.pyo', '.py')
342 return _cast_unicode(the_path, fs_encoding)
342 return _cast_unicode(the_path, fs_encoding)
343
343
344
344
345 def expand_path(s):
345 def expand_path(s):
346 """Expand $VARS and ~names in a string, like a shell
346 """Expand $VARS and ~names in a string, like a shell
347
347
348 :Examples:
348 :Examples:
349
349
350 In [2]: os.environ['FOO']='test'
350 In [2]: os.environ['FOO']='test'
351
351
352 In [3]: expand_path('variable FOO is $FOO')
352 In [3]: expand_path('variable FOO is $FOO')
353 Out[3]: 'variable FOO is test'
353 Out[3]: 'variable FOO is test'
354 """
354 """
355 # 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
356 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
356 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
357 # the $ to get (\\server\share\%username%). I think it considered $
357 # the $ to get (\\server\share\%username%). I think it considered $
358 # 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
359 # a hidden share).
359 # a hidden share).
360 if os.name=='nt':
360 if os.name=='nt':
361 s = s.replace('$\\', 'IPYTHON_TEMP')
361 s = s.replace('$\\', 'IPYTHON_TEMP')
362 s = os.path.expandvars(os.path.expanduser(s))
362 s = os.path.expandvars(os.path.expanduser(s))
363 if os.name=='nt':
363 if os.name=='nt':
364 s = s.replace('IPYTHON_TEMP', '$\\')
364 s = s.replace('IPYTHON_TEMP', '$\\')
365 return s
365 return s
366
366
367
367
368 def target_outdated(target,deps):
368 def target_outdated(target,deps):
369 """Determine whether a target is out of date.
369 """Determine whether a target is out of date.
370
370
371 target_outdated(target,deps) -> 1/0
371 target_outdated(target,deps) -> 1/0
372
372
373 deps: list of filenames which MUST exist.
373 deps: list of filenames which MUST exist.
374 target: single filename which may or may not exist.
374 target: single filename which may or may not exist.
375
375
376 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
377 true, otherwise return false.
377 true, otherwise return false.
378 """
378 """
379 try:
379 try:
380 target_time = os.path.getmtime(target)
380 target_time = os.path.getmtime(target)
381 except os.error:
381 except os.error:
382 return 1
382 return 1
383 for dep in deps:
383 for dep in deps:
384 dep_time = os.path.getmtime(dep)
384 dep_time = os.path.getmtime(dep)
385 if dep_time > target_time:
385 if dep_time > target_time:
386 #print "For target",target,"Dep failed:",dep # dbg
386 #print "For target",target,"Dep failed:",dep # dbg
387 #print "times (dep,tar):",dep_time,target_time # dbg
387 #print "times (dep,tar):",dep_time,target_time # dbg
388 return 1
388 return 1
389 return 0
389 return 0
390
390
391
391
392 def target_update(target,deps,cmd):
392 def target_update(target,deps,cmd):
393 """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.
394
394
395 target_update(target,deps,cmd) -> runs cmd if target is outdated.
395 target_update(target,deps,cmd) -> runs cmd if target is outdated.
396
396
397 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
398 command if target is outdated."""
398 command if target is outdated."""
399
399
400 if target_outdated(target,deps):
400 if target_outdated(target,deps):
401 system(cmd)
401 system(cmd)
402
402
403 def check_for_old_config(ipython_dir=None):
403 def check_for_old_config(ipython_dir=None):
404 """Check for old config files, and present a warning if they exist.
404 """Check for old config files, and present a warning if they exist.
405
405
406 A link to the docs of the new config is included in the message.
406 A link to the docs of the new config is included in the message.
407
407
408 This should mitigate confusion with the transition to the new
408 This should mitigate confusion with the transition to the new
409 config system in 0.11.
409 config system in 0.11.
410 """
410 """
411 if ipython_dir is None:
411 if ipython_dir is None:
412 ipython_dir = get_ipython_dir()
412 ipython_dir = get_ipython_dir()
413
413
414 old_configs = ['ipy_user_conf.py', 'ipythonrc']
414 old_configs = ['ipy_user_conf.py', 'ipythonrc']
415 for cfg in old_configs:
415 for cfg in old_configs:
416 f = os.path.join(ipython_dir, cfg)
416 f = os.path.join(ipython_dir, cfg)
417 if os.path.exists(f):
417 if os.path.exists(f):
418 warn.warn("""Found old IPython config file %r.
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.
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.
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)
421 The current default config file is 'ipython_config.py', where you can suppress these
422 warnings with `Global.ignore_old_config = True`."""%f)
423
General Comments 0
You need to be logged in to leave comments. Login now