Show More
@@ -0,0 +1,191 b'' | |||||
|
1 | #!/usr/bin/env python | |||
|
2 | # encoding: utf-8 | |||
|
3 | """ | |||
|
4 | IPython's alias component | |||
|
5 | ||||
|
6 | Authors: | |||
|
7 | ||||
|
8 | * Brian Granger | |||
|
9 | """ | |||
|
10 | ||||
|
11 | #----------------------------------------------------------------------------- | |||
|
12 | # Copyright (C) 2008-2009 The IPython Development Team | |||
|
13 | # | |||
|
14 | # Distributed under the terms of the BSD License. The full license is in | |||
|
15 | # the file COPYING, distributed as part of this software. | |||
|
16 | #----------------------------------------------------------------------------- | |||
|
17 | ||||
|
18 | #----------------------------------------------------------------------------- | |||
|
19 | # Imports | |||
|
20 | #----------------------------------------------------------------------------- | |||
|
21 | ||||
|
22 | import __builtin__ | |||
|
23 | import keyword | |||
|
24 | import os | |||
|
25 | import sys | |||
|
26 | ||||
|
27 | from IPython.core.component import Component | |||
|
28 | ||||
|
29 | from IPython.utils.traitlets import CBool, List, Instance | |||
|
30 | from IPython.utils.genutils import error | |||
|
31 | ||||
|
32 | #----------------------------------------------------------------------------- | |||
|
33 | # Functions and classes | |||
|
34 | #----------------------------------------------------------------------------- | |||
|
35 | ||||
|
36 | def default_aliases(): | |||
|
37 | # Make some aliases automatically | |||
|
38 | # Prepare list of shell aliases to auto-define | |||
|
39 | if os.name == 'posix': | |||
|
40 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', | |||
|
41 | 'mv mv -i','rm rm -i','cp cp -i', | |||
|
42 | 'cat cat','less less','clear clear', | |||
|
43 | # a better ls | |||
|
44 | 'ls ls -F', | |||
|
45 | # long ls | |||
|
46 | 'll ls -lF') | |||
|
47 | # Extra ls aliases with color, which need special treatment on BSD | |||
|
48 | # variants | |||
|
49 | ls_extra = ( # color ls | |||
|
50 | 'lc ls -F -o --color', | |||
|
51 | # ls normal files only | |||
|
52 | 'lf ls -F -o --color %l | grep ^-', | |||
|
53 | # ls symbolic links | |||
|
54 | 'lk ls -F -o --color %l | grep ^l', | |||
|
55 | # directories or links to directories, | |||
|
56 | 'ldir ls -F -o --color %l | grep /$', | |||
|
57 | # things which are executable | |||
|
58 | 'lx ls -F -o --color %l | grep ^-..x', | |||
|
59 | ) | |||
|
60 | # The BSDs don't ship GNU ls, so they don't understand the | |||
|
61 | # --color switch out of the box | |||
|
62 | if 'bsd' in sys.platform: | |||
|
63 | ls_extra = ( # ls normal files only | |||
|
64 | 'lf ls -lF | grep ^-', | |||
|
65 | # ls symbolic links | |||
|
66 | 'lk ls -lF | grep ^l', | |||
|
67 | # directories or links to directories, | |||
|
68 | 'ldir ls -lF | grep /$', | |||
|
69 | # things which are executable | |||
|
70 | 'lx ls -lF | grep ^-..x', | |||
|
71 | ) | |||
|
72 | auto_alias = auto_alias + ls_extra | |||
|
73 | elif os.name in ['nt','dos']: | |||
|
74 | auto_alias = ('ls dir /on', | |||
|
75 | 'ddir dir /ad /on', 'ldir dir /ad /on', | |||
|
76 | 'mkdir mkdir','rmdir rmdir','echo echo', | |||
|
77 | 'ren ren','cls cls','copy copy') | |||
|
78 | else: | |||
|
79 | auto_alias = () | |||
|
80 | return [s.split(None,1) for s in auto_alias] | |||
|
81 | ||||
|
82 | ||||
|
83 | class AliasError(Exception): | |||
|
84 | pass | |||
|
85 | ||||
|
86 | ||||
|
87 | class InvalidAliasError(AliasError): | |||
|
88 | pass | |||
|
89 | ||||
|
90 | ||||
|
91 | class AliasManager(Component): | |||
|
92 | ||||
|
93 | auto_alias = List(default_aliases()) | |||
|
94 | user_alias = List(default_value=[], config_key='USER_ALIAS') | |||
|
95 | ||||
|
96 | def __init__(self, parent, config=None): | |||
|
97 | super(AliasManager, self).__init__(parent, config=config) | |||
|
98 | self.shell = Component.get_instances( | |||
|
99 | root=self.root, | |||
|
100 | klass='IPython.core.iplib.InteractiveShell' | |||
|
101 | )[0] | |||
|
102 | self.alias_table = {} | |||
|
103 | self.exclude_aliases() | |||
|
104 | self.init_aliases() | |||
|
105 | ||||
|
106 | def __contains__(self, name): | |||
|
107 | if name in self.alias_table: | |||
|
108 | return True | |||
|
109 | else: | |||
|
110 | return False | |||
|
111 | ||||
|
112 | @property | |||
|
113 | def aliases(self): | |||
|
114 | return [(item[0], item[1][1]) for item in self.alias_table.iteritems()] | |||
|
115 | ||||
|
116 | def exclude_aliases(self): | |||
|
117 | # set of things NOT to alias (keywords, builtins and some magics) | |||
|
118 | no_alias = set(['cd','popd','pushd','dhist','alias','unalias']) | |||
|
119 | no_alias.update(set(keyword.kwlist)) | |||
|
120 | no_alias.update(set(__builtin__.__dict__.keys())) | |||
|
121 | self.no_alias = no_alias | |||
|
122 | ||||
|
123 | def init_aliases(self): | |||
|
124 | # Load default aliases | |||
|
125 | for name, cmd in self.auto_alias: | |||
|
126 | self.soft_define_alias(name, cmd) | |||
|
127 | ||||
|
128 | # Load user aliases | |||
|
129 | for name, cmd in self.user_alias: | |||
|
130 | self.soft_define_alias(name, cmd) | |||
|
131 | ||||
|
132 | def soft_define_alias(self, name, cmd): | |||
|
133 | """Define an alias, but don't raise on an AliasError.""" | |||
|
134 | try: | |||
|
135 | self.define_alias(name, cmd) | |||
|
136 | except AliasError, e: | |||
|
137 | error("Invalid alias: %s" % e) | |||
|
138 | ||||
|
139 | def define_alias(self, name, cmd): | |||
|
140 | """Define a new alias after validating it. | |||
|
141 | ||||
|
142 | This will raise an :exc:`AliasError` if there are validation | |||
|
143 | problems. | |||
|
144 | """ | |||
|
145 | nargs = self.validate_alias(name, cmd) | |||
|
146 | self.alias_table[name] = (nargs, cmd) | |||
|
147 | ||||
|
148 | def validate_alias(self, name, cmd): | |||
|
149 | """Validate an alias and return the its number of arguments.""" | |||
|
150 | if name in self.no_alias: | |||
|
151 | raise InvalidAliasError("The name %s can't be aliased " | |||
|
152 | "because it is a keyword or builtin." % name) | |||
|
153 | if not (isinstance(cmd, basestring)): | |||
|
154 | raise InvalidAliasError("An alias command must be a string, " | |||
|
155 | "got: %r" % name) | |||
|
156 | nargs = cmd.count('%s') | |||
|
157 | if nargs>0 and cmd.find('%l')>=0: | |||
|
158 | raise InvalidAliasError('The %s and %l specifiers are mutually ' | |||
|
159 | 'exclusive in alias definitions.') | |||
|
160 | return nargs | |||
|
161 | ||||
|
162 | def call_alias(self, alias, rest=''): | |||
|
163 | """Call an alias given its name and the rest of the line.""" | |||
|
164 | cmd = self.transform_alias(alias, rest) | |||
|
165 | try: | |||
|
166 | self.shell.system(cmd) | |||
|
167 | except: | |||
|
168 | self.shell.showtraceback() | |||
|
169 | ||||
|
170 | def transform_alias(self, alias,rest=''): | |||
|
171 | """Transform alias to system command string.""" | |||
|
172 | nargs, cmd = self.alias_table[alias] | |||
|
173 | ||||
|
174 | if ' ' in cmd and os.path.isfile(cmd): | |||
|
175 | cmd = '"%s"' % cmd | |||
|
176 | ||||
|
177 | # Expand the %l special to be the user's input line | |||
|
178 | if cmd.find('%l') >= 0: | |||
|
179 | cmd = cmd.replace('%l', rest) | |||
|
180 | rest = '' | |||
|
181 | if nargs==0: | |||
|
182 | # Simple, argument-less aliases | |||
|
183 | cmd = '%s %s' % (cmd, rest) | |||
|
184 | else: | |||
|
185 | # Handle aliases with positional arguments | |||
|
186 | args = rest.split(None, nargs) | |||
|
187 | if len(args) < nargs: | |||
|
188 | raise AliasError('Alias <%s> requires %s arguments, %s given.' % | |||
|
189 | (alias, nargs, len(args))) | |||
|
190 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) | |||
|
191 | return cmd |
@@ -1,241 +1,242 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | An application for IPython |
|
4 | An application for IPython | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | import os |
|
26 | import os | |
27 | import sys |
|
27 | import sys | |
28 | import traceback |
|
28 | import traceback | |
29 |
|
29 | |||
30 | from copy import deepcopy |
|
30 | from copy import deepcopy | |
31 | from IPython.utils.ipstruct import Struct |
|
31 | from IPython.utils.ipstruct import Struct | |
32 | from IPython.utils.genutils import get_ipython_dir, filefind |
|
32 | from IPython.utils.genutils import get_ipython_dir, filefind | |
33 | from IPython.config.loader import ( |
|
33 | from IPython.config.loader import ( | |
34 | IPythonArgParseConfigLoader, |
|
34 | IPythonArgParseConfigLoader, | |
35 | PyFileConfigLoader |
|
35 | PyFileConfigLoader | |
36 | ) |
|
36 | ) | |
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Classes and functions |
|
39 | # Classes and functions | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | class ApplicationError(Exception): |
|
43 | class ApplicationError(Exception): | |
44 | pass |
|
44 | pass | |
45 |
|
45 | |||
46 |
|
46 | |||
47 | class Application(object): |
|
47 | class Application(object): | |
48 | """Load a config, construct an app and run it. |
|
48 | """Load a config, construct an app and run it. | |
49 | """ |
|
49 | """ | |
50 |
|
50 | |||
51 | config_file_name = 'ipython_config.py' |
|
51 | config_file_name = 'ipython_config.py' | |
52 | name = 'ipython' |
|
52 | name = 'ipython' | |
53 | debug = False |
|
53 | debug = False | |
54 |
|
54 | |||
55 | def __init__(self): |
|
55 | def __init__(self): | |
56 | pass |
|
56 | pass | |
57 |
|
57 | |||
58 | def start(self): |
|
58 | def start(self): | |
59 | """Start the application.""" |
|
59 | """Start the application.""" | |
60 | self.attempt(self.create_default_config) |
|
60 | self.attempt(self.create_default_config) | |
61 | self.attempt(self.pre_load_command_line_config) |
|
61 | self.attempt(self.pre_load_command_line_config) | |
62 | self.attempt(self.load_command_line_config, action='abort') |
|
62 | self.attempt(self.load_command_line_config, action='abort') | |
63 | self.attempt(self.post_load_command_line_config) |
|
63 | self.attempt(self.post_load_command_line_config) | |
64 | self.attempt(self.find_ipythondir) |
|
64 | self.attempt(self.find_ipythondir) | |
65 | self.attempt(self.find_config_file_name) |
|
65 | self.attempt(self.find_config_file_name) | |
66 | self.attempt(self.find_config_file_paths) |
|
66 | self.attempt(self.find_config_file_paths) | |
67 | self.attempt(self.pre_load_file_config) |
|
67 | self.attempt(self.pre_load_file_config) | |
68 | self.attempt(self.load_file_config) |
|
68 | self.attempt(self.load_file_config) | |
69 | self.attempt(self.post_load_file_config) |
|
69 | self.attempt(self.post_load_file_config) | |
70 | self.attempt(self.merge_configs) |
|
70 | self.attempt(self.merge_configs) | |
71 | self.attempt(self.pre_construct) |
|
71 | self.attempt(self.pre_construct) | |
72 | self.attempt(self.construct) |
|
72 | self.attempt(self.construct) | |
73 | self.attempt(self.post_construct) |
|
73 | self.attempt(self.post_construct) | |
74 | self.attempt(self.start_app) |
|
74 | self.attempt(self.start_app) | |
75 |
|
75 | |||
76 | #------------------------------------------------------------------------- |
|
76 | #------------------------------------------------------------------------- | |
77 | # Various stages of Application creation |
|
77 | # Various stages of Application creation | |
78 | #------------------------------------------------------------------------- |
|
78 | #------------------------------------------------------------------------- | |
79 |
|
79 | |||
80 | def create_default_config(self): |
|
80 | def create_default_config(self): | |
81 | """Create defaults that can't be set elsewhere.""" |
|
81 | """Create defaults that can't be set elsewhere.""" | |
82 | self.default_config = Struct() |
|
82 | self.default_config = Struct() | |
83 | self.default_config.IPYTHONDIR = get_ipython_dir() |
|
83 | self.default_config.IPYTHONDIR = get_ipython_dir() | |
84 |
|
84 | |||
85 | def create_command_line_config(self): |
|
85 | def create_command_line_config(self): | |
86 | """Create and return a command line config loader.""" |
|
86 | """Create and return a command line config loader.""" | |
87 | return IPythonArgParseConfigLoader(description=self.name) |
|
87 | return IPythonArgParseConfigLoader(description=self.name) | |
88 |
|
88 | |||
89 | def pre_load_command_line_config(self): |
|
89 | def pre_load_command_line_config(self): | |
90 | """Do actions just before loading the command line config.""" |
|
90 | """Do actions just before loading the command line config.""" | |
91 | pass |
|
91 | pass | |
92 |
|
92 | |||
93 | def load_command_line_config(self): |
|
93 | def load_command_line_config(self): | |
94 | """Load the command line config. |
|
94 | """Load the command line config. | |
95 |
|
95 | |||
96 | This method also sets ``self.debug``. |
|
96 | This method also sets ``self.debug``. | |
97 | """ |
|
97 | """ | |
98 |
|
98 | |||
99 | loader = self.create_command_line_config() |
|
99 | loader = self.create_command_line_config() | |
100 | self.command_line_config = loader.load_config() |
|
100 | self.command_line_config = loader.load_config() | |
101 | try: |
|
101 | try: | |
102 | self.debug = self.command_line_config.DEBUG |
|
102 | self.debug = self.command_line_config.DEBUG | |
103 | except AttributeError: |
|
103 | except AttributeError: | |
104 | pass # use class default |
|
104 | pass # use class default | |
105 | self.log("Default config loaded:", self.default_config) |
|
105 | self.log("Default config loaded:", self.default_config) | |
106 | self.log("Command line config loaded:", self.command_line_config) |
|
106 | self.log("Command line config loaded:", self.command_line_config) | |
107 |
|
107 | |||
108 | def post_load_command_line_config(self): |
|
108 | def post_load_command_line_config(self): | |
109 | """Do actions just after loading the command line config.""" |
|
109 | """Do actions just after loading the command line config.""" | |
110 | pass |
|
110 | pass | |
111 |
|
111 | |||
112 | def find_ipythondir(self): |
|
112 | def find_ipythondir(self): | |
113 | """Set the IPython directory. |
|
113 | """Set the IPython directory. | |
114 |
|
114 | |||
115 | This sets ``self.ipythondir``, but the actual value that is passed |
|
115 | This sets ``self.ipythondir``, but the actual value that is passed | |
116 | to the application is kept in either ``self.default_config`` or |
|
116 | to the application is kept in either ``self.default_config`` or | |
117 | ``self.command_line_config``. This also added ``self.ipythondir`` to |
|
117 | ``self.command_line_config``. This also added ``self.ipythondir`` to | |
118 | ``sys.path`` so config files there can be references by other config |
|
118 | ``sys.path`` so config files there can be references by other config | |
119 | files. |
|
119 | files. | |
120 | """ |
|
120 | """ | |
121 |
|
121 | |||
122 | try: |
|
122 | try: | |
123 | self.ipythondir = self.command_line_config.IPYTHONDIR |
|
123 | self.ipythondir = self.command_line_config.IPYTHONDIR | |
124 | except AttributeError: |
|
124 | except AttributeError: | |
125 | self.ipythondir = self.default_config.IPYTHONDIR |
|
125 | self.ipythondir = self.default_config.IPYTHONDIR | |
126 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
126 | sys.path.append(os.path.abspath(self.ipythondir)) | |
127 | if not os.path.isdir(self.ipythondir): |
|
127 | if not os.path.isdir(self.ipythondir): | |
128 | os.makedirs(self.ipythondir, mode = 0777) |
|
128 | os.makedirs(self.ipythondir, mode = 0777) | |
129 | self.log("IPYTHONDIR set to: %s" % self.ipythondir) |
|
129 | self.log("IPYTHONDIR set to: %s" % self.ipythondir) | |
130 |
|
130 | |||
131 | def find_config_file_name(self): |
|
131 | def find_config_file_name(self): | |
132 | """Find the config file name for this application. |
|
132 | """Find the config file name for this application. | |
133 |
|
133 | |||
134 | If a profile has been set at the command line, this will resolve |
|
134 | If a profile has been set at the command line, this will resolve | |
135 | it. The search paths for the config file are set in |
|
135 | it. The search paths for the config file are set in | |
136 | :meth:`find_config_file_paths` and then passed to the config file |
|
136 | :meth:`find_config_file_paths` and then passed to the config file | |
137 | loader where they are resolved to an absolute path. |
|
137 | loader where they are resolved to an absolute path. | |
138 | """ |
|
138 | """ | |
139 |
|
139 | |||
140 | try: |
|
140 | try: | |
141 | self.config_file_name = self.command_line_config.CONFIG_FILE |
|
141 | self.config_file_name = self.command_line_config.CONFIG_FILE | |
142 | except AttributeError: |
|
142 | except AttributeError: | |
143 | pass |
|
143 | pass | |
144 |
|
144 | |||
145 | try: |
|
145 | try: | |
146 | self.profile_name = self.command_line_config.PROFILE |
|
146 | self.profile_name = self.command_line_config.PROFILE | |
147 | name_parts = self.config_file_name.split('.') |
|
147 | name_parts = self.config_file_name.split('.') | |
148 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
148 | name_parts.insert(1, '_' + self.profile_name + '.') | |
149 | self.config_file_name = ''.join(name_parts) |
|
149 | self.config_file_name = ''.join(name_parts) | |
150 | except AttributeError: |
|
150 | except AttributeError: | |
151 | pass |
|
151 | pass | |
152 |
|
152 | |||
153 | def find_config_file_paths(self): |
|
153 | def find_config_file_paths(self): | |
154 | """Set the search paths for resolving the config file.""" |
|
154 | """Set the search paths for resolving the config file.""" | |
155 | self.config_file_paths = (os.getcwd(), self.ipythondir) |
|
155 | self.config_file_paths = (os.getcwd(), self.ipythondir) | |
156 |
|
156 | |||
157 | def pre_load_file_config(self): |
|
157 | def pre_load_file_config(self): | |
158 | """Do actions before the config file is loaded.""" |
|
158 | """Do actions before the config file is loaded.""" | |
159 | pass |
|
159 | pass | |
160 |
|
160 | |||
161 | def load_file_config(self): |
|
161 | def load_file_config(self): | |
162 | """Load the config file. |
|
162 | """Load the config file. | |
163 |
|
163 | |||
164 | This tries to load the config file from disk. If successful, the |
|
164 | This tries to load the config file from disk. If successful, the | |
165 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
165 | ``CONFIG_FILE`` config variable is set to the resolved config file | |
166 | location. If not successful, an empty config is used. |
|
166 | location. If not successful, an empty config is used. | |
167 | """ |
|
167 | """ | |
168 | loader = PyFileConfigLoader(self.config_file_name, |
|
168 | loader = PyFileConfigLoader(self.config_file_name, | |
169 | self.config_file_paths) |
|
169 | self.config_file_paths) | |
170 | try: |
|
170 | try: | |
171 | self.file_config = loader.load_config() |
|
171 | self.file_config = loader.load_config() | |
172 | self.file_config.CONFIG_FILE = loader.full_filename |
|
172 | self.file_config.CONFIG_FILE = loader.full_filename | |
173 | except IOError: |
|
173 | except IOError: | |
174 | self.log("Config file not found, skipping: %s" % \ |
|
174 | self.log("Config file not found, skipping: %s" % \ | |
175 | self.config_file_name) |
|
175 | self.config_file_name) | |
176 | self.file_config = Struct() |
|
176 | self.file_config = Struct() | |
177 | else: |
|
177 | else: | |
178 | self.log("Config file loaded: %s" % loader.full_filename, |
|
178 | self.log("Config file loaded: %s" % loader.full_filename, | |
179 | self.file_config) |
|
179 | self.file_config) | |
180 |
|
180 | |||
181 | def post_load_file_config(self): |
|
181 | def post_load_file_config(self): | |
182 | """Do actions after the config file is loaded.""" |
|
182 | """Do actions after the config file is loaded.""" | |
183 | pass |
|
183 | pass | |
184 |
|
184 | |||
185 | def merge_configs(self): |
|
185 | def merge_configs(self): | |
186 | """Merge the default, command line and file config objects.""" |
|
186 | """Merge the default, command line and file config objects.""" | |
187 | config = Struct() |
|
187 | config = Struct() | |
188 | config.update(self.default_config) |
|
188 | config.update(self.default_config) | |
189 | config.update(self.file_config) |
|
189 | config.update(self.file_config) | |
190 | config.update(self.command_line_config) |
|
190 | config.update(self.command_line_config) | |
191 | self.master_config = config |
|
191 | self.master_config = config | |
192 | self.log("Master config created:", self.master_config) |
|
192 | self.log("Master config created:", self.master_config) | |
193 |
|
193 | |||
194 | def pre_construct(self): |
|
194 | def pre_construct(self): | |
195 | """Do actions after the config has been built, but before construct.""" |
|
195 | """Do actions after the config has been built, but before construct.""" | |
196 | pass |
|
196 | pass | |
197 |
|
197 | |||
198 | def construct(self): |
|
198 | def construct(self): | |
199 | """Construct the main components that make up this app.""" |
|
199 | """Construct the main components that make up this app.""" | |
200 | self.log("Constructing components for application...") |
|
200 | self.log("Constructing components for application...") | |
201 |
|
201 | |||
202 | def post_construct(self): |
|
202 | def post_construct(self): | |
203 | """Do actions after construct, but before starting the app.""" |
|
203 | """Do actions after construct, but before starting the app.""" | |
204 | pass |
|
204 | pass | |
205 |
|
205 | |||
206 | def start_app(self): |
|
206 | def start_app(self): | |
207 | """Actually start the app.""" |
|
207 | """Actually start the app.""" | |
208 | self.log("Starting application...") |
|
208 | self.log("Starting application...") | |
209 |
|
209 | |||
210 | #------------------------------------------------------------------------- |
|
210 | #------------------------------------------------------------------------- | |
211 | # Utility methods |
|
211 | # Utility methods | |
212 | #------------------------------------------------------------------------- |
|
212 | #------------------------------------------------------------------------- | |
213 |
|
213 | |||
214 | def abort(self): |
|
214 | def abort(self): | |
215 | """Abort the starting of the application.""" |
|
215 | """Abort the starting of the application.""" | |
216 | print "Aborting application: ", self.name |
|
216 | print "Aborting application: ", self.name | |
217 | sys.exit(1) |
|
217 | sys.exit(1) | |
218 |
|
218 | |||
219 | def exit(self): |
|
219 | def exit(self): | |
220 | print "Exiting application: ", self.name |
|
220 | print "Exiting application: ", self.name | |
221 | sys.exit(1) |
|
221 | sys.exit(1) | |
222 |
|
222 | |||
223 | def attempt(self, func, action='abort'): |
|
223 | def attempt(self, func, action='abort'): | |
224 | try: |
|
224 | try: | |
225 | func() |
|
225 | func() | |
226 | except: |
|
226 | except: | |
227 | if action == 'abort': |
|
227 | if action == 'abort': | |
228 | self.print_traceback() |
|
228 | self.print_traceback() | |
229 | self.abort() |
|
229 | self.abort() | |
230 | elif action == 'exit': |
|
230 | elif action == 'exit': | |
|
231 | self.print_traceback() | |||
231 | self.exit() |
|
232 | self.exit() | |
232 |
|
233 | |||
233 | def print_traceback(self): |
|
234 | def print_traceback(self): | |
234 | print "Error in appliction startup: ", self.name |
|
235 | print "Error in appliction startup: ", self.name | |
235 |
|
236 | |||
236 | traceback.print_exc() |
|
237 | traceback.print_exc() | |
237 |
|
238 | |||
238 | def log(self, *args): |
|
239 | def log(self, *args): | |
239 | if self.debug: |
|
240 | if self.debug: | |
240 | for arg in args: |
|
241 | for arg in args: | |
241 | print "[%s] %s" % (self.name, arg) No newline at end of file |
|
242 | print "[%s] %s" % (self.name, arg) |
@@ -1,107 +1,108 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A context manager for managing things injected into :mod:`__builtin__`. |
|
4 | A context manager for managing things injected into :mod:`__builtin__`. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | # Copyright (C) 2008-2009 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 |
|
23 | |||
24 | from IPython.core.component import Component |
|
24 | from IPython.core.component import Component | |
25 | from IPython.core.quitter import Quitter |
|
25 | from IPython.core.quitter import Quitter | |
26 |
|
26 | |||
27 | from IPython.utils.traitlets import Instance |
|
27 | from IPython.utils.traitlets import Instance | |
28 |
|
28 | |||
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 | # Classes and functions |
|
30 | # Classes and functions | |
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | class BuiltinUndefined(object): pass |
|
34 | class BuiltinUndefined(object): pass | |
35 | BuiltinUndefined = BuiltinUndefined() |
|
35 | BuiltinUndefined = BuiltinUndefined() | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | class BuiltinTrap(Component): |
|
38 | class BuiltinTrap(Component): | |
39 | shell = Instance('IPython.core.iplib.InteractiveShell') |
|
|||
40 |
|
39 | |||
41 | def __init__(self, parent): |
|
40 | def __init__(self, parent): | |
42 | super(BuiltinTrap, self).__init__(parent, None, None) |
|
41 | super(BuiltinTrap, self).__init__(parent, None, None) | |
43 | # Don't just grab parent!!! |
|
42 | # Don't just grab parent!!! | |
44 |
self.shell = Component.get_instances( |
|
43 | self.shell = Component.get_instances( | |
45 | klass='IPython.core.iplib.InteractiveShell')[0] |
|
44 | root=self.root, | |
|
45 | klass='IPython.core.iplib.InteractiveShell' | |||
|
46 | )[0] | |||
46 | self._orig_builtins = {} |
|
47 | self._orig_builtins = {} | |
47 |
|
48 | |||
48 | def __enter__(self): |
|
49 | def __enter__(self): | |
49 | self.set() |
|
50 | self.set() | |
50 | # I return self, so callers can use add_builtin in a with clause. |
|
51 | # I return self, so callers can use add_builtin in a with clause. | |
51 | return self |
|
52 | return self | |
52 |
|
53 | |||
53 | def __exit__(self, type, value, traceback): |
|
54 | def __exit__(self, type, value, traceback): | |
54 | self.unset() |
|
55 | self.unset() | |
55 | return True |
|
56 | return True | |
56 |
|
57 | |||
57 | def add_builtin(self, key, value): |
|
58 | def add_builtin(self, key, value): | |
58 | """Add a builtin and save the original.""" |
|
59 | """Add a builtin and save the original.""" | |
59 | orig = __builtin__.__dict__.get(key, BuiltinUndefined) |
|
60 | orig = __builtin__.__dict__.get(key, BuiltinUndefined) | |
60 | self._orig_builtins[key] = orig |
|
61 | self._orig_builtins[key] = orig | |
61 | __builtin__.__dict__[key] = value |
|
62 | __builtin__.__dict__[key] = value | |
62 |
|
63 | |||
63 | def remove_builtin(self, key): |
|
64 | def remove_builtin(self, key): | |
64 | """Remove an added builtin and re-set the original.""" |
|
65 | """Remove an added builtin and re-set the original.""" | |
65 | try: |
|
66 | try: | |
66 | orig = self._orig_builtins.pop(key) |
|
67 | orig = self._orig_builtins.pop(key) | |
67 | except KeyError: |
|
68 | except KeyError: | |
68 | pass |
|
69 | pass | |
69 | else: |
|
70 | else: | |
70 | if orig is BuiltinUndefined: |
|
71 | if orig is BuiltinUndefined: | |
71 | del __builtin__.__dict__[key] |
|
72 | del __builtin__.__dict__[key] | |
72 | else: |
|
73 | else: | |
73 | __builtin__.__dict__[key] = orig |
|
74 | __builtin__.__dict__[key] = orig | |
74 |
|
75 | |||
75 | def set(self): |
|
76 | def set(self): | |
76 | """Store ipython references in the __builtin__ namespace.""" |
|
77 | """Store ipython references in the __builtin__ namespace.""" | |
77 | self.add_builtin('exit', Quitter(self.shell, 'exit')) |
|
78 | self.add_builtin('exit', Quitter(self.shell, 'exit')) | |
78 | self.add_builtin('quit', Quitter(self.shell, 'quit')) |
|
79 | self.add_builtin('quit', Quitter(self.shell, 'quit')) | |
79 |
|
80 | |||
80 | # Recursive reload function |
|
81 | # Recursive reload function | |
81 | try: |
|
82 | try: | |
82 | from IPython.lib import deepreload |
|
83 | from IPython.lib import deepreload | |
83 | if self.shell.deep_reload: |
|
84 | if self.shell.deep_reload: | |
84 | self.add_builtin('reload', deepreload.reload) |
|
85 | self.add_builtin('reload', deepreload.reload) | |
85 | else: |
|
86 | else: | |
86 | self.add_builtin('dreload', deepreload.reload) |
|
87 | self.add_builtin('dreload', deepreload.reload) | |
87 | del deepreload |
|
88 | del deepreload | |
88 | except ImportError: |
|
89 | except ImportError: | |
89 | pass |
|
90 | pass | |
90 |
|
91 | |||
91 | # Keep in the builtins a flag for when IPython is active. We set it |
|
92 | # Keep in the builtins a flag for when IPython is active. We set it | |
92 | # with setdefault so that multiple nested IPythons don't clobber one |
|
93 | # with setdefault so that multiple nested IPythons don't clobber one | |
93 | # another. Each will increase its value by one upon being activated, |
|
94 | # another. Each will increase its value by one upon being activated, | |
94 | # which also gives us a way to determine the nesting level. |
|
95 | # which also gives us a way to determine the nesting level. | |
95 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
96 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
96 |
|
97 | |||
97 | def unset(self): |
|
98 | def unset(self): | |
98 | """Remove any builtins which might have been added by add_builtins, or |
|
99 | """Remove any builtins which might have been added by add_builtins, or | |
99 | restore overwritten ones to their previous values.""" |
|
100 | restore overwritten ones to their previous values.""" | |
100 | for key in self._orig_builtins.keys(): |
|
101 | for key in self._orig_builtins.keys(): | |
101 | self.remove_builtin(key) |
|
102 | self.remove_builtin(key) | |
102 | self._orig_builtins.clear() |
|
103 | self._orig_builtins.clear() | |
103 | self._builtins_added = False |
|
104 | self._builtins_added = False | |
104 | try: |
|
105 | try: | |
105 | del __builtin__.__dict__['__IPYTHON__active'] |
|
106 | del __builtin__.__dict__['__IPYTHON__active'] | |
106 | except KeyError: |
|
107 | except KeyError: | |
107 | pass No newline at end of file |
|
108 | pass |
@@ -1,248 +1,305 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A lightweight component system for IPython. |
|
4 | A lightweight component system for IPython. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | from copy import deepcopy |
|
23 | from copy import deepcopy | |
24 | import datetime |
|
24 | import datetime | |
25 | from weakref import WeakValueDictionary |
|
25 | from weakref import WeakValueDictionary | |
26 |
|
26 | |||
27 | from IPython.utils.importstring import import_item |
|
27 | from IPython.utils.importstring import import_item | |
28 | from IPython.utils.ipstruct import Struct |
|
28 | from IPython.utils.ipstruct import Struct | |
29 | from IPython.utils.traitlets import ( |
|
29 | from IPython.utils.traitlets import ( | |
30 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This |
|
30 | HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This | |
31 | ) |
|
31 | ) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Helper classes for Components |
|
35 | # Helper classes for Components | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class ComponentError(Exception): |
|
39 | class ComponentError(Exception): | |
40 | pass |
|
40 | pass | |
41 |
|
41 | |||
42 | class MetaComponentTracker(type): |
|
42 | class MetaComponentTracker(type): | |
43 | """A metaclass that tracks instances of Components and its subclasses.""" |
|
43 | """A metaclass that tracks instances of Components and its subclasses.""" | |
44 |
|
44 | |||
45 | def __init__(cls, name, bases, d): |
|
45 | def __init__(cls, name, bases, d): | |
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) |
|
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) | |
47 | cls.__instance_refs = WeakValueDictionary() |
|
47 | cls.__instance_refs = WeakValueDictionary() | |
48 | cls.__numcreated = 0 |
|
48 | cls.__numcreated = 0 | |
49 |
|
49 | |||
50 | def __call__(cls, *args, **kw): |
|
50 | def __call__(cls, *args, **kw): | |
51 |
"""Called when |
|
51 | """Called when a class is called (instantiated)!!! | |
52 |
|
52 | |||
53 | When a Component or subclass is instantiated, this is called and |
|
53 | When a Component or subclass is instantiated, this is called and | |
54 | the instance is saved in a WeakValueDictionary for tracking. |
|
54 | the instance is saved in a WeakValueDictionary for tracking. | |
55 | """ |
|
55 | """ | |
56 | instance = cls.__new__(cls, *args, **kw) |
|
56 | instance = cls.__new__(cls, *args, **kw) | |
57 | # Do this before __init__ is called so get_instances works inside |
|
57 | ||
58 | # __init__ methods! |
|
58 | # Register the instance before __init__ is called so get_instances | |
|
59 | # works inside __init__ methods! | |||
|
60 | indices = cls.register_instance(instance) | |||
|
61 | ||||
|
62 | # This is in a try/except because of the __init__ method fails, the | |||
|
63 | # instance is discarded and shouldn't be tracked. | |||
|
64 | try: | |||
|
65 | if isinstance(instance, cls): | |||
|
66 | cls.__init__(instance, *args, **kw) | |||
|
67 | except: | |||
|
68 | # Unregister the instance because __init__ failed! | |||
|
69 | cls.unregister_instances(indices) | |||
|
70 | raise | |||
|
71 | else: | |||
|
72 | return instance | |||
|
73 | ||||
|
74 | def register_instance(cls, instance): | |||
|
75 | """Register instance with cls and its subclasses.""" | |||
|
76 | # indices is a list of the keys used to register the instance | |||
|
77 | # with. This list is needed if the instance needs to be unregistered. | |||
|
78 | indices = [] | |||
59 | for c in cls.__mro__: |
|
79 | for c in cls.__mro__: | |
60 | if issubclass(cls, c) and issubclass(c, Component): |
|
80 | if issubclass(cls, c) and issubclass(c, Component): | |
61 | c.__numcreated += 1 |
|
81 | c.__numcreated += 1 | |
|
82 | indices.append(c.__numcreated) | |||
62 | c.__instance_refs[c.__numcreated] = instance |
|
83 | c.__instance_refs[c.__numcreated] = instance | |
63 | if isinstance(instance, cls): |
|
84 | else: | |
64 | cls.__init__(instance, *args, **kw) |
|
85 | break | |
|
86 | return indices | |||
|
87 | ||||
|
88 | def unregister_instances(cls, indices): | |||
|
89 | """Unregister instance with cls and its subclasses.""" | |||
|
90 | for c, index in zip(cls.__mro__, indices): | |||
|
91 | try: | |||
|
92 | del c.__instance_refs[index] | |||
|
93 | except KeyError: | |||
|
94 | pass | |||
65 |
|
95 | |||
66 | return instance |
|
96 | def clear_instances(cls): | |
|
97 | """Clear all instances tracked by cls.""" | |||
|
98 | cls.__instance_refs.clear() | |||
|
99 | cls.__numcreated = 0 | |||
67 |
|
100 | |||
68 | def get_instances(cls, name=None, root=None, klass=None): |
|
101 | def get_instances(cls, name=None, root=None, klass=None): | |
69 | """Get all instances of cls and its subclasses. |
|
102 | """Get all instances of cls and its subclasses. | |
70 |
|
103 | |||
71 | Parameters |
|
104 | Parameters | |
72 | ---------- |
|
105 | ---------- | |
73 | name : str |
|
106 | name : str | |
74 | Limit to components with this name. |
|
107 | Limit to components with this name. | |
75 | root : Component or subclass |
|
108 | root : Component or subclass | |
76 | Limit to components having this root. |
|
109 | Limit to components having this root. | |
77 | klass : class or str |
|
110 | klass : class or str | |
78 | Limits to instances of the class or its subclasses. If a str |
|
111 | Limits to instances of the class or its subclasses. If a str | |
79 | is given ut must be in the form 'foo.bar.MyClass'. The str |
|
112 | is given ut must be in the form 'foo.bar.MyClass'. The str | |
80 | form of this argument is useful for forward declarations. |
|
113 | form of this argument is useful for forward declarations. | |
81 | """ |
|
114 | """ | |
82 | if klass is not None: |
|
115 | if klass is not None: | |
83 | if isinstance(klass, basestring): |
|
116 | if isinstance(klass, basestring): | |
84 | klass = import_item(klass) |
|
117 | klass = import_item(klass) | |
|
118 | # Limit search to instances of klass for performance | |||
|
119 | if issubclass(klass, Component): | |||
|
120 | return klass.get_instances(name=name, root=root) | |||
85 | instances = cls.__instance_refs.values() |
|
121 | instances = cls.__instance_refs.values() | |
86 | if name is not None: |
|
122 | if name is not None: | |
87 | instances = [i for i in instances if i.name == name] |
|
123 | instances = [i for i in instances if i.name == name] | |
88 | if klass is not None: |
|
124 | if klass is not None: | |
89 | instances = [i for i in instances if isinstance(i, klass)] |
|
125 | instances = [i for i in instances if isinstance(i, klass)] | |
90 | if root is not None: |
|
126 | if root is not None: | |
91 | instances = [i for i in instances if i.root == root] |
|
127 | instances = [i for i in instances if i.root == root] | |
92 | return instances |
|
128 | return instances | |
93 |
|
129 | |||
94 | def get_instances_by_condition(cls, call, name=None, root=None, |
|
130 | def get_instances_by_condition(cls, call, name=None, root=None, | |
95 | klass=None): |
|
131 | klass=None): | |
96 | """Get all instances of cls, i such that call(i)==True. |
|
132 | """Get all instances of cls, i such that call(i)==True. | |
97 |
|
133 | |||
98 | This also takes the ``name`` and ``root`` and ``classname`` |
|
134 | This also takes the ``name`` and ``root`` and ``classname`` | |
99 | arguments of :meth:`get_instance` |
|
135 | arguments of :meth:`get_instance` | |
100 | """ |
|
136 | """ | |
101 | return [i for i in cls.get_instances(name, root, klass) if call(i)] |
|
137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] | |
102 |
|
138 | |||
103 |
|
139 | |||
|
140 | def masquerade_as(instance, cls): | |||
|
141 | """Let instance masquerade as an instance of cls. | |||
|
142 | ||||
|
143 | Sometimes, such as in testing code, it is useful to let a class | |||
|
144 | masquerade as another. Python, being duck typed, allows this by | |||
|
145 | default. But, instances of components are tracked by their class type. | |||
|
146 | ||||
|
147 | After calling this, cls.get_instances() will return ``instance``. This | |||
|
148 | does not, however, cause isinstance(instance, cls) to return ``True``. | |||
|
149 | ||||
|
150 | Parameters | |||
|
151 | ---------- | |||
|
152 | instance : an instance of a Component or Component subclass | |||
|
153 | The instance that will pretend to be a cls. | |||
|
154 | cls : subclass of Component | |||
|
155 | The Component subclass that instance will pretend to be. | |||
|
156 | """ | |||
|
157 | cls.register_instance(instance) | |||
|
158 | ||||
|
159 | ||||
104 | class ComponentNameGenerator(object): |
|
160 | class ComponentNameGenerator(object): | |
105 | """A Singleton to generate unique component names.""" |
|
161 | """A Singleton to generate unique component names.""" | |
106 |
|
162 | |||
107 | def __init__(self, prefix): |
|
163 | def __init__(self, prefix): | |
108 | self.prefix = prefix |
|
164 | self.prefix = prefix | |
109 | self.i = 0 |
|
165 | self.i = 0 | |
110 |
|
166 | |||
111 | def __call__(self): |
|
167 | def __call__(self): | |
112 | count = self.i |
|
168 | count = self.i | |
113 | self.i += 1 |
|
169 | self.i += 1 | |
114 | return "%s%s" % (self.prefix, count) |
|
170 | return "%s%s" % (self.prefix, count) | |
115 |
|
171 | |||
116 |
|
172 | |||
117 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') |
|
173 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') | |
118 |
|
174 | |||
119 |
|
175 | |||
120 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): |
|
176 | class MetaComponent(MetaHasTraitlets, MetaComponentTracker): | |
121 | pass |
|
177 | pass | |
122 |
|
178 | |||
123 |
|
179 | |||
124 | #----------------------------------------------------------------------------- |
|
180 | #----------------------------------------------------------------------------- | |
125 | # Component implementation |
|
181 | # Component implementation | |
126 | #----------------------------------------------------------------------------- |
|
182 | #----------------------------------------------------------------------------- | |
127 |
|
183 | |||
128 |
|
184 | |||
129 | class Component(HasTraitlets): |
|
185 | class Component(HasTraitlets): | |
130 |
|
186 | |||
131 | __metaclass__ = MetaComponent |
|
187 | __metaclass__ = MetaComponent | |
132 |
|
188 | |||
133 | # Traitlets are fun! |
|
189 | # Traitlets are fun! | |
134 | config = Instance(Struct,(),{}) |
|
190 | config = Instance(Struct,(),{}) | |
135 | parent = This() |
|
191 | parent = This() | |
136 | root = This() |
|
192 | root = This() | |
137 | created = None |
|
193 | created = None | |
138 |
|
194 | |||
139 | def __init__(self, parent, name=None, config=None): |
|
195 | def __init__(self, parent, name=None, config=None): | |
140 | """Create a component given a parent and possibly and name and config. |
|
196 | """Create a component given a parent and possibly and name and config. | |
141 |
|
197 | |||
142 | Parameters |
|
198 | Parameters | |
143 | ---------- |
|
199 | ---------- | |
144 | parent : Component subclass |
|
200 | parent : Component subclass | |
145 | The parent in the component graph. The parent is used |
|
201 | The parent in the component graph. The parent is used | |
146 | to get the root of the component graph. |
|
202 | to get the root of the component graph. | |
147 | name : str |
|
203 | name : str | |
148 | The unique name of the component. If empty, then a unique |
|
204 | The unique name of the component. If empty, then a unique | |
149 | one will be autogenerated. |
|
205 | one will be autogenerated. | |
150 | config : Struct |
|
206 | config : Struct | |
151 | If this is empty, self.config = parent.config, otherwise |
|
207 | If this is empty, self.config = parent.config, otherwise | |
152 | self.config = config and root.config is ignored. This argument |
|
208 | self.config = config and root.config is ignored. This argument | |
153 | should only be used to *override* the automatic inheritance of |
|
209 | should only be used to *override* the automatic inheritance of | |
154 | parent.config. If a caller wants to modify parent.config |
|
210 | parent.config. If a caller wants to modify parent.config | |
155 | (not override), the caller should make a copy and change |
|
211 | (not override), the caller should make a copy and change | |
156 | attributes and then pass the copy to this argument. |
|
212 | attributes and then pass the copy to this argument. | |
157 |
|
213 | |||
158 | Notes |
|
214 | Notes | |
159 | ----- |
|
215 | ----- | |
160 | Subclasses of Component must call the :meth:`__init__` method of |
|
216 | Subclasses of Component must call the :meth:`__init__` method of | |
161 | :class:`Component` *before* doing anything else and using |
|
217 | :class:`Component` *before* doing anything else and using | |
162 | :func:`super`:: |
|
218 | :func:`super`:: | |
163 |
|
219 | |||
164 | class MyComponent(Component): |
|
220 | class MyComponent(Component): | |
165 | def __init__(self, parent, name=None, config=None): |
|
221 | def __init__(self, parent, name=None, config=None): | |
166 | super(MyComponent, self).__init__(parent, name, config) |
|
222 | super(MyComponent, self).__init__(parent, name, config) | |
167 | # Then any other code you need to finish initialization. |
|
223 | # Then any other code you need to finish initialization. | |
168 |
|
224 | |||
169 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` |
|
225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` | |
170 | attributes are handled properly. |
|
226 | attributes are handled properly. | |
171 | """ |
|
227 | """ | |
172 | super(Component, self).__init__() |
|
228 | super(Component, self).__init__() | |
173 | self._children = [] |
|
229 | self._children = [] | |
174 | if name is None: |
|
230 | if name is None: | |
175 | self.name = ComponentNameGenerator() |
|
231 | self.name = ComponentNameGenerator() | |
176 | else: |
|
232 | else: | |
177 | self.name = name |
|
233 | self.name = name | |
178 | self.root = self # This is the default, it is set when parent is set |
|
234 | self.root = self # This is the default, it is set when parent is set | |
179 | self.parent = parent |
|
235 | self.parent = parent | |
180 | if config is not None: |
|
236 | if config is not None: | |
181 | self.config = deepcopy(config) |
|
237 | self.config = deepcopy(config) | |
182 | else: |
|
238 | else: | |
183 | if self.parent is not None: |
|
239 | if self.parent is not None: | |
184 | self.config = deepcopy(self.parent.config) |
|
240 | self.config = deepcopy(self.parent.config) | |
185 |
|
241 | |||
186 | self.created = datetime.datetime.now() |
|
242 | self.created = datetime.datetime.now() | |
187 |
|
243 | |||
188 | #------------------------------------------------------------------------- |
|
244 | #------------------------------------------------------------------------- | |
189 | # Static traitlet notifiations |
|
245 | # Static traitlet notifiations | |
190 | #------------------------------------------------------------------------- |
|
246 | #------------------------------------------------------------------------- | |
191 |
|
247 | |||
192 | def _parent_changed(self, name, old, new): |
|
248 | def _parent_changed(self, name, old, new): | |
193 | if old is not None: |
|
249 | if old is not None: | |
194 | old._remove_child(self) |
|
250 | old._remove_child(self) | |
195 | if new is not None: |
|
251 | if new is not None: | |
196 | new._add_child(self) |
|
252 | new._add_child(self) | |
197 |
|
253 | |||
198 | if new is None: |
|
254 | if new is None: | |
199 | self.root = self |
|
255 | self.root = self | |
200 | else: |
|
256 | else: | |
201 | self.root = new.root |
|
257 | self.root = new.root | |
202 |
|
258 | |||
203 | def _root_changed(self, name, old, new): |
|
259 | def _root_changed(self, name, old, new): | |
204 | if self.parent is None: |
|
260 | if self.parent is None: | |
205 | if not (new is self): |
|
261 | if not (new is self): | |
206 | raise ComponentError("Root not self, but parent is None.") |
|
262 | raise ComponentError("Root not self, but parent is None.") | |
207 | else: |
|
263 | else: | |
208 | if not self.parent.root is new: |
|
264 | if not self.parent.root is new: | |
209 | raise ComponentError("Error in setting the root attribute: " |
|
265 | raise ComponentError("Error in setting the root attribute: " | |
210 | "root != parent.root") |
|
266 | "root != parent.root") | |
211 |
|
267 | |||
212 | def _config_changed(self, name, old, new): |
|
268 | def _config_changed(self, name, old, new): | |
213 | """Update all the class traits having a config_key with the config. |
|
269 | """Update all the class traits having a config_key with the config. | |
214 |
|
270 | |||
215 | For any class traitlet with a ``config_key`` metadata attribute, we |
|
271 | For any class traitlet with a ``config_key`` metadata attribute, we | |
216 | update the traitlet with the value of the corresponding config entry. |
|
272 | update the traitlet with the value of the corresponding config entry. | |
217 |
|
273 | |||
218 | In the future, we might want to do a pop here so stale config info |
|
274 | In the future, we might want to do a pop here so stale config info | |
219 | is not passed onto children. |
|
275 | is not passed onto children. | |
220 | """ |
|
276 | """ | |
221 | # Get all traitlets with a config_key metadata entry |
|
277 | # Get all traitlets with a config_key metadata entry | |
222 | traitlets = self.traitlets('config_key') |
|
278 | traitlets = self.traitlets('config_key') | |
223 | for k, v in traitlets.items(): |
|
279 | for k, v in traitlets.items(): | |
224 | try: |
|
280 | try: | |
225 | config_value = new[v.get_metadata('config_key')] |
|
281 | config_value = new[v.get_metadata('config_key')] | |
226 | except KeyError: |
|
282 | except KeyError: | |
227 | pass |
|
283 | pass | |
228 | else: |
|
284 | else: | |
229 | setattr(self, k, config_value) |
|
285 | setattr(self, k, config_value) | |
230 |
|
286 | |||
231 | @property |
|
287 | @property | |
232 | def children(self): |
|
288 | def children(self): | |
233 | """A list of all my child components.""" |
|
289 | """A list of all my child components.""" | |
234 | return self._children |
|
290 | return self._children | |
235 |
|
291 | |||
236 | def _remove_child(self, child): |
|
292 | def _remove_child(self, child): | |
237 | """A private method for removing children components.""" |
|
293 | """A private method for removing children components.""" | |
238 | if child in self._children: |
|
294 | if child in self._children: | |
239 | index = self._children.index(child) |
|
295 | index = self._children.index(child) | |
240 | del self._children[index] |
|
296 | del self._children[index] | |
241 |
|
297 | |||
242 | def _add_child(self, child): |
|
298 | def _add_child(self, child): | |
243 | """A private method for adding children components.""" |
|
299 | """A private method for adding children components.""" | |
244 | if child not in self._children: |
|
300 | if child not in self._children: | |
245 | self._children.append(child) |
|
301 | self._children.append(child) | |
246 |
|
302 | |||
247 | def __repr__(self): |
|
303 | def __repr__(self): | |
248 |
return "< |
|
304 | return "<%s('%s')>" % (self.__class__.__name__, "DummyName") | |
|
305 | # return "<Component('%s')>" % self.name |
@@ -1,317 +1,318 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The main IPython application object |
|
4 | The main IPython application object | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | import os |
|
26 | import os | |
27 | import sys |
|
27 | import sys | |
28 | import warnings |
|
28 | import warnings | |
29 |
|
29 | |||
30 | from IPython.core.application import Application |
|
30 | from IPython.core.application import Application | |
31 | from IPython.core import release |
|
31 | from IPython.core import release | |
32 | from IPython.core.iplib import InteractiveShell |
|
32 | from IPython.core.iplib import InteractiveShell | |
33 | from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault |
|
33 | from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault | |
34 |
|
34 | |||
35 | from IPython.utils.ipstruct import Struct |
|
35 | from IPython.utils.ipstruct import Struct | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Utilities and helpers |
|
39 | # Utilities and helpers | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | ipython_desc = """ |
|
43 | ipython_desc = """ | |
44 | A Python shell with automatic history (input and output), dynamic object |
|
44 | A Python shell with automatic history (input and output), dynamic object | |
45 | introspection, easier configuration, command completion, access to the system |
|
45 | introspection, easier configuration, command completion, access to the system | |
46 | shell and more. |
|
46 | shell and more. | |
47 | """ |
|
47 | """ | |
48 |
|
48 | |||
49 | def threaded_shell_warning(): |
|
49 | def threaded_shell_warning(): | |
50 | msg = """ |
|
50 | msg = """ | |
51 |
|
51 | |||
52 | The IPython threaded shells and their associated command line |
|
52 | The IPython threaded shells and their associated command line | |
53 | arguments (pylab/wthread/gthread/qthread/q4thread) have been |
|
53 | arguments (pylab/wthread/gthread/qthread/q4thread) have been | |
54 | deprecated. See the %gui magic for information on the new interface. |
|
54 | deprecated. See the %gui magic for information on the new interface. | |
55 | """ |
|
55 | """ | |
56 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) |
|
56 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | #----------------------------------------------------------------------------- |
|
59 | #----------------------------------------------------------------------------- | |
60 | # Main classes and functions |
|
60 | # Main classes and functions | |
61 | #----------------------------------------------------------------------------- |
|
61 | #----------------------------------------------------------------------------- | |
62 |
|
62 | |||
63 | cl_args = ( |
|
63 | cl_args = ( | |
64 | (('-autocall',), dict( |
|
64 | (('-autocall',), dict( | |
65 | type=int, dest='AUTOCALL', default=NoDefault, |
|
65 | type=int, dest='AUTOCALL', default=NoDefault, | |
66 | help='Set the autocall value (0,1,2).') |
|
66 | help='Set the autocall value (0,1,2).') | |
67 | ), |
|
67 | ), | |
68 | (('-autoindent',), dict( |
|
68 | (('-autoindent',), dict( | |
69 | action='store_true', dest='AUTOINDENT', default=NoDefault, |
|
69 | action='store_true', dest='AUTOINDENT', default=NoDefault, | |
70 | help='Turn on autoindenting.') |
|
70 | help='Turn on autoindenting.') | |
71 | ), |
|
71 | ), | |
72 | (('-noautoindent',), dict( |
|
72 | (('-noautoindent',), dict( | |
73 | action='store_false', dest='AUTOINDENT', default=NoDefault, |
|
73 | action='store_false', dest='AUTOINDENT', default=NoDefault, | |
74 | help='Turn off autoindenting.') |
|
74 | help='Turn off autoindenting.') | |
75 | ), |
|
75 | ), | |
76 | (('-automagic',), dict( |
|
76 | (('-automagic',), dict( | |
77 | action='store_true', dest='AUTOMAGIC', default=NoDefault, |
|
77 | action='store_true', dest='AUTOMAGIC', default=NoDefault, | |
78 | help='Turn on the auto calling of magic commands.') |
|
78 | help='Turn on the auto calling of magic commands.') | |
79 | ), |
|
79 | ), | |
80 | (('-noautomagic',), dict( |
|
80 | (('-noautomagic',), dict( | |
81 | action='store_false', dest='AUTOMAGIC', default=NoDefault, |
|
81 | action='store_false', dest='AUTOMAGIC', default=NoDefault, | |
82 | help='Turn off the auto calling of magic commands.') |
|
82 | help='Turn off the auto calling of magic commands.') | |
83 | ), |
|
83 | ), | |
84 | (('-autoedit_syntax',), dict( |
|
84 | (('-autoedit_syntax',), dict( | |
85 | action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault, |
|
85 | action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault, | |
86 | help='Turn on auto editing of files with syntax errors.') |
|
86 | help='Turn on auto editing of files with syntax errors.') | |
87 | ), |
|
87 | ), | |
88 | (('-noautoedit_syntax',), dict( |
|
88 | (('-noautoedit_syntax',), dict( | |
89 | action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault, |
|
89 | action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault, | |
90 | help='Turn off auto editing of files with syntax errors.') |
|
90 | help='Turn off auto editing of files with syntax errors.') | |
91 | ), |
|
91 | ), | |
92 | (('-banner',), dict( |
|
92 | (('-banner',), dict( | |
93 | action='store_true', dest='DISPLAY_BANNER', default=NoDefault, |
|
93 | action='store_true', dest='DISPLAY_BANNER', default=NoDefault, | |
94 | help='Display a banner upon starting IPython.') |
|
94 | help='Display a banner upon starting IPython.') | |
95 | ), |
|
95 | ), | |
96 | (('-nobanner',), dict( |
|
96 | (('-nobanner',), dict( | |
97 | action='store_false', dest='DISPLAY_BANNER', default=NoDefault, |
|
97 | action='store_false', dest='DISPLAY_BANNER', default=NoDefault, | |
98 | help="Don't display a banner upon starting IPython.") |
|
98 | help="Don't display a banner upon starting IPython.") | |
99 | ), |
|
99 | ), | |
100 | (('-c',), dict( |
|
100 | (('-c',), dict( | |
101 | type=str, dest='C', default=NoDefault, |
|
101 | type=str, dest='C', default=NoDefault, | |
102 | help="Execute the given command string.") |
|
102 | help="Execute the given command string.") | |
103 | ), |
|
103 | ), | |
104 | (('-cache_size',), dict( |
|
104 | (('-cache_size',), dict( | |
105 | type=int, dest='CACHE_SIZE', default=NoDefault, |
|
105 | type=int, dest='CACHE_SIZE', default=NoDefault, | |
106 | help="Set the size of the output cache.") |
|
106 | help="Set the size of the output cache.") | |
107 | ), |
|
107 | ), | |
108 | (('-classic',), dict( |
|
108 | (('-classic',), dict( | |
109 | action='store_true', dest='CLASSIC', default=NoDefault, |
|
109 | action='store_true', dest='CLASSIC', default=NoDefault, | |
110 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
110 | help="Gives IPython a similar feel to the classic Python prompt.") | |
111 | ), |
|
111 | ), | |
112 | (('-colors',), dict( |
|
112 | (('-colors',), dict( | |
113 | type=str, dest='COLORS', default=NoDefault, |
|
113 | type=str, dest='COLORS', default=NoDefault, | |
114 | help="Set the color scheme (NoColor, Linux, and LightBG).") |
|
114 | help="Set the color scheme (NoColor, Linux, and LightBG).") | |
115 | ), |
|
115 | ), | |
116 | (('-color_info',), dict( |
|
116 | (('-color_info',), dict( | |
117 | action='store_true', dest='COLOR_INFO', default=NoDefault, |
|
117 | action='store_true', dest='COLOR_INFO', default=NoDefault, | |
118 | help="Enable using colors for info related things.") |
|
118 | help="Enable using colors for info related things.") | |
119 | ), |
|
119 | ), | |
120 | (('-nocolor_info',), dict( |
|
120 | (('-nocolor_info',), dict( | |
121 | action='store_false', dest='COLOR_INFO', default=NoDefault, |
|
121 | action='store_false', dest='COLOR_INFO', default=NoDefault, | |
122 | help="Disable using colors for info related things.") |
|
122 | help="Disable using colors for info related things.") | |
123 | ), |
|
123 | ), | |
124 | (('-confirm_exit',), dict( |
|
124 | (('-confirm_exit',), dict( | |
125 | action='store_true', dest='CONFIRM_EXIT', default=NoDefault, |
|
125 | action='store_true', dest='CONFIRM_EXIT', default=NoDefault, | |
126 | help="Prompt the user when existing.") |
|
126 | help="Prompt the user when existing.") | |
127 | ), |
|
127 | ), | |
128 | (('-noconfirm_exit',), dict( |
|
128 | (('-noconfirm_exit',), dict( | |
129 | action='store_false', dest='CONFIRM_EXIT', default=NoDefault, |
|
129 | action='store_false', dest='CONFIRM_EXIT', default=NoDefault, | |
130 | help="Don't prompt the user when existing.") |
|
130 | help="Don't prompt the user when existing.") | |
131 | ), |
|
131 | ), | |
132 | (('-deep_reload',), dict( |
|
132 | (('-deep_reload',), dict( | |
133 | action='store_true', dest='DEEP_RELOAD', default=NoDefault, |
|
133 | action='store_true', dest='DEEP_RELOAD', default=NoDefault, | |
134 | help="Enable deep (recursive) reloading by default.") |
|
134 | help="Enable deep (recursive) reloading by default.") | |
135 | ), |
|
135 | ), | |
136 | (('-nodeep_reload',), dict( |
|
136 | (('-nodeep_reload',), dict( | |
137 | action='store_false', dest='DEEP_RELOAD', default=NoDefault, |
|
137 | action='store_false', dest='DEEP_RELOAD', default=NoDefault, | |
138 | help="Disable deep (recursive) reloading by default.") |
|
138 | help="Disable deep (recursive) reloading by default.") | |
139 | ), |
|
139 | ), | |
140 | (('-editor',), dict( |
|
140 | (('-editor',), dict( | |
141 | type=str, dest='EDITOR', default=NoDefault, |
|
141 | type=str, dest='EDITOR', default=NoDefault, | |
142 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).") |
|
142 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).") | |
143 | ), |
|
143 | ), | |
144 | (('-log','-l'), dict( |
|
144 | (('-log','-l'), dict( | |
145 | action='store_true', dest='LOGSTART', default=NoDefault, |
|
145 | action='store_true', dest='LOGSTART', default=NoDefault, | |
146 | help="Start logging to the default file (./ipython_log.py).") |
|
146 | help="Start logging to the default file (./ipython_log.py).") | |
147 | ), |
|
147 | ), | |
148 | (('-logfile','-lf'), dict( |
|
148 | (('-logfile','-lf'), dict( | |
149 | type=str, dest='LOGFILE', default=NoDefault, |
|
149 | type=str, dest='LOGFILE', default=NoDefault, | |
150 | help="Specify the name of your logfile.") |
|
150 | help="Specify the name of your logfile.") | |
151 | ), |
|
151 | ), | |
152 | (('-logplay','-lp'), dict( |
|
152 | (('-logplay','-lp'), dict( | |
153 | type=str, dest='LOGPLAY', default=NoDefault, |
|
153 | type=str, dest='LOGPLAY', default=NoDefault, | |
154 | help="Re-play a log file and then append to it.") |
|
154 | help="Re-play a log file and then append to it.") | |
155 | ), |
|
155 | ), | |
156 | (('-pdb',), dict( |
|
156 | (('-pdb',), dict( | |
157 | action='store_true', dest='PDB', default=NoDefault, |
|
157 | action='store_true', dest='PDB', default=NoDefault, | |
158 | help="Enable auto calling the pdb debugger after every exception.") |
|
158 | help="Enable auto calling the pdb debugger after every exception.") | |
159 | ), |
|
159 | ), | |
160 | (('-nopdb',), dict( |
|
160 | (('-nopdb',), dict( | |
161 | action='store_false', dest='PDB', default=NoDefault, |
|
161 | action='store_false', dest='PDB', default=NoDefault, | |
162 | help="Disable auto calling the pdb debugger after every exception.") |
|
162 | help="Disable auto calling the pdb debugger after every exception.") | |
163 | ), |
|
163 | ), | |
164 | (('-pprint',), dict( |
|
164 | (('-pprint',), dict( | |
165 | action='store_true', dest='PPRINT', default=NoDefault, |
|
165 | action='store_true', dest='PPRINT', default=NoDefault, | |
166 | help="Enable auto pretty printing of results.") |
|
166 | help="Enable auto pretty printing of results.") | |
167 | ), |
|
167 | ), | |
168 | (('-nopprint',), dict( |
|
168 | (('-nopprint',), dict( | |
169 | action='store_false', dest='PPRINT', default=NoDefault, |
|
169 | action='store_false', dest='PPRINT', default=NoDefault, | |
170 | help="Disable auto auto pretty printing of results.") |
|
170 | help="Disable auto auto pretty printing of results.") | |
171 | ), |
|
171 | ), | |
172 | (('-prompt_in1','-pi1'), dict( |
|
172 | (('-prompt_in1','-pi1'), dict( | |
173 | type=str, dest='PROMPT_IN1', default=NoDefault, |
|
173 | type=str, dest='PROMPT_IN1', default=NoDefault, | |
174 | help="Set the main input prompt ('In [\#]: ')") |
|
174 | help="Set the main input prompt ('In [\#]: ')") | |
175 | ), |
|
175 | ), | |
176 | (('-prompt_in2','-pi2'), dict( |
|
176 | (('-prompt_in2','-pi2'), dict( | |
177 | type=str, dest='PROMPT_IN2', default=NoDefault, |
|
177 | type=str, dest='PROMPT_IN2', default=NoDefault, | |
178 | help="Set the secondary input prompt (' .\D.: ')") |
|
178 | help="Set the secondary input prompt (' .\D.: ')") | |
179 | ), |
|
179 | ), | |
180 | (('-prompt_out','-po'), dict( |
|
180 | (('-prompt_out','-po'), dict( | |
181 | type=str, dest='PROMPT_OUT', default=NoDefault, |
|
181 | type=str, dest='PROMPT_OUT', default=NoDefault, | |
182 | help="Set the output prompt ('Out[\#]:')") |
|
182 | help="Set the output prompt ('Out[\#]:')") | |
183 | ), |
|
183 | ), | |
184 | (('-quick',), dict( |
|
184 | (('-quick',), dict( | |
185 | action='store_true', dest='QUICK', default=NoDefault, |
|
185 | action='store_true', dest='QUICK', default=NoDefault, | |
186 | help="Enable quick startup with no config files.") |
|
186 | help="Enable quick startup with no config files.") | |
187 | ), |
|
187 | ), | |
188 | (('-readline',), dict( |
|
188 | (('-readline',), dict( | |
189 | action='store_true', dest='READLINE_USE', default=NoDefault, |
|
189 | action='store_true', dest='READLINE_USE', default=NoDefault, | |
190 | help="Enable readline for command line usage.") |
|
190 | help="Enable readline for command line usage.") | |
191 | ), |
|
191 | ), | |
192 | (('-noreadline',), dict( |
|
192 | (('-noreadline',), dict( | |
193 | action='store_false', dest='READLINE_USE', default=NoDefault, |
|
193 | action='store_false', dest='READLINE_USE', default=NoDefault, | |
194 | help="Disable readline for command line usage.") |
|
194 | help="Disable readline for command line usage.") | |
195 | ), |
|
195 | ), | |
196 | (('-screen_length','-sl'), dict( |
|
196 | (('-screen_length','-sl'), dict( | |
197 | type=int, dest='SCREEN_LENGTH', default=NoDefault, |
|
197 | type=int, dest='SCREEN_LENGTH', default=NoDefault, | |
198 | help='Number of lines on screen, used to control printing of long strings.') |
|
198 | help='Number of lines on screen, used to control printing of long strings.') | |
199 | ), |
|
199 | ), | |
200 | (('-separate_in','-si'), dict( |
|
200 | (('-separate_in','-si'), dict( | |
201 | type=str, dest='SEPARATE_IN', default=NoDefault, |
|
201 | type=str, dest='SEPARATE_IN', default=NoDefault, | |
202 | help="Separator before input prompts. Default '\n'.") |
|
202 | help="Separator before input prompts. Default '\n'.") | |
203 | ), |
|
203 | ), | |
204 | (('-separate_out','-so'), dict( |
|
204 | (('-separate_out','-so'), dict( | |
205 | type=str, dest='SEPARATE_OUT', default=NoDefault, |
|
205 | type=str, dest='SEPARATE_OUT', default=NoDefault, | |
206 | help="Separator before output prompts. Default 0 (nothing).") |
|
206 | help="Separator before output prompts. Default 0 (nothing).") | |
207 | ), |
|
207 | ), | |
208 | (('-separate_out2','-so2'), dict( |
|
208 | (('-separate_out2','-so2'), dict( | |
209 | type=str, dest='SEPARATE_OUT2', default=NoDefault, |
|
209 | type=str, dest='SEPARATE_OUT2', default=NoDefault, | |
210 | help="Separator after output prompts. Default 0 (nonight).") |
|
210 | help="Separator after output prompts. Default 0 (nonight).") | |
211 | ), |
|
211 | ), | |
212 | (('-nosep',), dict( |
|
212 | (('-nosep',), dict( | |
213 | action='store_true', dest='NOSEP', default=NoDefault, |
|
213 | action='store_true', dest='NOSEP', default=NoDefault, | |
214 | help="Eliminate all spacing between prompts.") |
|
214 | help="Eliminate all spacing between prompts.") | |
215 | ), |
|
215 | ), | |
216 | (('-term_title',), dict( |
|
216 | (('-term_title',), dict( | |
217 | action='store_true', dest='TERM_TITLE', default=NoDefault, |
|
217 | action='store_true', dest='TERM_TITLE', default=NoDefault, | |
218 | help="Enable auto setting the terminal title.") |
|
218 | help="Enable auto setting the terminal title.") | |
219 | ), |
|
219 | ), | |
220 | (('-noterm_title',), dict( |
|
220 | (('-noterm_title',), dict( | |
221 | action='store_false', dest='TERM_TITLE', default=NoDefault, |
|
221 | action='store_false', dest='TERM_TITLE', default=NoDefault, | |
222 | help="Disable auto setting the terminal title.") |
|
222 | help="Disable auto setting the terminal title.") | |
223 | ), |
|
223 | ), | |
224 | (('-xmode',), dict( |
|
224 | (('-xmode',), dict( | |
225 | type=str, dest='XMODE', default=NoDefault, |
|
225 | type=str, dest='XMODE', default=NoDefault, | |
226 | help="Exception mode ('Plain','Context','Verbose')") |
|
226 | help="Exception mode ('Plain','Context','Verbose')") | |
227 | ), |
|
227 | ), | |
228 | # These are only here to get the proper deprecation warnings |
|
228 | # These are only here to get the proper deprecation warnings | |
229 | (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict( |
|
229 | (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict( | |
230 | action='store_true', dest='THREADED_SHELL', default=NoDefault, |
|
230 | action='store_true', dest='THREADED_SHELL', default=NoDefault, | |
231 | help="These command line flags are deprecated, see the 'gui' magic.") |
|
231 | help="These command line flags are deprecated, see the 'gui' magic.") | |
232 | ), |
|
232 | ), | |
233 | ) |
|
233 | ) | |
234 |
|
234 | |||
235 |
|
235 | |||
236 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): |
|
236 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): | |
237 |
|
237 | |||
238 | arguments = cl_args |
|
238 | arguments = cl_args | |
239 |
|
239 | |||
240 |
|
240 | |||
241 | class IPythonApp(Application): |
|
241 | class IPythonApp(Application): | |
242 | name = 'ipython' |
|
242 | name = 'ipython' | |
243 | config_file_name = 'ipython_config.py' |
|
243 | config_file_name = 'ipython_config.py' | |
244 |
|
244 | |||
245 | def create_command_line_config(self): |
|
245 | def create_command_line_config(self): | |
246 | """Create and return a command line config loader.""" |
|
246 | """Create and return a command line config loader.""" | |
247 | return IPythonAppCLConfigLoader( |
|
247 | return IPythonAppCLConfigLoader( | |
248 | description=ipython_desc, |
|
248 | description=ipython_desc, | |
249 | version=release.version) |
|
249 | version=release.version) | |
250 |
|
250 | |||
251 | def post_load_command_line_config(self): |
|
251 | def post_load_command_line_config(self): | |
252 | """Do actions after loading cl config.""" |
|
252 | """Do actions after loading cl config.""" | |
253 | clc = self.command_line_config |
|
253 | clc = self.command_line_config | |
254 |
|
254 | |||
255 | # This needs to be set here, the rest are set in pre_construct. |
|
255 | # This needs to be set here, the rest are set in pre_construct. | |
256 | if hasattr(clc, 'CLASSIC'): |
|
256 | if hasattr(clc, 'CLASSIC'): | |
257 | if clc.CLASSIC: clc.QUICK = 1 |
|
257 | if clc.CLASSIC: clc.QUICK = 1 | |
258 |
|
258 | |||
259 | # Display the deprecation warnings about threaded shells |
|
259 | # Display the deprecation warnings about threaded shells | |
260 | if hasattr(clc, 'THREADED_SHELL'): |
|
260 | if hasattr(clc, 'THREADED_SHELL'): | |
261 | threaded_shell_warning() |
|
261 | threaded_shell_warning() | |
262 | del clc['THREADED_SHELL'] |
|
262 | del clc['THREADED_SHELL'] | |
263 |
|
263 | |||
264 | def load_file_config(self): |
|
264 | def load_file_config(self): | |
265 | if hasattr(self.command_line_config, 'QUICK'): |
|
265 | if hasattr(self.command_line_config, 'QUICK'): | |
266 | if self.command_line_config.QUICK: |
|
266 | if self.command_line_config.QUICK: | |
267 | self.file_config = Struct() |
|
267 | self.file_config = Struct() | |
268 | return |
|
268 | return | |
269 | super(IPythonApp, self).load_file_config() |
|
269 | super(IPythonApp, self).load_file_config() | |
270 |
|
270 | |||
271 | def post_load_file_config(self): |
|
271 | def post_load_file_config(self): | |
272 | """Logic goes here.""" |
|
272 | """Logic goes here.""" | |
273 |
|
273 | |||
274 | def pre_construct(self): |
|
274 | def pre_construct(self): | |
275 | config = self.master_config |
|
275 | config = self.master_config | |
276 |
|
276 | |||
277 | if hasattr(config, 'CLASSIC'): |
|
277 | if hasattr(config, 'CLASSIC'): | |
278 | if config.CLASSIC: |
|
278 | if config.CLASSIC: | |
279 | config.QUICK = 1 |
|
279 | config.QUICK = 1 | |
280 | config.CACHE_SIZE = 0 |
|
280 | config.CACHE_SIZE = 0 | |
281 | config.PPRINT = 0 |
|
281 | config.PPRINT = 0 | |
282 | config.PROMPT_IN1 = '>>> ' |
|
282 | config.PROMPT_IN1 = '>>> ' | |
283 | config.PROMPT_IN2 = '... ' |
|
283 | config.PROMPT_IN2 = '... ' | |
284 | config.PROMPT_OUT = '' |
|
284 | config.PROMPT_OUT = '' | |
285 | config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '' |
|
285 | config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '' | |
286 | config.COLORS = 'NoColor' |
|
286 | config.COLORS = 'NoColor' | |
287 | config.XMODE = 'Plain' |
|
287 | config.XMODE = 'Plain' | |
288 |
|
288 | |||
289 | # All this should be moved to traitlet handlers in InteractiveShell |
|
289 | # All this should be moved to traitlet handlers in InteractiveShell | |
290 | # But, currently InteractiveShell doesn't have support for changing |
|
290 | # But, currently InteractiveShell doesn't have support for changing | |
291 | # these values at runtime. Once we support that, this should |
|
291 | # these values at runtime. Once we support that, this should | |
292 | # be moved there!!! |
|
292 | # be moved there!!! | |
293 | if hasattr(config, 'NOSEP'): |
|
293 | if hasattr(config, 'NOSEP'): | |
294 | if config.NOSEP: |
|
294 | if config.NOSEP: | |
295 | config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0' |
|
295 | config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0' | |
296 |
|
296 | |||
297 | def construct(self): |
|
297 | def construct(self): | |
298 | # I am a little hesitant to put these into InteractiveShell itself. |
|
298 | # I am a little hesitant to put these into InteractiveShell itself. | |
299 | # But that might be the place for them |
|
299 | # But that might be the place for them | |
300 | sys.path.insert(0, '') |
|
300 | sys.path.insert(0, '') | |
301 | # add personal ipythondir to sys.path so that users can put things in |
|
301 | # add personal ipythondir to sys.path so that users can put things in | |
302 | # there for customization |
|
302 | # there for customization | |
303 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
303 | sys.path.append(os.path.abspath(self.ipythondir)) | |
304 |
|
304 | |||
305 | # Create an InteractiveShell instance |
|
305 | # Create an InteractiveShell instance | |
306 | self.shell = InteractiveShell( |
|
306 | self.shell = InteractiveShell( | |
307 | parent=None, |
|
307 | parent=None, | |
308 | config=self.master_config |
|
308 | config=self.master_config | |
309 | ) |
|
309 | ) | |
310 |
|
310 | print self.shell | ||
|
311 | ||||
311 | def start_app(self): |
|
312 | def start_app(self): | |
312 | self.shell.mainloop() |
|
313 | self.shell.mainloop() | |
313 |
|
314 | |||
314 |
|
315 | |||
315 | if __name__ == '__main__': |
|
316 | if __name__ == '__main__': | |
316 | app = IPythonApp() |
|
317 | app = IPythonApp() | |
317 | app.start() No newline at end of file |
|
318 | app.start() |
@@ -1,3018 +1,2849 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Main IPython Component |
|
3 | Main IPython Component | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from __future__ import with_statement |
|
19 | from __future__ import with_statement | |
20 |
|
20 | |||
21 | import __main__ |
|
21 | import __main__ | |
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 | import StringIO |
|
23 | import StringIO | |
24 | import bdb |
|
24 | import bdb | |
25 | import codeop |
|
25 | import codeop | |
26 | import exceptions |
|
26 | import exceptions | |
27 | import glob |
|
27 | import glob | |
28 | import keyword |
|
28 | import keyword | |
29 | import new |
|
29 | import new | |
30 | import os |
|
30 | import os | |
31 | import re |
|
31 | import re | |
32 | import shutil |
|
32 | import shutil | |
33 | import string |
|
33 | import string | |
34 | import sys |
|
34 | import sys | |
35 | import tempfile |
|
35 | import tempfile | |
36 | from contextlib import nested |
|
36 | from contextlib import nested | |
37 |
|
37 | |||
38 | from IPython.core import ultratb |
|
38 | from IPython.core import ultratb | |
39 | from IPython.core import debugger, oinspect |
|
39 | from IPython.core import debugger, oinspect | |
40 | from IPython.core import shadowns |
|
40 | from IPython.core import shadowns | |
41 | from IPython.core import history as ipcorehist |
|
41 | from IPython.core import history as ipcorehist | |
42 | from IPython.core import prefilter |
|
42 | from IPython.core import prefilter | |
|
43 | from IPython.core.alias import AliasManager | |||
43 | from IPython.core.autocall import IPyAutocall |
|
44 | from IPython.core.autocall import IPyAutocall | |
44 | from IPython.core.builtin_trap import BuiltinTrap |
|
45 | from IPython.core.builtin_trap import BuiltinTrap | |
45 | from IPython.core.display_trap import DisplayTrap |
|
46 | from IPython.core.display_trap import DisplayTrap | |
46 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
47 | from IPython.core.logger import Logger |
|
48 | from IPython.core.logger import Logger | |
48 | from IPython.core.magic import Magic |
|
49 | from IPython.core.magic import Magic | |
49 | from IPython.core.prompts import CachedOutput |
|
50 | from IPython.core.prompts import CachedOutput | |
50 | from IPython.core.page import page |
|
51 | from IPython.core.page import page | |
51 | from IPython.core.component import Component |
|
52 | from IPython.core.component import Component | |
52 | from IPython.core.oldusersetup import user_setup |
|
53 | from IPython.core.oldusersetup import user_setup | |
53 | from IPython.core.usage import interactive_usage, default_banner |
|
54 | from IPython.core.usage import interactive_usage, default_banner | |
54 | from IPython.core.error import TryNext, UsageError |
|
55 | from IPython.core.error import TryNext, UsageError | |
55 |
|
56 | |||
56 | from IPython.extensions import pickleshare |
|
57 | from IPython.extensions import pickleshare | |
57 | from IPython.external.Itpl import ItplNS |
|
58 | from IPython.external.Itpl import ItplNS | |
58 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
59 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
59 | from IPython.utils.ipstruct import Struct |
|
60 | from IPython.utils.ipstruct import Struct | |
60 | from IPython.utils import PyColorize |
|
61 | from IPython.utils import PyColorize | |
61 | from IPython.utils.genutils import * |
|
62 | from IPython.utils.genutils import * | |
62 | from IPython.utils.strdispatch import StrDispatch |
|
63 | from IPython.utils.strdispatch import StrDispatch | |
63 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
64 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
64 |
|
65 | |||
|
66 | from IPython.utils import growl | |||
|
67 | growl.start("IPython") | |||
|
68 | ||||
65 | from IPython.utils.traitlets import ( |
|
69 | from IPython.utils.traitlets import ( | |
66 | Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
70 | Int, Float, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
67 | ) |
|
71 | ) | |
68 |
|
72 | |||
69 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
70 | # Globals |
|
74 | # Globals | |
71 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
72 |
|
76 | |||
73 |
|
77 | |||
74 | # store the builtin raw_input globally, and use this always, in case user code |
|
78 | # store the builtin raw_input globally, and use this always, in case user code | |
75 | # overwrites it (like wx.py.PyShell does) |
|
79 | # overwrites it (like wx.py.PyShell does) | |
76 | raw_input_original = raw_input |
|
80 | raw_input_original = raw_input | |
77 |
|
81 | |||
78 | # compiled regexps for autoindent management |
|
82 | # compiled regexps for autoindent management | |
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
83 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
80 |
|
84 | |||
81 |
|
85 | |||
82 | #----------------------------------------------------------------------------- |
|
86 | #----------------------------------------------------------------------------- | |
83 | # Utilities |
|
87 | # Utilities | |
84 | #----------------------------------------------------------------------------- |
|
88 | #----------------------------------------------------------------------------- | |
85 |
|
89 | |||
86 |
|
90 | |||
87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
91 | ini_spaces_re = re.compile(r'^(\s+)') | |
88 |
|
92 | |||
89 |
|
93 | |||
90 | def num_ini_spaces(strng): |
|
94 | def num_ini_spaces(strng): | |
91 | """Return the number of initial spaces in a string""" |
|
95 | """Return the number of initial spaces in a string""" | |
92 |
|
96 | |||
93 | ini_spaces = ini_spaces_re.match(strng) |
|
97 | ini_spaces = ini_spaces_re.match(strng) | |
94 | if ini_spaces: |
|
98 | if ini_spaces: | |
95 | return ini_spaces.end() |
|
99 | return ini_spaces.end() | |
96 | else: |
|
100 | else: | |
97 | return 0 |
|
101 | return 0 | |
98 |
|
102 | |||
99 |
|
103 | |||
100 | def softspace(file, newvalue): |
|
104 | def softspace(file, newvalue): | |
101 | """Copied from code.py, to remove the dependency""" |
|
105 | """Copied from code.py, to remove the dependency""" | |
102 |
|
106 | |||
103 | oldvalue = 0 |
|
107 | oldvalue = 0 | |
104 | try: |
|
108 | try: | |
105 | oldvalue = file.softspace |
|
109 | oldvalue = file.softspace | |
106 | except AttributeError: |
|
110 | except AttributeError: | |
107 | pass |
|
111 | pass | |
108 | try: |
|
112 | try: | |
109 | file.softspace = newvalue |
|
113 | file.softspace = newvalue | |
110 | except (AttributeError, TypeError): |
|
114 | except (AttributeError, TypeError): | |
111 | # "attribute-less object" or "read-only attributes" |
|
115 | # "attribute-less object" or "read-only attributes" | |
112 | pass |
|
116 | pass | |
113 | return oldvalue |
|
117 | return oldvalue | |
114 |
|
118 | |||
115 |
|
119 | |||
116 | class SpaceInInput(exceptions.Exception): pass |
|
120 | class SpaceInInput(exceptions.Exception): pass | |
117 |
|
121 | |||
118 | class Bunch: pass |
|
122 | class Bunch: pass | |
119 |
|
123 | |||
120 | class InputList(list): |
|
124 | class InputList(list): | |
121 | """Class to store user input. |
|
125 | """Class to store user input. | |
122 |
|
126 | |||
123 | It's basically a list, but slices return a string instead of a list, thus |
|
127 | It's basically a list, but slices return a string instead of a list, thus | |
124 | allowing things like (assuming 'In' is an instance): |
|
128 | allowing things like (assuming 'In' is an instance): | |
125 |
|
129 | |||
126 | exec In[4:7] |
|
130 | exec In[4:7] | |
127 |
|
131 | |||
128 | or |
|
132 | or | |
129 |
|
133 | |||
130 | exec In[5:9] + In[14] + In[21:25]""" |
|
134 | exec In[5:9] + In[14] + In[21:25]""" | |
131 |
|
135 | |||
132 | def __getslice__(self,i,j): |
|
136 | def __getslice__(self,i,j): | |
133 | return ''.join(list.__getslice__(self,i,j)) |
|
137 | return ''.join(list.__getslice__(self,i,j)) | |
134 |
|
138 | |||
135 |
|
139 | |||
136 | class SyntaxTB(ultratb.ListTB): |
|
140 | class SyntaxTB(ultratb.ListTB): | |
137 | """Extension which holds some state: the last exception value""" |
|
141 | """Extension which holds some state: the last exception value""" | |
138 |
|
142 | |||
139 | def __init__(self,color_scheme = 'NoColor'): |
|
143 | def __init__(self,color_scheme = 'NoColor'): | |
140 | ultratb.ListTB.__init__(self,color_scheme) |
|
144 | ultratb.ListTB.__init__(self,color_scheme) | |
141 | self.last_syntax_error = None |
|
145 | self.last_syntax_error = None | |
142 |
|
146 | |||
143 | def __call__(self, etype, value, elist): |
|
147 | def __call__(self, etype, value, elist): | |
144 | self.last_syntax_error = value |
|
148 | self.last_syntax_error = value | |
145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
149 | ultratb.ListTB.__call__(self,etype,value,elist) | |
146 |
|
150 | |||
147 | def clear_err_state(self): |
|
151 | def clear_err_state(self): | |
148 | """Return the current error state and clear it""" |
|
152 | """Return the current error state and clear it""" | |
149 | e = self.last_syntax_error |
|
153 | e = self.last_syntax_error | |
150 | self.last_syntax_error = None |
|
154 | self.last_syntax_error = None | |
151 | return e |
|
155 | return e | |
152 |
|
156 | |||
153 |
|
157 | |||
154 | def get_default_editor(): |
|
158 | def get_default_editor(): | |
155 | try: |
|
159 | try: | |
156 | ed = os.environ['EDITOR'] |
|
160 | ed = os.environ['EDITOR'] | |
157 | except KeyError: |
|
161 | except KeyError: | |
158 | if os.name == 'posix': |
|
162 | if os.name == 'posix': | |
159 | ed = 'vi' # the only one guaranteed to be there! |
|
163 | ed = 'vi' # the only one guaranteed to be there! | |
160 | else: |
|
164 | else: | |
161 | ed = 'notepad' # same in Windows! |
|
165 | ed = 'notepad' # same in Windows! | |
162 | return ed |
|
166 | return ed | |
163 |
|
167 | |||
164 |
|
168 | |||
165 | class SeparateStr(Str): |
|
169 | class SeparateStr(Str): | |
166 | """A Str subclass to validate separate_in, separate_out, etc. |
|
170 | """A Str subclass to validate separate_in, separate_out, etc. | |
167 |
|
171 | |||
168 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. |
|
172 | This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'. | |
169 | """ |
|
173 | """ | |
170 |
|
174 | |||
171 | def validate(self, obj, value): |
|
175 | def validate(self, obj, value): | |
172 | if value == '0': value = '' |
|
176 | if value == '0': value = '' | |
173 | value = value.replace('\\n','\n') |
|
177 | value = value.replace('\\n','\n') | |
174 | return super(SeparateStr, self).validate(obj, value) |
|
178 | return super(SeparateStr, self).validate(obj, value) | |
175 |
|
179 | |||
176 |
|
180 | |||
177 | #----------------------------------------------------------------------------- |
|
181 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
182 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
183 | #----------------------------------------------------------------------------- | |
180 |
|
184 | |||
181 |
|
185 | |||
182 | class InteractiveShell(Component, Magic): |
|
186 | class InteractiveShell(Component, Magic): | |
183 | """An enhanced, interactive shell for Python.""" |
|
187 | """An enhanced, interactive shell for Python.""" | |
184 |
|
188 | |||
185 | autocall = Enum((0,1,2), config_key='AUTOCALL') |
|
189 | autocall = Enum((0,1,2), config_key='AUTOCALL') | |
186 | autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX') |
|
190 | autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX') | |
187 | autoindent = CBool(True, config_key='AUTOINDENT') |
|
191 | autoindent = CBool(True, config_key='AUTOINDENT') | |
188 | automagic = CBool(True, config_key='AUTOMAGIC') |
|
192 | automagic = CBool(True, config_key='AUTOMAGIC') | |
189 | display_banner = CBool(True, config_key='DISPLAY_BANNER') |
|
193 | display_banner = CBool(True, config_key='DISPLAY_BANNER') | |
190 | banner = Str('') |
|
194 | banner = Str('') | |
191 | banner1 = Str(default_banner, config_key='BANNER1') |
|
195 | banner1 = Str(default_banner, config_key='BANNER1') | |
192 | banner2 = Str('', config_key='BANNER2') |
|
196 | banner2 = Str('', config_key='BANNER2') | |
193 | c = Str('', config_key='C') |
|
197 | c = Str('', config_key='C') | |
194 | cache_size = Int(1000, config_key='CACHE_SIZE') |
|
198 | cache_size = Int(1000, config_key='CACHE_SIZE') | |
195 | classic = CBool(False, config_key='CLASSIC') |
|
199 | classic = CBool(False, config_key='CLASSIC') | |
196 | color_info = CBool(True, config_key='COLOR_INFO') |
|
200 | color_info = CBool(True, config_key='COLOR_INFO') | |
197 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
201 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
198 | default_value='LightBG', config_key='COLORS') |
|
202 | default_value='LightBG', config_key='COLORS') | |
199 | confirm_exit = CBool(True, config_key='CONFIRM_EXIT') |
|
203 | confirm_exit = CBool(True, config_key='CONFIRM_EXIT') | |
200 | debug = CBool(False, config_key='DEBUG') |
|
204 | debug = CBool(False, config_key='DEBUG') | |
201 | deep_reload = CBool(False, config_key='DEEP_RELOAD') |
|
205 | deep_reload = CBool(False, config_key='DEEP_RELOAD') | |
202 | embedded = CBool(False) |
|
206 | embedded = CBool(False) | |
203 | embedded_active = CBool(False) |
|
207 | embedded_active = CBool(False) | |
204 | editor = Str(get_default_editor(), config_key='EDITOR') |
|
208 | editor = Str(get_default_editor(), config_key='EDITOR') | |
205 | filename = Str("<ipython console>") |
|
209 | filename = Str("<ipython console>") | |
206 | interactive = CBool(False, config_key='INTERACTIVE') |
|
210 | interactive = CBool(False, config_key='INTERACTIVE') | |
207 | ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__ |
|
211 | ipythondir= Unicode('', config_key='IPYTHONDIR') # Set to os.getcwd() in __init__ | |
208 | logstart = CBool(False, config_key='LOGSTART') |
|
212 | logstart = CBool(False, config_key='LOGSTART') | |
209 | logfile = Str('', config_key='LOGFILE') |
|
213 | logfile = Str('', config_key='LOGFILE') | |
210 | logplay = Str('', config_key='LOGPLAY') |
|
214 | logplay = Str('', config_key='LOGPLAY') | |
211 | multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS') |
|
215 | multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS') | |
212 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
216 | object_info_string_level = Enum((0,1,2), default_value=0, | |
213 | config_keys='OBJECT_INFO_STRING_LEVEL') |
|
217 | config_keys='OBJECT_INFO_STRING_LEVEL') | |
214 | pager = Str('less', config_key='PAGER') |
|
218 | pager = Str('less', config_key='PAGER') | |
215 | pdb = CBool(False, config_key='PDB') |
|
219 | pdb = CBool(False, config_key='PDB') | |
216 | pprint = CBool(True, config_key='PPRINT') |
|
220 | pprint = CBool(True, config_key='PPRINT') | |
217 | profile = Str('', config_key='PROFILE') |
|
221 | profile = Str('', config_key='PROFILE') | |
218 | prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1') |
|
222 | prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1') | |
219 | prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2') |
|
223 | prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2') | |
220 | prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1') |
|
224 | prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1') | |
221 | prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT') |
|
225 | prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT') | |
222 | quiet = CBool(False, config_key='QUIET') |
|
226 | quiet = CBool(False, config_key='QUIET') | |
223 |
|
227 | |||
224 | readline_use = CBool(True, config_key='READLINE_USE') |
|
228 | readline_use = CBool(True, config_key='READLINE_USE') | |
225 | readline_merge_completions = CBool(True, |
|
229 | readline_merge_completions = CBool(True, | |
226 | config_key='READLINE_MERGE_COMPLETIONS') |
|
230 | config_key='READLINE_MERGE_COMPLETIONS') | |
227 | readline_omit__names = Enum((0,1,2), default_value=0, |
|
231 | readline_omit__names = Enum((0,1,2), default_value=0, | |
228 | config_key='READLINE_OMIT_NAMES') |
|
232 | config_key='READLINE_OMIT_NAMES') | |
229 | readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS') |
|
233 | readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS') | |
230 | readline_parse_and_bind = List([ |
|
234 | readline_parse_and_bind = List([ | |
231 | 'tab: complete', |
|
235 | 'tab: complete', | |
232 | '"\C-l": possible-completions', |
|
236 | '"\C-l": possible-completions', | |
233 | 'set show-all-if-ambiguous on', |
|
237 | 'set show-all-if-ambiguous on', | |
234 | '"\C-o": tab-insert', |
|
238 | '"\C-o": tab-insert', | |
235 | '"\M-i": " "', |
|
239 | '"\M-i": " "', | |
236 | '"\M-o": "\d\d\d\d"', |
|
240 | '"\M-o": "\d\d\d\d"', | |
237 | '"\M-I": "\d\d\d\d"', |
|
241 | '"\M-I": "\d\d\d\d"', | |
238 | '"\C-r": reverse-search-history', |
|
242 | '"\C-r": reverse-search-history', | |
239 | '"\C-s": forward-search-history', |
|
243 | '"\C-s": forward-search-history', | |
240 | '"\C-p": history-search-backward', |
|
244 | '"\C-p": history-search-backward', | |
241 | '"\C-n": history-search-forward', |
|
245 | '"\C-n": history-search-forward', | |
242 | '"\e[A": history-search-backward', |
|
246 | '"\e[A": history-search-backward', | |
243 | '"\e[B": history-search-forward', |
|
247 | '"\e[B": history-search-forward', | |
244 | '"\C-k": kill-line', |
|
248 | '"\C-k": kill-line', | |
245 | '"\C-u": unix-line-discard', |
|
249 | '"\C-u": unix-line-discard', | |
246 | ], allow_none=False, config_key='READLINE_PARSE_AND_BIND' |
|
250 | ], allow_none=False, config_key='READLINE_PARSE_AND_BIND' | |
247 | ) |
|
251 | ) | |
248 |
|
252 | |||
249 | screen_length = Int(0, config_key='SCREEN_LENGTH') |
|
253 | screen_length = Int(0, config_key='SCREEN_LENGTH') | |
250 |
|
254 | |||
251 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' |
|
255 | # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n' | |
252 | separate_in = SeparateStr('\n', config_key='SEPARATE_IN') |
|
256 | separate_in = SeparateStr('\n', config_key='SEPARATE_IN') | |
253 | separate_out = SeparateStr('', config_key='SEPARATE_OUT') |
|
257 | separate_out = SeparateStr('', config_key='SEPARATE_OUT') | |
254 | separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2') |
|
258 | separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2') | |
255 |
|
259 | |||
256 | system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER') |
|
260 | system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER') | |
257 | system_verbose = CBool(False, config_key='SYSTEM_VERBOSE') |
|
261 | system_verbose = CBool(False, config_key='SYSTEM_VERBOSE') | |
258 | term_title = CBool(False, config_key='TERM_TITLE') |
|
262 | term_title = CBool(False, config_key='TERM_TITLE') | |
259 | wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE') |
|
263 | wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE') | |
260 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
264 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
261 | default_value='Context', config_key='XMODE') |
|
265 | default_value='Context', config_key='XMODE') | |
262 |
|
266 | |||
263 | alias = List(allow_none=False, config_key='ALIAS') |
|
267 | alias = List(allow_none=False, config_key='ALIAS') | |
264 | autoexec = List(allow_none=False) |
|
268 | autoexec = List(allow_none=False) | |
265 |
|
269 | |||
266 | # class attribute to indicate whether the class supports threads or not. |
|
270 | # class attribute to indicate whether the class supports threads or not. | |
267 | # Subclasses with thread support should override this as needed. |
|
271 | # Subclasses with thread support should override this as needed. | |
268 | isthreaded = False |
|
272 | isthreaded = False | |
269 |
|
273 | |||
270 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
274 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, | |
271 | user_ns=None, user_global_ns=None, |
|
275 | user_ns=None, user_global_ns=None, | |
272 | banner1=None, banner2=None, |
|
276 | banner1=None, banner2=None, | |
273 | custom_exceptions=((),None)): |
|
277 | custom_exceptions=((),None)): | |
274 |
|
278 | |||
275 | # This is where traitlets with a config_key argument are updated |
|
279 | # This is where traitlets with a config_key argument are updated | |
276 | # from the values on config. |
|
280 | # from the values on config. | |
277 | super(InteractiveShell, self).__init__(parent, config=config, name='__IP') |
|
281 | super(InteractiveShell, self).__init__(parent, config=config, name='__IP') | |
278 |
|
282 | |||
279 | # These are relatively independent and stateless |
|
283 | # These are relatively independent and stateless | |
280 | self.init_ipythondir(ipythondir) |
|
284 | self.init_ipythondir(ipythondir) | |
281 | self.init_instance_attrs() |
|
285 | self.init_instance_attrs() | |
282 | self.init_term_title() |
|
286 | self.init_term_title() | |
283 | self.init_usage(usage) |
|
287 | self.init_usage(usage) | |
284 | self.init_banner(banner1, banner2) |
|
288 | self.init_banner(banner1, banner2) | |
285 |
|
289 | |||
286 | # Create namespaces (user_ns, user_global_ns, alias_table, etc.) |
|
290 | # Create namespaces (user_ns, user_global_ns, alias_table, etc.) | |
287 | self.init_create_namespaces(user_ns, user_global_ns) |
|
291 | self.init_create_namespaces(user_ns, user_global_ns) | |
288 | # This has to be done after init_create_namespaces because it uses |
|
292 | # This has to be done after init_create_namespaces because it uses | |
289 | # something in self.user_ns, but before init_sys_modules, which |
|
293 | # something in self.user_ns, but before init_sys_modules, which | |
290 | # is the first thing to modify sys. |
|
294 | # is the first thing to modify sys. | |
291 | self.save_sys_module_state() |
|
295 | self.save_sys_module_state() | |
292 | self.init_sys_modules() |
|
296 | self.init_sys_modules() | |
293 |
|
297 | |||
294 | self.init_history() |
|
298 | self.init_history() | |
295 | self.init_encoding() |
|
299 | self.init_encoding() | |
296 | self.init_handlers() |
|
300 | self.init_handlers() | |
297 |
|
301 | |||
298 | Magic.__init__(self, self) |
|
302 | Magic.__init__(self, self) | |
299 |
|
303 | |||
300 | self.init_syntax_highlighting() |
|
304 | self.init_syntax_highlighting() | |
301 | self.init_hooks() |
|
305 | self.init_hooks() | |
302 | self.init_pushd_popd_magic() |
|
306 | self.init_pushd_popd_magic() | |
303 | self.init_traceback_handlers(custom_exceptions) |
|
307 | self.init_traceback_handlers(custom_exceptions) | |
304 | self.init_user_ns() |
|
308 | self.init_user_ns() | |
305 | self.init_logger() |
|
309 | self.init_logger() | |
306 |
self.init_alias |
|
310 | self.init_alias() | |
307 | self.init_builtins() |
|
311 | self.init_builtins() | |
308 |
|
312 | |||
309 | # pre_config_initialization |
|
313 | # pre_config_initialization | |
310 | self.init_shadow_hist() |
|
314 | self.init_shadow_hist() | |
311 |
|
315 | |||
312 | # The next section should contain averything that was in ipmaker. |
|
316 | # The next section should contain averything that was in ipmaker. | |
313 | self.init_logstart() |
|
317 | self.init_logstart() | |
314 |
|
318 | |||
315 | # The following was in post_config_initialization |
|
319 | # The following was in post_config_initialization | |
316 | self.init_inspector() |
|
320 | self.init_inspector() | |
317 | self.init_readline() |
|
321 | self.init_readline() | |
318 | self.init_prompts() |
|
322 | self.init_prompts() | |
319 | self.init_displayhook() |
|
323 | self.init_displayhook() | |
320 | self.init_reload_doctest() |
|
324 | self.init_reload_doctest() | |
321 | self.init_magics() |
|
325 | self.init_magics() | |
322 | self.init_pdb() |
|
326 | self.init_pdb() | |
323 | self.hooks.late_startup_hook() |
|
327 | self.hooks.late_startup_hook() | |
324 |
|
328 | |||
325 | #------------------------------------------------------------------------- |
|
329 | #------------------------------------------------------------------------- | |
326 | # Traitlet changed handlers |
|
330 | # Traitlet changed handlers | |
327 | #------------------------------------------------------------------------- |
|
331 | #------------------------------------------------------------------------- | |
328 |
|
332 | |||
329 | def _banner1_changed(self): |
|
333 | def _banner1_changed(self): | |
330 | self.compute_banner() |
|
334 | self.compute_banner() | |
331 |
|
335 | |||
332 | def _banner2_changed(self): |
|
336 | def _banner2_changed(self): | |
333 | self.compute_banner() |
|
337 | self.compute_banner() | |
334 |
|
338 | |||
335 | @property |
|
339 | @property | |
336 | def usable_screen_length(self): |
|
340 | def usable_screen_length(self): | |
337 | if self.screen_length == 0: |
|
341 | if self.screen_length == 0: | |
338 | return 0 |
|
342 | return 0 | |
339 | else: |
|
343 | else: | |
340 | num_lines_bot = self.separate_in.count('\n')+1 |
|
344 | num_lines_bot = self.separate_in.count('\n')+1 | |
341 | return self.screen_length - num_lines_bot |
|
345 | return self.screen_length - num_lines_bot | |
342 |
|
346 | |||
343 | def _term_title_changed(self, name, new_value): |
|
347 | def _term_title_changed(self, name, new_value): | |
344 | self.init_term_title() |
|
348 | self.init_term_title() | |
345 |
|
349 | |||
346 | def set_autoindent(self,value=None): |
|
350 | def set_autoindent(self,value=None): | |
347 | """Set the autoindent flag, checking for readline support. |
|
351 | """Set the autoindent flag, checking for readline support. | |
348 |
|
352 | |||
349 | If called with no arguments, it acts as a toggle.""" |
|
353 | If called with no arguments, it acts as a toggle.""" | |
350 |
|
354 | |||
351 | if not self.has_readline: |
|
355 | if not self.has_readline: | |
352 | if os.name == 'posix': |
|
356 | if os.name == 'posix': | |
353 | warn("The auto-indent feature requires the readline library") |
|
357 | warn("The auto-indent feature requires the readline library") | |
354 | self.autoindent = 0 |
|
358 | self.autoindent = 0 | |
355 | return |
|
359 | return | |
356 | if value is None: |
|
360 | if value is None: | |
357 | self.autoindent = not self.autoindent |
|
361 | self.autoindent = not self.autoindent | |
358 | else: |
|
362 | else: | |
359 | self.autoindent = value |
|
363 | self.autoindent = value | |
360 |
|
364 | |||
361 | #------------------------------------------------------------------------- |
|
365 | #------------------------------------------------------------------------- | |
362 | # init_* methods called by __init__ |
|
366 | # init_* methods called by __init__ | |
363 | #------------------------------------------------------------------------- |
|
367 | #------------------------------------------------------------------------- | |
364 |
|
368 | |||
365 | def init_ipythondir(self, ipythondir): |
|
369 | def init_ipythondir(self, ipythondir): | |
366 | if ipythondir is not None: |
|
370 | if ipythondir is not None: | |
367 | self.ipythondir = ipythondir |
|
371 | self.ipythondir = ipythondir | |
368 | self.config.IPYTHONDIR = self.ipythondir |
|
372 | self.config.IPYTHONDIR = self.ipythondir | |
369 | return |
|
373 | return | |
370 |
|
374 | |||
371 | if hasattr(self.config, 'IPYTHONDIR'): |
|
375 | if hasattr(self.config, 'IPYTHONDIR'): | |
372 | self.ipythondir = self.config.IPYTHONDIR |
|
376 | self.ipythondir = self.config.IPYTHONDIR | |
373 | if not hasattr(self.config, 'IPYTHONDIR'): |
|
377 | if not hasattr(self.config, 'IPYTHONDIR'): | |
374 | # cdw is always defined |
|
378 | # cdw is always defined | |
375 | self.ipythondir = os.getcwd() |
|
379 | self.ipythondir = os.getcwd() | |
376 |
|
380 | |||
377 | # The caller must make sure that ipythondir exists. We should |
|
381 | # The caller must make sure that ipythondir exists. We should | |
378 | # probably handle this using a Dir traitlet. |
|
382 | # probably handle this using a Dir traitlet. | |
379 | if not os.path.isdir(self.ipythondir): |
|
383 | if not os.path.isdir(self.ipythondir): | |
380 | raise IOError('IPython dir does not exist: %s' % self.ipythondir) |
|
384 | raise IOError('IPython dir does not exist: %s' % self.ipythondir) | |
381 |
|
385 | |||
382 | # All children can just read this |
|
386 | # All children can just read this | |
383 | self.config.IPYTHONDIR = self.ipythondir |
|
387 | self.config.IPYTHONDIR = self.ipythondir | |
384 |
|
388 | |||
385 | def init_instance_attrs(self): |
|
389 | def init_instance_attrs(self): | |
386 | self.jobs = BackgroundJobManager() |
|
390 | self.jobs = BackgroundJobManager() | |
387 | self.more = False |
|
391 | self.more = False | |
388 |
|
392 | |||
389 | # command compiler |
|
393 | # command compiler | |
390 | self.compile = codeop.CommandCompiler() |
|
394 | self.compile = codeop.CommandCompiler() | |
391 |
|
395 | |||
392 | # User input buffer |
|
396 | # User input buffer | |
393 | self.buffer = [] |
|
397 | self.buffer = [] | |
394 |
|
398 | |||
395 | # Make an empty namespace, which extension writers can rely on both |
|
399 | # Make an empty namespace, which extension writers can rely on both | |
396 | # existing and NEVER being used by ipython itself. This gives them a |
|
400 | # existing and NEVER being used by ipython itself. This gives them a | |
397 | # convenient location for storing additional information and state |
|
401 | # convenient location for storing additional information and state | |
398 | # their extensions may require, without fear of collisions with other |
|
402 | # their extensions may require, without fear of collisions with other | |
399 | # ipython names that may develop later. |
|
403 | # ipython names that may develop later. | |
400 | self.meta = Struct() |
|
404 | self.meta = Struct() | |
401 |
|
405 | |||
402 | # Object variable to store code object waiting execution. This is |
|
406 | # Object variable to store code object waiting execution. This is | |
403 | # used mainly by the multithreaded shells, but it can come in handy in |
|
407 | # used mainly by the multithreaded shells, but it can come in handy in | |
404 | # other situations. No need to use a Queue here, since it's a single |
|
408 | # other situations. No need to use a Queue here, since it's a single | |
405 | # item which gets cleared once run. |
|
409 | # item which gets cleared once run. | |
406 | self.code_to_run = None |
|
410 | self.code_to_run = None | |
407 |
|
411 | |||
408 | # Flag to mark unconditional exit |
|
412 | # Flag to mark unconditional exit | |
409 | self.exit_now = False |
|
413 | self.exit_now = False | |
410 |
|
414 | |||
411 | # Temporary files used for various purposes. Deleted at exit. |
|
415 | # Temporary files used for various purposes. Deleted at exit. | |
412 | self.tempfiles = [] |
|
416 | self.tempfiles = [] | |
413 |
|
417 | |||
414 | # Keep track of readline usage (later set by init_readline) |
|
418 | # Keep track of readline usage (later set by init_readline) | |
415 | self.has_readline = False |
|
419 | self.has_readline = False | |
416 |
|
420 | |||
417 | # keep track of where we started running (mainly for crash post-mortem) |
|
421 | # keep track of where we started running (mainly for crash post-mortem) | |
418 | # This is not being used anywhere currently. |
|
422 | # This is not being used anywhere currently. | |
419 | self.starting_dir = os.getcwd() |
|
423 | self.starting_dir = os.getcwd() | |
420 |
|
424 | |||
421 | # Indentation management |
|
425 | # Indentation management | |
422 | self.indent_current_nsp = 0 |
|
426 | self.indent_current_nsp = 0 | |
423 |
|
427 | |||
424 | def init_term_title(self): |
|
428 | def init_term_title(self): | |
425 | # Enable or disable the terminal title. |
|
429 | # Enable or disable the terminal title. | |
426 | if self.term_title: |
|
430 | if self.term_title: | |
427 | toggle_set_term_title(True) |
|
431 | toggle_set_term_title(True) | |
428 | set_term_title('IPython: ' + abbrev_cwd()) |
|
432 | set_term_title('IPython: ' + abbrev_cwd()) | |
429 | else: |
|
433 | else: | |
430 | toggle_set_term_title(False) |
|
434 | toggle_set_term_title(False) | |
431 |
|
435 | |||
432 | def init_usage(self, usage=None): |
|
436 | def init_usage(self, usage=None): | |
433 | if usage is None: |
|
437 | if usage is None: | |
434 | self.usage = interactive_usage |
|
438 | self.usage = interactive_usage | |
435 | else: |
|
439 | else: | |
436 | self.usage = usage |
|
440 | self.usage = usage | |
437 |
|
441 | |||
438 | def init_banner(self, banner1, banner2): |
|
442 | def init_banner(self, banner1, banner2): | |
439 | if self.c: # regular python doesn't print the banner with -c |
|
443 | if self.c: # regular python doesn't print the banner with -c | |
440 | self.display_banner = False |
|
444 | self.display_banner = False | |
441 | if banner1 is not None: |
|
445 | if banner1 is not None: | |
442 | self.banner1 = banner1 |
|
446 | self.banner1 = banner1 | |
443 | if banner2 is not None: |
|
447 | if banner2 is not None: | |
444 | self.banner2 = banner2 |
|
448 | self.banner2 = banner2 | |
445 | self.compute_banner() |
|
449 | self.compute_banner() | |
446 |
|
450 | |||
447 | def compute_banner(self): |
|
451 | def compute_banner(self): | |
448 | self.banner = self.banner1 + '\n' |
|
452 | self.banner = self.banner1 + '\n' | |
449 | if self.profile: |
|
453 | if self.profile: | |
450 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
454 | self.banner += '\nIPython profile: %s\n' % self.profile | |
451 | if self.banner2: |
|
455 | if self.banner2: | |
452 | self.banner += '\n' + self.banner2 + '\n' |
|
456 | self.banner += '\n' + self.banner2 + '\n' | |
453 |
|
457 | |||
454 | def init_encoding(self): |
|
458 | def init_encoding(self): | |
455 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
459 | # Get system encoding at startup time. Certain terminals (like Emacs | |
456 | # under Win32 have it set to None, and we need to have a known valid |
|
460 | # under Win32 have it set to None, and we need to have a known valid | |
457 | # encoding to use in the raw_input() method |
|
461 | # encoding to use in the raw_input() method | |
458 | try: |
|
462 | try: | |
459 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
463 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
460 | except AttributeError: |
|
464 | except AttributeError: | |
461 | self.stdin_encoding = 'ascii' |
|
465 | self.stdin_encoding = 'ascii' | |
462 |
|
466 | |||
463 | def init_syntax_highlighting(self): |
|
467 | def init_syntax_highlighting(self): | |
464 | # Python source parser/formatter for syntax highlighting |
|
468 | # Python source parser/formatter for syntax highlighting | |
465 | pyformat = PyColorize.Parser().format |
|
469 | pyformat = PyColorize.Parser().format | |
466 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
470 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
467 |
|
471 | |||
468 | def init_pushd_popd_magic(self): |
|
472 | def init_pushd_popd_magic(self): | |
469 | # for pushd/popd management |
|
473 | # for pushd/popd management | |
470 | try: |
|
474 | try: | |
471 | self.home_dir = get_home_dir() |
|
475 | self.home_dir = get_home_dir() | |
472 | except HomeDirError, msg: |
|
476 | except HomeDirError, msg: | |
473 | fatal(msg) |
|
477 | fatal(msg) | |
474 |
|
478 | |||
475 | self.dir_stack = [] |
|
479 | self.dir_stack = [] | |
476 |
|
480 | |||
477 | def init_logger(self): |
|
481 | def init_logger(self): | |
478 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
482 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
479 | # local shortcut, this is used a LOT |
|
483 | # local shortcut, this is used a LOT | |
480 | self.log = self.logger.log |
|
484 | self.log = self.logger.log | |
481 | # template for logfile headers. It gets resolved at runtime by the |
|
485 | # template for logfile headers. It gets resolved at runtime by the | |
482 | # logstart method. |
|
486 | # logstart method. | |
483 | self.loghead_tpl = \ |
|
487 | self.loghead_tpl = \ | |
484 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** |
|
488 | """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** | |
485 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW |
|
489 | #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW | |
486 | #log# opts = %s |
|
490 | #log# opts = %s | |
487 | #log# args = %s |
|
491 | #log# args = %s | |
488 | #log# It is safe to make manual edits below here. |
|
492 | #log# It is safe to make manual edits below here. | |
489 | #log#----------------------------------------------------------------------- |
|
493 | #log#----------------------------------------------------------------------- | |
490 | """ |
|
494 | """ | |
491 |
|
495 | |||
492 | def init_logstart(self): |
|
496 | def init_logstart(self): | |
493 | if self.logplay: |
|
497 | if self.logplay: | |
494 | self.magic_logstart(self.logplay + ' append') |
|
498 | self.magic_logstart(self.logplay + ' append') | |
495 | elif self.logfile: |
|
499 | elif self.logfile: | |
496 | self.magic_logstart(self.logfile) |
|
500 | self.magic_logstart(self.logfile) | |
497 | elif self.logstart: |
|
501 | elif self.logstart: | |
498 | self.magic_logstart() |
|
502 | self.magic_logstart() | |
499 |
|
503 | |||
500 | def init_builtins(self): |
|
504 | def init_builtins(self): | |
501 | self.builtin_trap = BuiltinTrap(self) |
|
505 | self.builtin_trap = BuiltinTrap(self) | |
502 |
|
506 | |||
503 | def init_inspector(self): |
|
507 | def init_inspector(self): | |
504 | # Object inspector |
|
508 | # Object inspector | |
505 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
509 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
506 | PyColorize.ANSICodeColors, |
|
510 | PyColorize.ANSICodeColors, | |
507 | 'NoColor', |
|
511 | 'NoColor', | |
508 | self.object_info_string_level) |
|
512 | self.object_info_string_level) | |
509 |
|
513 | |||
510 | def init_prompts(self): |
|
514 | def init_prompts(self): | |
511 | # Initialize cache, set in/out prompts and printing system |
|
515 | # Initialize cache, set in/out prompts and printing system | |
512 | self.outputcache = CachedOutput(self, |
|
516 | self.outputcache = CachedOutput(self, | |
513 | self.cache_size, |
|
517 | self.cache_size, | |
514 | self.pprint, |
|
518 | self.pprint, | |
515 | input_sep = self.separate_in, |
|
519 | input_sep = self.separate_in, | |
516 | output_sep = self.separate_out, |
|
520 | output_sep = self.separate_out, | |
517 | output_sep2 = self.separate_out2, |
|
521 | output_sep2 = self.separate_out2, | |
518 | ps1 = self.prompt_in1, |
|
522 | ps1 = self.prompt_in1, | |
519 | ps2 = self.prompt_in2, |
|
523 | ps2 = self.prompt_in2, | |
520 | ps_out = self.prompt_out, |
|
524 | ps_out = self.prompt_out, | |
521 | pad_left = self.prompts_pad_left) |
|
525 | pad_left = self.prompts_pad_left) | |
522 |
|
526 | |||
523 | # user may have over-ridden the default print hook: |
|
527 | # user may have over-ridden the default print hook: | |
524 | try: |
|
528 | try: | |
525 | self.outputcache.__class__.display = self.hooks.display |
|
529 | self.outputcache.__class__.display = self.hooks.display | |
526 | except AttributeError: |
|
530 | except AttributeError: | |
527 | pass |
|
531 | pass | |
528 |
|
532 | |||
529 | def init_displayhook(self): |
|
533 | def init_displayhook(self): | |
530 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
534 | self.display_trap = DisplayTrap(self, self.outputcache) | |
531 |
|
535 | |||
532 | def init_reload_doctest(self): |
|
536 | def init_reload_doctest(self): | |
533 | # Do a proper resetting of doctest, including the necessary displayhook |
|
537 | # Do a proper resetting of doctest, including the necessary displayhook | |
534 | # monkeypatching |
|
538 | # monkeypatching | |
535 | try: |
|
539 | try: | |
536 | doctest_reload() |
|
540 | doctest_reload() | |
537 | except ImportError: |
|
541 | except ImportError: | |
538 | warn("doctest module does not exist.") |
|
542 | warn("doctest module does not exist.") | |
539 |
|
543 | |||
540 | #------------------------------------------------------------------------- |
|
544 | #------------------------------------------------------------------------- | |
541 | # Things related to injections into the sys module |
|
545 | # Things related to injections into the sys module | |
542 | #------------------------------------------------------------------------- |
|
546 | #------------------------------------------------------------------------- | |
543 |
|
547 | |||
544 | def save_sys_module_state(self): |
|
548 | def save_sys_module_state(self): | |
545 | """Save the state of hooks in the sys module. |
|
549 | """Save the state of hooks in the sys module. | |
546 |
|
550 | |||
547 | This has to be called after self.user_ns is created. |
|
551 | This has to be called after self.user_ns is created. | |
548 | """ |
|
552 | """ | |
549 | self._orig_sys_module_state = {} |
|
553 | self._orig_sys_module_state = {} | |
550 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
554 | self._orig_sys_module_state['stdin'] = sys.stdin | |
551 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
555 | self._orig_sys_module_state['stdout'] = sys.stdout | |
552 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
556 | self._orig_sys_module_state['stderr'] = sys.stderr | |
553 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
557 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
554 | try: |
|
558 | try: | |
555 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
559 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
556 | except KeyError: |
|
560 | except KeyError: | |
557 | pass |
|
561 | pass | |
558 |
|
562 | |||
559 | def restore_sys_module_state(self): |
|
563 | def restore_sys_module_state(self): | |
560 | """Restore the state of the sys module.""" |
|
564 | """Restore the state of the sys module.""" | |
561 | try: |
|
565 | try: | |
562 | for k, v in self._orig_sys_module_state.items(): |
|
566 | for k, v in self._orig_sys_module_state.items(): | |
563 | setattr(sys, k, v) |
|
567 | setattr(sys, k, v) | |
564 | except AttributeError: |
|
568 | except AttributeError: | |
565 | pass |
|
569 | pass | |
566 | try: |
|
570 | try: | |
567 | delattr(sys, 'ipcompleter') |
|
571 | delattr(sys, 'ipcompleter') | |
568 | except AttributeError: |
|
572 | except AttributeError: | |
569 | pass |
|
573 | pass | |
570 | # Reset what what done in self.init_sys_modules |
|
574 | # Reset what what done in self.init_sys_modules | |
571 | try: |
|
575 | try: | |
572 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
576 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
573 | except (AttributeError, KeyError): |
|
577 | except (AttributeError, KeyError): | |
574 | pass |
|
578 | pass | |
575 |
|
579 | |||
576 | #------------------------------------------------------------------------- |
|
580 | #------------------------------------------------------------------------- | |
577 | # Things related to hooks |
|
581 | # Things related to hooks | |
578 | #------------------------------------------------------------------------- |
|
582 | #------------------------------------------------------------------------- | |
579 |
|
583 | |||
580 | def init_hooks(self): |
|
584 | def init_hooks(self): | |
581 | # hooks holds pointers used for user-side customizations |
|
585 | # hooks holds pointers used for user-side customizations | |
582 | self.hooks = Struct() |
|
586 | self.hooks = Struct() | |
583 |
|
587 | |||
584 | self.strdispatchers = {} |
|
588 | self.strdispatchers = {} | |
585 |
|
589 | |||
586 | # Set all default hooks, defined in the IPython.hooks module. |
|
590 | # Set all default hooks, defined in the IPython.hooks module. | |
587 | import IPython.core.hooks |
|
591 | import IPython.core.hooks | |
588 | hooks = IPython.core.hooks |
|
592 | hooks = IPython.core.hooks | |
589 | for hook_name in hooks.__all__: |
|
593 | for hook_name in hooks.__all__: | |
590 | # default hooks have priority 100, i.e. low; user hooks should have |
|
594 | # default hooks have priority 100, i.e. low; user hooks should have | |
591 | # 0-100 priority |
|
595 | # 0-100 priority | |
592 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
596 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
593 |
|
597 | |||
594 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
598 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
595 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
599 | """set_hook(name,hook) -> sets an internal IPython hook. | |
596 |
|
600 | |||
597 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
601 | IPython exposes some of its internal API as user-modifiable hooks. By | |
598 | adding your function to one of these hooks, you can modify IPython's |
|
602 | adding your function to one of these hooks, you can modify IPython's | |
599 | behavior to call at runtime your own routines.""" |
|
603 | behavior to call at runtime your own routines.""" | |
600 |
|
604 | |||
601 | # At some point in the future, this should validate the hook before it |
|
605 | # At some point in the future, this should validate the hook before it | |
602 | # accepts it. Probably at least check that the hook takes the number |
|
606 | # accepts it. Probably at least check that the hook takes the number | |
603 | # of args it's supposed to. |
|
607 | # of args it's supposed to. | |
604 |
|
608 | |||
605 | f = new.instancemethod(hook,self,self.__class__) |
|
609 | f = new.instancemethod(hook,self,self.__class__) | |
606 |
|
610 | |||
607 | # check if the hook is for strdispatcher first |
|
611 | # check if the hook is for strdispatcher first | |
608 | if str_key is not None: |
|
612 | if str_key is not None: | |
609 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
613 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
610 | sdp.add_s(str_key, f, priority ) |
|
614 | sdp.add_s(str_key, f, priority ) | |
611 | self.strdispatchers[name] = sdp |
|
615 | self.strdispatchers[name] = sdp | |
612 | return |
|
616 | return | |
613 | if re_key is not None: |
|
617 | if re_key is not None: | |
614 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
618 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
615 | sdp.add_re(re.compile(re_key), f, priority ) |
|
619 | sdp.add_re(re.compile(re_key), f, priority ) | |
616 | self.strdispatchers[name] = sdp |
|
620 | self.strdispatchers[name] = sdp | |
617 | return |
|
621 | return | |
618 |
|
622 | |||
619 | dp = getattr(self.hooks, name, None) |
|
623 | dp = getattr(self.hooks, name, None) | |
620 | if name not in IPython.core.hooks.__all__: |
|
624 | if name not in IPython.core.hooks.__all__: | |
621 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
625 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
622 | if not dp: |
|
626 | if not dp: | |
623 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
627 | dp = IPython.core.hooks.CommandChainDispatcher() | |
624 |
|
628 | |||
625 | try: |
|
629 | try: | |
626 | dp.add(f,priority) |
|
630 | dp.add(f,priority) | |
627 | except AttributeError: |
|
631 | except AttributeError: | |
628 | # it was not commandchain, plain old func - replace |
|
632 | # it was not commandchain, plain old func - replace | |
629 | dp = f |
|
633 | dp = f | |
630 |
|
634 | |||
631 | setattr(self.hooks,name, dp) |
|
635 | setattr(self.hooks,name, dp) | |
632 |
|
636 | |||
633 | #------------------------------------------------------------------------- |
|
637 | #------------------------------------------------------------------------- | |
634 | # Things related to the "main" module |
|
638 | # Things related to the "main" module | |
635 | #------------------------------------------------------------------------- |
|
639 | #------------------------------------------------------------------------- | |
636 |
|
640 | |||
637 | def new_main_mod(self,ns=None): |
|
641 | def new_main_mod(self,ns=None): | |
638 | """Return a new 'main' module object for user code execution. |
|
642 | """Return a new 'main' module object for user code execution. | |
639 | """ |
|
643 | """ | |
640 | main_mod = self._user_main_module |
|
644 | main_mod = self._user_main_module | |
641 | init_fakemod_dict(main_mod,ns) |
|
645 | init_fakemod_dict(main_mod,ns) | |
642 | return main_mod |
|
646 | return main_mod | |
643 |
|
647 | |||
644 | def cache_main_mod(self,ns,fname): |
|
648 | def cache_main_mod(self,ns,fname): | |
645 | """Cache a main module's namespace. |
|
649 | """Cache a main module's namespace. | |
646 |
|
650 | |||
647 | When scripts are executed via %run, we must keep a reference to the |
|
651 | When scripts are executed via %run, we must keep a reference to the | |
648 | namespace of their __main__ module (a FakeModule instance) around so |
|
652 | namespace of their __main__ module (a FakeModule instance) around so | |
649 | that Python doesn't clear it, rendering objects defined therein |
|
653 | that Python doesn't clear it, rendering objects defined therein | |
650 | useless. |
|
654 | useless. | |
651 |
|
655 | |||
652 | This method keeps said reference in a private dict, keyed by the |
|
656 | This method keeps said reference in a private dict, keyed by the | |
653 | absolute path of the module object (which corresponds to the script |
|
657 | absolute path of the module object (which corresponds to the script | |
654 | path). This way, for multiple executions of the same script we only |
|
658 | path). This way, for multiple executions of the same script we only | |
655 | keep one copy of the namespace (the last one), thus preventing memory |
|
659 | keep one copy of the namespace (the last one), thus preventing memory | |
656 | leaks from old references while allowing the objects from the last |
|
660 | leaks from old references while allowing the objects from the last | |
657 | execution to be accessible. |
|
661 | execution to be accessible. | |
658 |
|
662 | |||
659 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
663 | Note: we can not allow the actual FakeModule instances to be deleted, | |
660 | because of how Python tears down modules (it hard-sets all their |
|
664 | because of how Python tears down modules (it hard-sets all their | |
661 | references to None without regard for reference counts). This method |
|
665 | references to None without regard for reference counts). This method | |
662 | must therefore make a *copy* of the given namespace, to allow the |
|
666 | must therefore make a *copy* of the given namespace, to allow the | |
663 | original module's __dict__ to be cleared and reused. |
|
667 | original module's __dict__ to be cleared and reused. | |
664 |
|
668 | |||
665 |
|
669 | |||
666 | Parameters |
|
670 | Parameters | |
667 | ---------- |
|
671 | ---------- | |
668 | ns : a namespace (a dict, typically) |
|
672 | ns : a namespace (a dict, typically) | |
669 |
|
673 | |||
670 | fname : str |
|
674 | fname : str | |
671 | Filename associated with the namespace. |
|
675 | Filename associated with the namespace. | |
672 |
|
676 | |||
673 | Examples |
|
677 | Examples | |
674 | -------- |
|
678 | -------- | |
675 |
|
679 | |||
676 | In [10]: import IPython |
|
680 | In [10]: import IPython | |
677 |
|
681 | |||
678 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
682 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
679 |
|
683 | |||
680 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
684 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
681 | Out[12]: True |
|
685 | Out[12]: True | |
682 | """ |
|
686 | """ | |
683 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
687 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
684 |
|
688 | |||
685 | def clear_main_mod_cache(self): |
|
689 | def clear_main_mod_cache(self): | |
686 | """Clear the cache of main modules. |
|
690 | """Clear the cache of main modules. | |
687 |
|
691 | |||
688 | Mainly for use by utilities like %reset. |
|
692 | Mainly for use by utilities like %reset. | |
689 |
|
693 | |||
690 | Examples |
|
694 | Examples | |
691 | -------- |
|
695 | -------- | |
692 |
|
696 | |||
693 | In [15]: import IPython |
|
697 | In [15]: import IPython | |
694 |
|
698 | |||
695 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
699 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
696 |
|
700 | |||
697 | In [17]: len(_ip._main_ns_cache) > 0 |
|
701 | In [17]: len(_ip._main_ns_cache) > 0 | |
698 | Out[17]: True |
|
702 | Out[17]: True | |
699 |
|
703 | |||
700 | In [18]: _ip.clear_main_mod_cache() |
|
704 | In [18]: _ip.clear_main_mod_cache() | |
701 |
|
705 | |||
702 | In [19]: len(_ip._main_ns_cache) == 0 |
|
706 | In [19]: len(_ip._main_ns_cache) == 0 | |
703 | Out[19]: True |
|
707 | Out[19]: True | |
704 | """ |
|
708 | """ | |
705 | self._main_ns_cache.clear() |
|
709 | self._main_ns_cache.clear() | |
706 |
|
710 | |||
707 | #------------------------------------------------------------------------- |
|
711 | #------------------------------------------------------------------------- | |
708 | # Things related to debugging |
|
712 | # Things related to debugging | |
709 | #------------------------------------------------------------------------- |
|
713 | #------------------------------------------------------------------------- | |
710 |
|
714 | |||
711 | def init_pdb(self): |
|
715 | def init_pdb(self): | |
712 | # Set calling of pdb on exceptions |
|
716 | # Set calling of pdb on exceptions | |
713 | # self.call_pdb is a property |
|
717 | # self.call_pdb is a property | |
714 | self.call_pdb = self.pdb |
|
718 | self.call_pdb = self.pdb | |
715 |
|
719 | |||
716 | def _get_call_pdb(self): |
|
720 | def _get_call_pdb(self): | |
717 | return self._call_pdb |
|
721 | return self._call_pdb | |
718 |
|
722 | |||
719 | def _set_call_pdb(self,val): |
|
723 | def _set_call_pdb(self,val): | |
720 |
|
724 | |||
721 | if val not in (0,1,False,True): |
|
725 | if val not in (0,1,False,True): | |
722 | raise ValueError,'new call_pdb value must be boolean' |
|
726 | raise ValueError,'new call_pdb value must be boolean' | |
723 |
|
727 | |||
724 | # store value in instance |
|
728 | # store value in instance | |
725 | self._call_pdb = val |
|
729 | self._call_pdb = val | |
726 |
|
730 | |||
727 | # notify the actual exception handlers |
|
731 | # notify the actual exception handlers | |
728 | self.InteractiveTB.call_pdb = val |
|
732 | self.InteractiveTB.call_pdb = val | |
729 | if self.isthreaded: |
|
733 | if self.isthreaded: | |
730 | try: |
|
734 | try: | |
731 | self.sys_excepthook.call_pdb = val |
|
735 | self.sys_excepthook.call_pdb = val | |
732 | except: |
|
736 | except: | |
733 | warn('Failed to activate pdb for threaded exception handler') |
|
737 | warn('Failed to activate pdb for threaded exception handler') | |
734 |
|
738 | |||
735 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
739 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
736 | 'Control auto-activation of pdb at exceptions') |
|
740 | 'Control auto-activation of pdb at exceptions') | |
737 |
|
741 | |||
738 | def debugger(self,force=False): |
|
742 | def debugger(self,force=False): | |
739 | """Call the pydb/pdb debugger. |
|
743 | """Call the pydb/pdb debugger. | |
740 |
|
744 | |||
741 | Keywords: |
|
745 | Keywords: | |
742 |
|
746 | |||
743 | - force(False): by default, this routine checks the instance call_pdb |
|
747 | - force(False): by default, this routine checks the instance call_pdb | |
744 | flag and does not actually invoke the debugger if the flag is false. |
|
748 | flag and does not actually invoke the debugger if the flag is false. | |
745 | The 'force' option forces the debugger to activate even if the flag |
|
749 | The 'force' option forces the debugger to activate even if the flag | |
746 | is false. |
|
750 | is false. | |
747 | """ |
|
751 | """ | |
748 |
|
752 | |||
749 | if not (force or self.call_pdb): |
|
753 | if not (force or self.call_pdb): | |
750 | return |
|
754 | return | |
751 |
|
755 | |||
752 | if not hasattr(sys,'last_traceback'): |
|
756 | if not hasattr(sys,'last_traceback'): | |
753 | error('No traceback has been produced, nothing to debug.') |
|
757 | error('No traceback has been produced, nothing to debug.') | |
754 | return |
|
758 | return | |
755 |
|
759 | |||
756 | # use pydb if available |
|
760 | # use pydb if available | |
757 | if debugger.has_pydb: |
|
761 | if debugger.has_pydb: | |
758 | from pydb import pm |
|
762 | from pydb import pm | |
759 | else: |
|
763 | else: | |
760 | # fallback to our internal debugger |
|
764 | # fallback to our internal debugger | |
761 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
765 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
762 | self.history_saving_wrapper(pm)() |
|
766 | self.history_saving_wrapper(pm)() | |
763 |
|
767 | |||
764 | #------------------------------------------------------------------------- |
|
768 | #------------------------------------------------------------------------- | |
765 | # Things related to IPython's various namespaces |
|
769 | # Things related to IPython's various namespaces | |
766 | #------------------------------------------------------------------------- |
|
770 | #------------------------------------------------------------------------- | |
767 |
|
771 | |||
768 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
772 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
769 | # Create the namespace where the user will operate. user_ns is |
|
773 | # Create the namespace where the user will operate. user_ns is | |
770 | # normally the only one used, and it is passed to the exec calls as |
|
774 | # normally the only one used, and it is passed to the exec calls as | |
771 | # the locals argument. But we do carry a user_global_ns namespace |
|
775 | # the locals argument. But we do carry a user_global_ns namespace | |
772 | # given as the exec 'globals' argument, This is useful in embedding |
|
776 | # given as the exec 'globals' argument, This is useful in embedding | |
773 | # situations where the ipython shell opens in a context where the |
|
777 | # situations where the ipython shell opens in a context where the | |
774 | # distinction between locals and globals is meaningful. For |
|
778 | # distinction between locals and globals is meaningful. For | |
775 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
779 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
776 |
|
780 | |||
777 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
781 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
778 | # level as a dict instead of a module. This is a manual fix, but I |
|
782 | # level as a dict instead of a module. This is a manual fix, but I | |
779 | # should really track down where the problem is coming from. Alex |
|
783 | # should really track down where the problem is coming from. Alex | |
780 | # Schmolck reported this problem first. |
|
784 | # Schmolck reported this problem first. | |
781 |
|
785 | |||
782 | # A useful post by Alex Martelli on this topic: |
|
786 | # A useful post by Alex Martelli on this topic: | |
783 | # Re: inconsistent value from __builtins__ |
|
787 | # Re: inconsistent value from __builtins__ | |
784 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
788 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
785 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
789 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
786 | # Gruppen: comp.lang.python |
|
790 | # Gruppen: comp.lang.python | |
787 |
|
791 | |||
788 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
792 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
789 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
793 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
790 | # > <type 'dict'> |
|
794 | # > <type 'dict'> | |
791 | # > >>> print type(__builtins__) |
|
795 | # > >>> print type(__builtins__) | |
792 | # > <type 'module'> |
|
796 | # > <type 'module'> | |
793 | # > Is this difference in return value intentional? |
|
797 | # > Is this difference in return value intentional? | |
794 |
|
798 | |||
795 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
799 | # Well, it's documented that '__builtins__' can be either a dictionary | |
796 | # or a module, and it's been that way for a long time. Whether it's |
|
800 | # or a module, and it's been that way for a long time. Whether it's | |
797 | # intentional (or sensible), I don't know. In any case, the idea is |
|
801 | # intentional (or sensible), I don't know. In any case, the idea is | |
798 | # that if you need to access the built-in namespace directly, you |
|
802 | # that if you need to access the built-in namespace directly, you | |
799 | # should start with "import __builtin__" (note, no 's') which will |
|
803 | # should start with "import __builtin__" (note, no 's') which will | |
800 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
804 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
801 |
|
805 | |||
802 | # These routines return properly built dicts as needed by the rest of |
|
806 | # These routines return properly built dicts as needed by the rest of | |
803 | # the code, and can also be used by extension writers to generate |
|
807 | # the code, and can also be used by extension writers to generate | |
804 | # properly initialized namespaces. |
|
808 | # properly initialized namespaces. | |
805 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
809 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
806 | user_global_ns) |
|
810 | user_global_ns) | |
807 |
|
811 | |||
808 | # Assign namespaces |
|
812 | # Assign namespaces | |
809 | # This is the namespace where all normal user variables live |
|
813 | # This is the namespace where all normal user variables live | |
810 | self.user_ns = user_ns |
|
814 | self.user_ns = user_ns | |
811 | self.user_global_ns = user_global_ns |
|
815 | self.user_global_ns = user_global_ns | |
812 |
|
816 | |||
813 | # An auxiliary namespace that checks what parts of the user_ns were |
|
817 | # An auxiliary namespace that checks what parts of the user_ns were | |
814 | # loaded at startup, so we can list later only variables defined in |
|
818 | # loaded at startup, so we can list later only variables defined in | |
815 | # actual interactive use. Since it is always a subset of user_ns, it |
|
819 | # actual interactive use. Since it is always a subset of user_ns, it | |
816 | # doesn't need to be seaparately tracked in the ns_table |
|
820 | # doesn't need to be seaparately tracked in the ns_table | |
817 | self.user_config_ns = {} |
|
821 | self.user_config_ns = {} | |
818 |
|
822 | |||
819 | # A namespace to keep track of internal data structures to prevent |
|
823 | # A namespace to keep track of internal data structures to prevent | |
820 | # them from cluttering user-visible stuff. Will be updated later |
|
824 | # them from cluttering user-visible stuff. Will be updated later | |
821 | self.internal_ns = {} |
|
825 | self.internal_ns = {} | |
822 |
|
826 | |||
823 | # Namespace of system aliases. Each entry in the alias |
|
827 | # Namespace of system aliases. Each entry in the alias | |
824 | # table must be a 2-tuple of the form (N,name), where N is the number |
|
828 | # table must be a 2-tuple of the form (N,name), where N is the number | |
825 | # of positional arguments of the alias. |
|
829 | # of positional arguments of the alias. | |
826 | self.alias_table = {} |
|
830 | self.alias_table = {} | |
827 |
|
831 | |||
828 | # Now that FakeModule produces a real module, we've run into a nasty |
|
832 | # Now that FakeModule produces a real module, we've run into a nasty | |
829 | # problem: after script execution (via %run), the module where the user |
|
833 | # problem: after script execution (via %run), the module where the user | |
830 | # code ran is deleted. Now that this object is a true module (needed |
|
834 | # code ran is deleted. Now that this object is a true module (needed | |
831 | # so docetst and other tools work correctly), the Python module |
|
835 | # so docetst and other tools work correctly), the Python module | |
832 | # teardown mechanism runs over it, and sets to None every variable |
|
836 | # teardown mechanism runs over it, and sets to None every variable | |
833 | # present in that module. Top-level references to objects from the |
|
837 | # present in that module. Top-level references to objects from the | |
834 | # script survive, because the user_ns is updated with them. However, |
|
838 | # script survive, because the user_ns is updated with them. However, | |
835 | # calling functions defined in the script that use other things from |
|
839 | # calling functions defined in the script that use other things from | |
836 | # the script will fail, because the function's closure had references |
|
840 | # the script will fail, because the function's closure had references | |
837 | # to the original objects, which are now all None. So we must protect |
|
841 | # to the original objects, which are now all None. So we must protect | |
838 | # these modules from deletion by keeping a cache. |
|
842 | # these modules from deletion by keeping a cache. | |
839 | # |
|
843 | # | |
840 | # To avoid keeping stale modules around (we only need the one from the |
|
844 | # To avoid keeping stale modules around (we only need the one from the | |
841 | # last run), we use a dict keyed with the full path to the script, so |
|
845 | # last run), we use a dict keyed with the full path to the script, so | |
842 | # only the last version of the module is held in the cache. Note, |
|
846 | # only the last version of the module is held in the cache. Note, | |
843 | # however, that we must cache the module *namespace contents* (their |
|
847 | # however, that we must cache the module *namespace contents* (their | |
844 | # __dict__). Because if we try to cache the actual modules, old ones |
|
848 | # __dict__). Because if we try to cache the actual modules, old ones | |
845 | # (uncached) could be destroyed while still holding references (such as |
|
849 | # (uncached) could be destroyed while still holding references (such as | |
846 | # those held by GUI objects that tend to be long-lived)> |
|
850 | # those held by GUI objects that tend to be long-lived)> | |
847 | # |
|
851 | # | |
848 | # The %reset command will flush this cache. See the cache_main_mod() |
|
852 | # The %reset command will flush this cache. See the cache_main_mod() | |
849 | # and clear_main_mod_cache() methods for details on use. |
|
853 | # and clear_main_mod_cache() methods for details on use. | |
850 |
|
854 | |||
851 | # This is the cache used for 'main' namespaces |
|
855 | # This is the cache used for 'main' namespaces | |
852 | self._main_ns_cache = {} |
|
856 | self._main_ns_cache = {} | |
853 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
857 | # And this is the single instance of FakeModule whose __dict__ we keep | |
854 | # copying and clearing for reuse on each %run |
|
858 | # copying and clearing for reuse on each %run | |
855 | self._user_main_module = FakeModule() |
|
859 | self._user_main_module = FakeModule() | |
856 |
|
860 | |||
857 | # A table holding all the namespaces IPython deals with, so that |
|
861 | # A table holding all the namespaces IPython deals with, so that | |
858 | # introspection facilities can search easily. |
|
862 | # introspection facilities can search easily. | |
859 | self.ns_table = {'user':user_ns, |
|
863 | self.ns_table = {'user':user_ns, | |
860 | 'user_global':user_global_ns, |
|
864 | 'user_global':user_global_ns, | |
861 | 'alias':self.alias_table, |
|
865 | 'alias':self.alias_table, | |
862 | 'internal':self.internal_ns, |
|
866 | 'internal':self.internal_ns, | |
863 | 'builtin':__builtin__.__dict__ |
|
867 | 'builtin':__builtin__.__dict__ | |
864 | } |
|
868 | } | |
865 |
|
869 | |||
866 | # Similarly, track all namespaces where references can be held and that |
|
870 | # Similarly, track all namespaces where references can be held and that | |
867 | # we can safely clear (so it can NOT include builtin). This one can be |
|
871 | # we can safely clear (so it can NOT include builtin). This one can be | |
868 | # a simple list. |
|
872 | # a simple list. | |
869 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
873 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
870 | self.alias_table, self.internal_ns, |
|
874 | self.alias_table, self.internal_ns, | |
871 | self._main_ns_cache ] |
|
875 | self._main_ns_cache ] | |
872 |
|
876 | |||
873 | def init_sys_modules(self): |
|
877 | def init_sys_modules(self): | |
874 | # We need to insert into sys.modules something that looks like a |
|
878 | # We need to insert into sys.modules something that looks like a | |
875 | # module but which accesses the IPython namespace, for shelve and |
|
879 | # module but which accesses the IPython namespace, for shelve and | |
876 | # pickle to work interactively. Normally they rely on getting |
|
880 | # pickle to work interactively. Normally they rely on getting | |
877 | # everything out of __main__, but for embedding purposes each IPython |
|
881 | # everything out of __main__, but for embedding purposes each IPython | |
878 | # instance has its own private namespace, so we can't go shoving |
|
882 | # instance has its own private namespace, so we can't go shoving | |
879 | # everything into __main__. |
|
883 | # everything into __main__. | |
880 |
|
884 | |||
881 | # note, however, that we should only do this for non-embedded |
|
885 | # note, however, that we should only do this for non-embedded | |
882 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
886 | # ipythons, which really mimic the __main__.__dict__ with their own | |
883 | # namespace. Embedded instances, on the other hand, should not do |
|
887 | # namespace. Embedded instances, on the other hand, should not do | |
884 | # this because they need to manage the user local/global namespaces |
|
888 | # this because they need to manage the user local/global namespaces | |
885 | # only, but they live within a 'normal' __main__ (meaning, they |
|
889 | # only, but they live within a 'normal' __main__ (meaning, they | |
886 | # shouldn't overtake the execution environment of the script they're |
|
890 | # shouldn't overtake the execution environment of the script they're | |
887 | # embedded in). |
|
891 | # embedded in). | |
888 |
|
892 | |||
889 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
893 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
890 |
|
894 | |||
891 | try: |
|
895 | try: | |
892 | main_name = self.user_ns['__name__'] |
|
896 | main_name = self.user_ns['__name__'] | |
893 | except KeyError: |
|
897 | except KeyError: | |
894 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
898 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
895 | else: |
|
899 | else: | |
896 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
900 | sys.modules[main_name] = FakeModule(self.user_ns) | |
897 |
|
901 | |||
898 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
902 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
899 | """Return a valid local and global user interactive namespaces. |
|
903 | """Return a valid local and global user interactive namespaces. | |
900 |
|
904 | |||
901 | This builds a dict with the minimal information needed to operate as a |
|
905 | This builds a dict with the minimal information needed to operate as a | |
902 | valid IPython user namespace, which you can pass to the various |
|
906 | valid IPython user namespace, which you can pass to the various | |
903 | embedding classes in ipython. The default implementation returns the |
|
907 | embedding classes in ipython. The default implementation returns the | |
904 | same dict for both the locals and the globals to allow functions to |
|
908 | same dict for both the locals and the globals to allow functions to | |
905 | refer to variables in the namespace. Customized implementations can |
|
909 | refer to variables in the namespace. Customized implementations can | |
906 | return different dicts. The locals dictionary can actually be anything |
|
910 | return different dicts. The locals dictionary can actually be anything | |
907 | following the basic mapping protocol of a dict, but the globals dict |
|
911 | following the basic mapping protocol of a dict, but the globals dict | |
908 | must be a true dict, not even a subclass. It is recommended that any |
|
912 | must be a true dict, not even a subclass. It is recommended that any | |
909 | custom object for the locals namespace synchronize with the globals |
|
913 | custom object for the locals namespace synchronize with the globals | |
910 | dict somehow. |
|
914 | dict somehow. | |
911 |
|
915 | |||
912 | Raises TypeError if the provided globals namespace is not a true dict. |
|
916 | Raises TypeError if the provided globals namespace is not a true dict. | |
913 |
|
917 | |||
914 | :Parameters: |
|
918 | :Parameters: | |
915 | user_ns : dict-like, optional |
|
919 | user_ns : dict-like, optional | |
916 | The current user namespace. The items in this namespace should |
|
920 | The current user namespace. The items in this namespace should | |
917 | be included in the output. If None, an appropriate blank |
|
921 | be included in the output. If None, an appropriate blank | |
918 | namespace should be created. |
|
922 | namespace should be created. | |
919 | user_global_ns : dict, optional |
|
923 | user_global_ns : dict, optional | |
920 | The current user global namespace. The items in this namespace |
|
924 | The current user global namespace. The items in this namespace | |
921 | should be included in the output. If None, an appropriate |
|
925 | should be included in the output. If None, an appropriate | |
922 | blank namespace should be created. |
|
926 | blank namespace should be created. | |
923 |
|
927 | |||
924 | :Returns: |
|
928 | :Returns: | |
925 | A tuple pair of dictionary-like object to be used as the local namespace |
|
929 | A tuple pair of dictionary-like object to be used as the local namespace | |
926 | of the interpreter and a dict to be used as the global namespace. |
|
930 | of the interpreter and a dict to be used as the global namespace. | |
927 | """ |
|
931 | """ | |
928 |
|
932 | |||
929 | if user_ns is None: |
|
933 | if user_ns is None: | |
930 | # Set __name__ to __main__ to better match the behavior of the |
|
934 | # Set __name__ to __main__ to better match the behavior of the | |
931 | # normal interpreter. |
|
935 | # normal interpreter. | |
932 | user_ns = {'__name__' :'__main__', |
|
936 | user_ns = {'__name__' :'__main__', | |
933 | '__builtins__' : __builtin__, |
|
937 | '__builtins__' : __builtin__, | |
934 | } |
|
938 | } | |
935 | else: |
|
939 | else: | |
936 | user_ns.setdefault('__name__','__main__') |
|
940 | user_ns.setdefault('__name__','__main__') | |
937 | user_ns.setdefault('__builtins__',__builtin__) |
|
941 | user_ns.setdefault('__builtins__',__builtin__) | |
938 |
|
942 | |||
939 | if user_global_ns is None: |
|
943 | if user_global_ns is None: | |
940 | user_global_ns = user_ns |
|
944 | user_global_ns = user_ns | |
941 | if type(user_global_ns) is not dict: |
|
945 | if type(user_global_ns) is not dict: | |
942 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
946 | raise TypeError("user_global_ns must be a true dict; got %r" | |
943 | % type(user_global_ns)) |
|
947 | % type(user_global_ns)) | |
944 |
|
948 | |||
945 | return user_ns, user_global_ns |
|
949 | return user_ns, user_global_ns | |
946 |
|
950 | |||
947 | def init_user_ns(self): |
|
951 | def init_user_ns(self): | |
948 | """Initialize all user-visible namespaces to their minimum defaults. |
|
952 | """Initialize all user-visible namespaces to their minimum defaults. | |
949 |
|
953 | |||
950 | Certain history lists are also initialized here, as they effectively |
|
954 | Certain history lists are also initialized here, as they effectively | |
951 | act as user namespaces. |
|
955 | act as user namespaces. | |
952 |
|
956 | |||
953 | Notes |
|
957 | Notes | |
954 | ----- |
|
958 | ----- | |
955 | All data structures here are only filled in, they are NOT reset by this |
|
959 | All data structures here are only filled in, they are NOT reset by this | |
956 | method. If they were not empty before, data will simply be added to |
|
960 | method. If they were not empty before, data will simply be added to | |
957 | therm. |
|
961 | therm. | |
958 | """ |
|
962 | """ | |
959 | # The user namespace MUST have a pointer to the shell itself. |
|
963 | # The user namespace MUST have a pointer to the shell itself. | |
960 | self.user_ns[self.name] = self |
|
964 | self.user_ns[self.name] = self | |
961 |
|
965 | |||
962 | # Store myself as the public api!!! |
|
966 | # Store myself as the public api!!! | |
963 | self.user_ns['_ip'] = self |
|
967 | self.user_ns['_ip'] = self | |
964 |
|
968 | |||
965 | # make global variables for user access to the histories |
|
969 | # make global variables for user access to the histories | |
966 | self.user_ns['_ih'] = self.input_hist |
|
970 | self.user_ns['_ih'] = self.input_hist | |
967 | self.user_ns['_oh'] = self.output_hist |
|
971 | self.user_ns['_oh'] = self.output_hist | |
968 | self.user_ns['_dh'] = self.dir_hist |
|
972 | self.user_ns['_dh'] = self.dir_hist | |
969 |
|
973 | |||
970 | # user aliases to input and output histories |
|
974 | # user aliases to input and output histories | |
971 | self.user_ns['In'] = self.input_hist |
|
975 | self.user_ns['In'] = self.input_hist | |
972 | self.user_ns['Out'] = self.output_hist |
|
976 | self.user_ns['Out'] = self.output_hist | |
973 |
|
977 | |||
974 | self.user_ns['_sh'] = shadowns |
|
978 | self.user_ns['_sh'] = shadowns | |
975 |
|
979 | |||
976 | # Put 'help' in the user namespace |
|
980 | # Put 'help' in the user namespace | |
977 | try: |
|
981 | try: | |
978 | from site import _Helper |
|
982 | from site import _Helper | |
979 | self.user_ns['help'] = _Helper() |
|
983 | self.user_ns['help'] = _Helper() | |
980 | except ImportError: |
|
984 | except ImportError: | |
981 | warn('help() not available - check site.py') |
|
985 | warn('help() not available - check site.py') | |
982 |
|
986 | |||
983 | def reset(self): |
|
987 | def reset(self): | |
984 | """Clear all internal namespaces. |
|
988 | """Clear all internal namespaces. | |
985 |
|
989 | |||
986 | Note that this is much more aggressive than %reset, since it clears |
|
990 | Note that this is much more aggressive than %reset, since it clears | |
987 | fully all namespaces, as well as all input/output lists. |
|
991 | fully all namespaces, as well as all input/output lists. | |
988 | """ |
|
992 | """ | |
989 | for ns in self.ns_refs_table: |
|
993 | for ns in self.ns_refs_table: | |
990 | ns.clear() |
|
994 | ns.clear() | |
991 |
|
995 | |||
992 | # Clear input and output histories |
|
996 | # Clear input and output histories | |
993 | self.input_hist[:] = [] |
|
997 | self.input_hist[:] = [] | |
994 | self.input_hist_raw[:] = [] |
|
998 | self.input_hist_raw[:] = [] | |
995 | self.output_hist.clear() |
|
999 | self.output_hist.clear() | |
996 | # Restore the user namespaces to minimal usability |
|
1000 | # Restore the user namespaces to minimal usability | |
997 | self.init_user_ns() |
|
1001 | self.init_user_ns() | |
998 |
|
1002 | |||
999 | def push(self, variables, interactive=True): |
|
1003 | def push(self, variables, interactive=True): | |
1000 | """Inject a group of variables into the IPython user namespace. |
|
1004 | """Inject a group of variables into the IPython user namespace. | |
1001 |
|
1005 | |||
1002 | Parameters |
|
1006 | Parameters | |
1003 | ---------- |
|
1007 | ---------- | |
1004 | variables : dict, str or list/tuple of str |
|
1008 | variables : dict, str or list/tuple of str | |
1005 | The variables to inject into the user's namespace. If a dict, |
|
1009 | The variables to inject into the user's namespace. If a dict, | |
1006 | a simple update is done. If a str, the string is assumed to |
|
1010 | a simple update is done. If a str, the string is assumed to | |
1007 | have variable names separated by spaces. A list/tuple of str |
|
1011 | have variable names separated by spaces. A list/tuple of str | |
1008 | can also be used to give the variable names. If just the variable |
|
1012 | can also be used to give the variable names. If just the variable | |
1009 | names are give (list/tuple/str) then the variable values looked |
|
1013 | names are give (list/tuple/str) then the variable values looked | |
1010 | up in the callers frame. |
|
1014 | up in the callers frame. | |
1011 | interactive : bool |
|
1015 | interactive : bool | |
1012 | If True (default), the variables will be listed with the ``who`` |
|
1016 | If True (default), the variables will be listed with the ``who`` | |
1013 | magic. |
|
1017 | magic. | |
1014 | """ |
|
1018 | """ | |
1015 | vdict = None |
|
1019 | vdict = None | |
1016 |
|
1020 | |||
1017 | # We need a dict of name/value pairs to do namespace updates. |
|
1021 | # We need a dict of name/value pairs to do namespace updates. | |
1018 | if isinstance(variables, dict): |
|
1022 | if isinstance(variables, dict): | |
1019 | vdict = variables |
|
1023 | vdict = variables | |
1020 | elif isinstance(variables, (basestring, list, tuple)): |
|
1024 | elif isinstance(variables, (basestring, list, tuple)): | |
1021 | if isinstance(variables, basestring): |
|
1025 | if isinstance(variables, basestring): | |
1022 | vlist = variables.split() |
|
1026 | vlist = variables.split() | |
1023 | else: |
|
1027 | else: | |
1024 | vlist = variables |
|
1028 | vlist = variables | |
1025 | vdict = {} |
|
1029 | vdict = {} | |
1026 | cf = sys._getframe(1) |
|
1030 | cf = sys._getframe(1) | |
1027 | for name in vlist: |
|
1031 | for name in vlist: | |
1028 | try: |
|
1032 | try: | |
1029 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1033 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1030 | except: |
|
1034 | except: | |
1031 | print ('Could not get variable %s from %s' % |
|
1035 | print ('Could not get variable %s from %s' % | |
1032 | (name,cf.f_code.co_name)) |
|
1036 | (name,cf.f_code.co_name)) | |
1033 | else: |
|
1037 | else: | |
1034 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1038 | raise ValueError('variables must be a dict/str/list/tuple') | |
1035 |
|
1039 | |||
1036 | # Propagate variables to user namespace |
|
1040 | # Propagate variables to user namespace | |
1037 | self.user_ns.update(vdict) |
|
1041 | self.user_ns.update(vdict) | |
1038 |
|
1042 | |||
1039 | # And configure interactive visibility |
|
1043 | # And configure interactive visibility | |
1040 | config_ns = self.user_config_ns |
|
1044 | config_ns = self.user_config_ns | |
1041 | if interactive: |
|
1045 | if interactive: | |
1042 | for name, val in vdict.iteritems(): |
|
1046 | for name, val in vdict.iteritems(): | |
1043 | config_ns.pop(name, None) |
|
1047 | config_ns.pop(name, None) | |
1044 | else: |
|
1048 | else: | |
1045 | for name,val in vdict.iteritems(): |
|
1049 | for name,val in vdict.iteritems(): | |
1046 | config_ns[name] = val |
|
1050 | config_ns[name] = val | |
1047 |
|
1051 | |||
1048 | #------------------------------------------------------------------------- |
|
1052 | #------------------------------------------------------------------------- | |
1049 | # Things related to history management |
|
1053 | # Things related to history management | |
1050 | #------------------------------------------------------------------------- |
|
1054 | #------------------------------------------------------------------------- | |
1051 |
|
1055 | |||
1052 | def init_history(self): |
|
1056 | def init_history(self): | |
1053 | # List of input with multi-line handling. |
|
1057 | # List of input with multi-line handling. | |
1054 | self.input_hist = InputList() |
|
1058 | self.input_hist = InputList() | |
1055 | # This one will hold the 'raw' input history, without any |
|
1059 | # This one will hold the 'raw' input history, without any | |
1056 | # pre-processing. This will allow users to retrieve the input just as |
|
1060 | # pre-processing. This will allow users to retrieve the input just as | |
1057 | # it was exactly typed in by the user, with %hist -r. |
|
1061 | # it was exactly typed in by the user, with %hist -r. | |
1058 | self.input_hist_raw = InputList() |
|
1062 | self.input_hist_raw = InputList() | |
1059 |
|
1063 | |||
1060 | # list of visited directories |
|
1064 | # list of visited directories | |
1061 | try: |
|
1065 | try: | |
1062 | self.dir_hist = [os.getcwd()] |
|
1066 | self.dir_hist = [os.getcwd()] | |
1063 | except OSError: |
|
1067 | except OSError: | |
1064 | self.dir_hist = [] |
|
1068 | self.dir_hist = [] | |
1065 |
|
1069 | |||
1066 | # dict of output history |
|
1070 | # dict of output history | |
1067 | self.output_hist = {} |
|
1071 | self.output_hist = {} | |
1068 |
|
1072 | |||
1069 | # Now the history file |
|
1073 | # Now the history file | |
1070 | try: |
|
1074 | try: | |
1071 | histfname = 'history-%s' % self.profile |
|
1075 | histfname = 'history-%s' % self.profile | |
1072 | except AttributeError: |
|
1076 | except AttributeError: | |
1073 | histfname = 'history' |
|
1077 | histfname = 'history' | |
1074 | self.histfile = os.path.join(self.config.IPYTHONDIR, histfname) |
|
1078 | self.histfile = os.path.join(self.config.IPYTHONDIR, histfname) | |
1075 |
|
1079 | |||
1076 | # Fill the history zero entry, user counter starts at 1 |
|
1080 | # Fill the history zero entry, user counter starts at 1 | |
1077 | self.input_hist.append('\n') |
|
1081 | self.input_hist.append('\n') | |
1078 | self.input_hist_raw.append('\n') |
|
1082 | self.input_hist_raw.append('\n') | |
1079 |
|
1083 | |||
1080 | def init_shadow_hist(self): |
|
1084 | def init_shadow_hist(self): | |
1081 | try: |
|
1085 | try: | |
1082 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") |
|
1086 | self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db") | |
1083 | except exceptions.UnicodeDecodeError: |
|
1087 | except exceptions.UnicodeDecodeError: | |
1084 | print "Your ipythondir can't be decoded to unicode!" |
|
1088 | print "Your ipythondir can't be decoded to unicode!" | |
1085 | print "Please set HOME environment variable to something that" |
|
1089 | print "Please set HOME environment variable to something that" | |
1086 | print r"only has ASCII characters, e.g. c:\home" |
|
1090 | print r"only has ASCII characters, e.g. c:\home" | |
1087 | print "Now it is", self.config.IPYTHONDIR |
|
1091 | print "Now it is", self.config.IPYTHONDIR | |
1088 | sys.exit() |
|
1092 | sys.exit() | |
1089 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1093 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1090 |
|
1094 | |||
1091 | def savehist(self): |
|
1095 | def savehist(self): | |
1092 | """Save input history to a file (via readline library).""" |
|
1096 | """Save input history to a file (via readline library).""" | |
1093 |
|
1097 | |||
1094 | if not self.has_readline: |
|
1098 | if not self.has_readline: | |
1095 | return |
|
1099 | return | |
1096 |
|
1100 | |||
1097 | try: |
|
1101 | try: | |
1098 | self.readline.write_history_file(self.histfile) |
|
1102 | self.readline.write_history_file(self.histfile) | |
1099 | except: |
|
1103 | except: | |
1100 | print 'Unable to save IPython command history to file: ' + \ |
|
1104 | print 'Unable to save IPython command history to file: ' + \ | |
1101 | `self.histfile` |
|
1105 | `self.histfile` | |
1102 |
|
1106 | |||
1103 | def reloadhist(self): |
|
1107 | def reloadhist(self): | |
1104 | """Reload the input history from disk file.""" |
|
1108 | """Reload the input history from disk file.""" | |
1105 |
|
1109 | |||
1106 | if self.has_readline: |
|
1110 | if self.has_readline: | |
1107 | try: |
|
1111 | try: | |
1108 | self.readline.clear_history() |
|
1112 | self.readline.clear_history() | |
1109 | self.readline.read_history_file(self.shell.histfile) |
|
1113 | self.readline.read_history_file(self.shell.histfile) | |
1110 | except AttributeError: |
|
1114 | except AttributeError: | |
1111 | pass |
|
1115 | pass | |
1112 |
|
1116 | |||
1113 | def history_saving_wrapper(self, func): |
|
1117 | def history_saving_wrapper(self, func): | |
1114 | """ Wrap func for readline history saving |
|
1118 | """ Wrap func for readline history saving | |
1115 |
|
1119 | |||
1116 | Convert func into callable that saves & restores |
|
1120 | Convert func into callable that saves & restores | |
1117 | history around the call """ |
|
1121 | history around the call """ | |
1118 |
|
1122 | |||
1119 | if not self.has_readline: |
|
1123 | if not self.has_readline: | |
1120 | return func |
|
1124 | return func | |
1121 |
|
1125 | |||
1122 | def wrapper(): |
|
1126 | def wrapper(): | |
1123 | self.savehist() |
|
1127 | self.savehist() | |
1124 | try: |
|
1128 | try: | |
1125 | func() |
|
1129 | func() | |
1126 | finally: |
|
1130 | finally: | |
1127 | readline.read_history_file(self.histfile) |
|
1131 | readline.read_history_file(self.histfile) | |
1128 | return wrapper |
|
1132 | return wrapper | |
1129 |
|
1133 | |||
1130 | #------------------------------------------------------------------------- |
|
1134 | #------------------------------------------------------------------------- | |
1131 | # Things related to exception handling and tracebacks (not debugging) |
|
1135 | # Things related to exception handling and tracebacks (not debugging) | |
1132 | #------------------------------------------------------------------------- |
|
1136 | #------------------------------------------------------------------------- | |
1133 |
|
1137 | |||
1134 | def init_traceback_handlers(self, custom_exceptions): |
|
1138 | def init_traceback_handlers(self, custom_exceptions): | |
1135 | # Syntax error handler. |
|
1139 | # Syntax error handler. | |
1136 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1140 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
1137 |
|
1141 | |||
1138 | # The interactive one is initialized with an offset, meaning we always |
|
1142 | # The interactive one is initialized with an offset, meaning we always | |
1139 | # want to remove the topmost item in the traceback, which is our own |
|
1143 | # want to remove the topmost item in the traceback, which is our own | |
1140 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1144 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1141 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1145 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1142 | color_scheme='NoColor', |
|
1146 | color_scheme='NoColor', | |
1143 | tb_offset = 1) |
|
1147 | tb_offset = 1) | |
1144 |
|
1148 | |||
1145 | # IPython itself shouldn't crash. This will produce a detailed |
|
1149 | # IPython itself shouldn't crash. This will produce a detailed | |
1146 | # post-mortem if it does. But we only install the crash handler for |
|
1150 | # post-mortem if it does. But we only install the crash handler for | |
1147 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
1151 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
1148 | # and lose the crash handler. This is because exceptions in the main |
|
1152 | # and lose the crash handler. This is because exceptions in the main | |
1149 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
1153 | # thread (such as in GUI code) propagate directly to sys.excepthook, | |
1150 | # and there's no point in printing crash dumps for every user exception. |
|
1154 | # and there's no point in printing crash dumps for every user exception. | |
1151 | if self.isthreaded: |
|
1155 | if self.isthreaded: | |
1152 | ipCrashHandler = ultratb.FormattedTB() |
|
1156 | ipCrashHandler = ultratb.FormattedTB() | |
1153 | else: |
|
1157 | else: | |
1154 | from IPython.core import crashhandler |
|
1158 | from IPython.core import crashhandler | |
1155 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
1159 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) | |
1156 | self.set_crash_handler(ipCrashHandler) |
|
1160 | self.set_crash_handler(ipCrashHandler) | |
1157 |
|
1161 | |||
1158 | # and add any custom exception handlers the user may have specified |
|
1162 | # and add any custom exception handlers the user may have specified | |
1159 | self.set_custom_exc(*custom_exceptions) |
|
1163 | self.set_custom_exc(*custom_exceptions) | |
1160 |
|
1164 | |||
1161 | def set_crash_handler(self, crashHandler): |
|
1165 | def set_crash_handler(self, crashHandler): | |
1162 | """Set the IPython crash handler. |
|
1166 | """Set the IPython crash handler. | |
1163 |
|
1167 | |||
1164 | This must be a callable with a signature suitable for use as |
|
1168 | This must be a callable with a signature suitable for use as | |
1165 | sys.excepthook.""" |
|
1169 | sys.excepthook.""" | |
1166 |
|
1170 | |||
1167 | # Install the given crash handler as the Python exception hook |
|
1171 | # Install the given crash handler as the Python exception hook | |
1168 | sys.excepthook = crashHandler |
|
1172 | sys.excepthook = crashHandler | |
1169 |
|
1173 | |||
1170 | # The instance will store a pointer to this, so that runtime code |
|
1174 | # The instance will store a pointer to this, so that runtime code | |
1171 | # (such as magics) can access it. This is because during the |
|
1175 | # (such as magics) can access it. This is because during the | |
1172 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
1176 | # read-eval loop, it gets temporarily overwritten (to deal with GUI | |
1173 | # frameworks). |
|
1177 | # frameworks). | |
1174 | self.sys_excepthook = sys.excepthook |
|
1178 | self.sys_excepthook = sys.excepthook | |
1175 |
|
1179 | |||
1176 | def set_custom_exc(self,exc_tuple,handler): |
|
1180 | def set_custom_exc(self,exc_tuple,handler): | |
1177 | """set_custom_exc(exc_tuple,handler) |
|
1181 | """set_custom_exc(exc_tuple,handler) | |
1178 |
|
1182 | |||
1179 | Set a custom exception handler, which will be called if any of the |
|
1183 | Set a custom exception handler, which will be called if any of the | |
1180 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1184 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1181 | runcode() method. |
|
1185 | runcode() method. | |
1182 |
|
1186 | |||
1183 | Inputs: |
|
1187 | Inputs: | |
1184 |
|
1188 | |||
1185 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1189 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1186 | handler for. It is very important that you use a tuple, and NOT A |
|
1190 | handler for. It is very important that you use a tuple, and NOT A | |
1187 | LIST here, because of the way Python's except statement works. If |
|
1191 | LIST here, because of the way Python's except statement works. If | |
1188 | you only want to trap a single exception, use a singleton tuple: |
|
1192 | you only want to trap a single exception, use a singleton tuple: | |
1189 |
|
1193 | |||
1190 | exc_tuple == (MyCustomException,) |
|
1194 | exc_tuple == (MyCustomException,) | |
1191 |
|
1195 | |||
1192 | - handler: this must be defined as a function with the following |
|
1196 | - handler: this must be defined as a function with the following | |
1193 | basic interface: def my_handler(self,etype,value,tb). |
|
1197 | basic interface: def my_handler(self,etype,value,tb). | |
1194 |
|
1198 | |||
1195 | This will be made into an instance method (via new.instancemethod) |
|
1199 | This will be made into an instance method (via new.instancemethod) | |
1196 | of IPython itself, and it will be called if any of the exceptions |
|
1200 | of IPython itself, and it will be called if any of the exceptions | |
1197 | listed in the exc_tuple are caught. If the handler is None, an |
|
1201 | listed in the exc_tuple are caught. If the handler is None, an | |
1198 | internal basic one is used, which just prints basic info. |
|
1202 | internal basic one is used, which just prints basic info. | |
1199 |
|
1203 | |||
1200 | WARNING: by putting in your own exception handler into IPython's main |
|
1204 | WARNING: by putting in your own exception handler into IPython's main | |
1201 | execution loop, you run a very good chance of nasty crashes. This |
|
1205 | execution loop, you run a very good chance of nasty crashes. This | |
1202 | facility should only be used if you really know what you are doing.""" |
|
1206 | facility should only be used if you really know what you are doing.""" | |
1203 |
|
1207 | |||
1204 | assert type(exc_tuple)==type(()) , \ |
|
1208 | assert type(exc_tuple)==type(()) , \ | |
1205 | "The custom exceptions must be given AS A TUPLE." |
|
1209 | "The custom exceptions must be given AS A TUPLE." | |
1206 |
|
1210 | |||
1207 | def dummy_handler(self,etype,value,tb): |
|
1211 | def dummy_handler(self,etype,value,tb): | |
1208 | print '*** Simple custom exception handler ***' |
|
1212 | print '*** Simple custom exception handler ***' | |
1209 | print 'Exception type :',etype |
|
1213 | print 'Exception type :',etype | |
1210 | print 'Exception value:',value |
|
1214 | print 'Exception value:',value | |
1211 | print 'Traceback :',tb |
|
1215 | print 'Traceback :',tb | |
1212 | print 'Source code :','\n'.join(self.buffer) |
|
1216 | print 'Source code :','\n'.join(self.buffer) | |
1213 |
|
1217 | |||
1214 | if handler is None: handler = dummy_handler |
|
1218 | if handler is None: handler = dummy_handler | |
1215 |
|
1219 | |||
1216 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1220 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1217 | self.custom_exceptions = exc_tuple |
|
1221 | self.custom_exceptions = exc_tuple | |
1218 |
|
1222 | |||
1219 | def excepthook(self, etype, value, tb): |
|
1223 | def excepthook(self, etype, value, tb): | |
1220 | """One more defense for GUI apps that call sys.excepthook. |
|
1224 | """One more defense for GUI apps that call sys.excepthook. | |
1221 |
|
1225 | |||
1222 | GUI frameworks like wxPython trap exceptions and call |
|
1226 | GUI frameworks like wxPython trap exceptions and call | |
1223 | sys.excepthook themselves. I guess this is a feature that |
|
1227 | sys.excepthook themselves. I guess this is a feature that | |
1224 | enables them to keep running after exceptions that would |
|
1228 | enables them to keep running after exceptions that would | |
1225 | otherwise kill their mainloop. This is a bother for IPython |
|
1229 | otherwise kill their mainloop. This is a bother for IPython | |
1226 | which excepts to catch all of the program exceptions with a try: |
|
1230 | which excepts to catch all of the program exceptions with a try: | |
1227 | except: statement. |
|
1231 | except: statement. | |
1228 |
|
1232 | |||
1229 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1233 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1230 | any app directly invokes sys.excepthook, it will look to the user like |
|
1234 | any app directly invokes sys.excepthook, it will look to the user like | |
1231 | IPython crashed. In order to work around this, we can disable the |
|
1235 | IPython crashed. In order to work around this, we can disable the | |
1232 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1236 | CrashHandler and replace it with this excepthook instead, which prints a | |
1233 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1237 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1234 | call sys.excepthook will generate a regular-looking exception from |
|
1238 | call sys.excepthook will generate a regular-looking exception from | |
1235 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1239 | IPython, and the CrashHandler will only be triggered by real IPython | |
1236 | crashes. |
|
1240 | crashes. | |
1237 |
|
1241 | |||
1238 | This hook should be used sparingly, only in places which are not likely |
|
1242 | This hook should be used sparingly, only in places which are not likely | |
1239 | to be true IPython errors. |
|
1243 | to be true IPython errors. | |
1240 | """ |
|
1244 | """ | |
1241 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1245 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1242 |
|
1246 | |||
1243 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): |
|
1247 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None): | |
1244 | """Display the exception that just occurred. |
|
1248 | """Display the exception that just occurred. | |
1245 |
|
1249 | |||
1246 | If nothing is known about the exception, this is the method which |
|
1250 | If nothing is known about the exception, this is the method which | |
1247 | should be used throughout the code for presenting user tracebacks, |
|
1251 | should be used throughout the code for presenting user tracebacks, | |
1248 | rather than directly invoking the InteractiveTB object. |
|
1252 | rather than directly invoking the InteractiveTB object. | |
1249 |
|
1253 | |||
1250 | A specific showsyntaxerror() also exists, but this method can take |
|
1254 | A specific showsyntaxerror() also exists, but this method can take | |
1251 | care of calling it if needed, so unless you are explicitly catching a |
|
1255 | care of calling it if needed, so unless you are explicitly catching a | |
1252 | SyntaxError exception, don't try to analyze the stack manually and |
|
1256 | SyntaxError exception, don't try to analyze the stack manually and | |
1253 | simply call this method.""" |
|
1257 | simply call this method.""" | |
1254 |
|
1258 | |||
1255 |
|
1259 | |||
1256 | # Though this won't be called by syntax errors in the input line, |
|
1260 | # Though this won't be called by syntax errors in the input line, | |
1257 | # there may be SyntaxError cases whith imported code. |
|
1261 | # there may be SyntaxError cases whith imported code. | |
1258 |
|
1262 | |||
1259 | try: |
|
1263 | try: | |
1260 | if exc_tuple is None: |
|
1264 | if exc_tuple is None: | |
1261 | etype, value, tb = sys.exc_info() |
|
1265 | etype, value, tb = sys.exc_info() | |
1262 | else: |
|
1266 | else: | |
1263 | etype, value, tb = exc_tuple |
|
1267 | etype, value, tb = exc_tuple | |
1264 |
|
1268 | |||
1265 | if etype is SyntaxError: |
|
1269 | if etype is SyntaxError: | |
1266 | self.showsyntaxerror(filename) |
|
1270 | self.showsyntaxerror(filename) | |
1267 | elif etype is UsageError: |
|
1271 | elif etype is UsageError: | |
1268 | print "UsageError:", value |
|
1272 | print "UsageError:", value | |
1269 | else: |
|
1273 | else: | |
1270 | # WARNING: these variables are somewhat deprecated and not |
|
1274 | # WARNING: these variables are somewhat deprecated and not | |
1271 | # necessarily safe to use in a threaded environment, but tools |
|
1275 | # necessarily safe to use in a threaded environment, but tools | |
1272 | # like pdb depend on their existence, so let's set them. If we |
|
1276 | # like pdb depend on their existence, so let's set them. If we | |
1273 | # find problems in the field, we'll need to revisit their use. |
|
1277 | # find problems in the field, we'll need to revisit their use. | |
1274 | sys.last_type = etype |
|
1278 | sys.last_type = etype | |
1275 | sys.last_value = value |
|
1279 | sys.last_value = value | |
1276 | sys.last_traceback = tb |
|
1280 | sys.last_traceback = tb | |
1277 |
|
1281 | |||
1278 | if etype in self.custom_exceptions: |
|
1282 | if etype in self.custom_exceptions: | |
1279 | self.CustomTB(etype,value,tb) |
|
1283 | self.CustomTB(etype,value,tb) | |
1280 | else: |
|
1284 | else: | |
1281 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1285 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
1282 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1286 | if self.InteractiveTB.call_pdb and self.has_readline: | |
1283 | # pdb mucks up readline, fix it back |
|
1287 | # pdb mucks up readline, fix it back | |
1284 | self.set_completer() |
|
1288 | self.set_completer() | |
1285 | except KeyboardInterrupt: |
|
1289 | except KeyboardInterrupt: | |
1286 | self.write("\nKeyboardInterrupt\n") |
|
1290 | self.write("\nKeyboardInterrupt\n") | |
1287 |
|
1291 | |||
1288 | def showsyntaxerror(self, filename=None): |
|
1292 | def showsyntaxerror(self, filename=None): | |
1289 | """Display the syntax error that just occurred. |
|
1293 | """Display the syntax error that just occurred. | |
1290 |
|
1294 | |||
1291 | This doesn't display a stack trace because there isn't one. |
|
1295 | This doesn't display a stack trace because there isn't one. | |
1292 |
|
1296 | |||
1293 | If a filename is given, it is stuffed in the exception instead |
|
1297 | If a filename is given, it is stuffed in the exception instead | |
1294 | of what was there before (because Python's parser always uses |
|
1298 | of what was there before (because Python's parser always uses | |
1295 | "<string>" when reading from a string). |
|
1299 | "<string>" when reading from a string). | |
1296 | """ |
|
1300 | """ | |
1297 | etype, value, last_traceback = sys.exc_info() |
|
1301 | etype, value, last_traceback = sys.exc_info() | |
1298 |
|
1302 | |||
1299 | # See note about these variables in showtraceback() below |
|
1303 | # See note about these variables in showtraceback() below | |
1300 | sys.last_type = etype |
|
1304 | sys.last_type = etype | |
1301 | sys.last_value = value |
|
1305 | sys.last_value = value | |
1302 | sys.last_traceback = last_traceback |
|
1306 | sys.last_traceback = last_traceback | |
1303 |
|
1307 | |||
1304 | if filename and etype is SyntaxError: |
|
1308 | if filename and etype is SyntaxError: | |
1305 | # Work hard to stuff the correct filename in the exception |
|
1309 | # Work hard to stuff the correct filename in the exception | |
1306 | try: |
|
1310 | try: | |
1307 | msg, (dummy_filename, lineno, offset, line) = value |
|
1311 | msg, (dummy_filename, lineno, offset, line) = value | |
1308 | except: |
|
1312 | except: | |
1309 | # Not the format we expect; leave it alone |
|
1313 | # Not the format we expect; leave it alone | |
1310 | pass |
|
1314 | pass | |
1311 | else: |
|
1315 | else: | |
1312 | # Stuff in the right filename |
|
1316 | # Stuff in the right filename | |
1313 | try: |
|
1317 | try: | |
1314 | # Assume SyntaxError is a class exception |
|
1318 | # Assume SyntaxError is a class exception | |
1315 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1319 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1316 | except: |
|
1320 | except: | |
1317 | # If that failed, assume SyntaxError is a string |
|
1321 | # If that failed, assume SyntaxError is a string | |
1318 | value = msg, (filename, lineno, offset, line) |
|
1322 | value = msg, (filename, lineno, offset, line) | |
1319 | self.SyntaxTB(etype,value,[]) |
|
1323 | self.SyntaxTB(etype,value,[]) | |
1320 |
|
1324 | |||
1321 | def edit_syntax_error(self): |
|
1325 | def edit_syntax_error(self): | |
1322 | """The bottom half of the syntax error handler called in the main loop. |
|
1326 | """The bottom half of the syntax error handler called in the main loop. | |
1323 |
|
1327 | |||
1324 | Loop until syntax error is fixed or user cancels. |
|
1328 | Loop until syntax error is fixed or user cancels. | |
1325 | """ |
|
1329 | """ | |
1326 |
|
1330 | |||
1327 | while self.SyntaxTB.last_syntax_error: |
|
1331 | while self.SyntaxTB.last_syntax_error: | |
1328 | # copy and clear last_syntax_error |
|
1332 | # copy and clear last_syntax_error | |
1329 | err = self.SyntaxTB.clear_err_state() |
|
1333 | err = self.SyntaxTB.clear_err_state() | |
1330 | if not self._should_recompile(err): |
|
1334 | if not self._should_recompile(err): | |
1331 | return |
|
1335 | return | |
1332 | try: |
|
1336 | try: | |
1333 | # may set last_syntax_error again if a SyntaxError is raised |
|
1337 | # may set last_syntax_error again if a SyntaxError is raised | |
1334 | self.safe_execfile(err.filename,self.user_ns) |
|
1338 | self.safe_execfile(err.filename,self.user_ns) | |
1335 | except: |
|
1339 | except: | |
1336 | self.showtraceback() |
|
1340 | self.showtraceback() | |
1337 | else: |
|
1341 | else: | |
1338 | try: |
|
1342 | try: | |
1339 | f = file(err.filename) |
|
1343 | f = file(err.filename) | |
1340 | try: |
|
1344 | try: | |
1341 | # This should be inside a display_trap block and I |
|
1345 | # This should be inside a display_trap block and I | |
1342 | # think it is. |
|
1346 | # think it is. | |
1343 | sys.displayhook(f.read()) |
|
1347 | sys.displayhook(f.read()) | |
1344 | finally: |
|
1348 | finally: | |
1345 | f.close() |
|
1349 | f.close() | |
1346 | except: |
|
1350 | except: | |
1347 | self.showtraceback() |
|
1351 | self.showtraceback() | |
1348 |
|
1352 | |||
1349 | def _should_recompile(self,e): |
|
1353 | def _should_recompile(self,e): | |
1350 | """Utility routine for edit_syntax_error""" |
|
1354 | """Utility routine for edit_syntax_error""" | |
1351 |
|
1355 | |||
1352 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1356 | if e.filename in ('<ipython console>','<input>','<string>', | |
1353 | '<console>','<BackgroundJob compilation>', |
|
1357 | '<console>','<BackgroundJob compilation>', | |
1354 | None): |
|
1358 | None): | |
1355 |
|
1359 | |||
1356 | return False |
|
1360 | return False | |
1357 | try: |
|
1361 | try: | |
1358 | if (self.autoedit_syntax and |
|
1362 | if (self.autoedit_syntax and | |
1359 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1363 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1360 | '[Y/n] ','y')): |
|
1364 | '[Y/n] ','y')): | |
1361 | return False |
|
1365 | return False | |
1362 | except EOFError: |
|
1366 | except EOFError: | |
1363 | return False |
|
1367 | return False | |
1364 |
|
1368 | |||
1365 | def int0(x): |
|
1369 | def int0(x): | |
1366 | try: |
|
1370 | try: | |
1367 | return int(x) |
|
1371 | return int(x) | |
1368 | except TypeError: |
|
1372 | except TypeError: | |
1369 | return 0 |
|
1373 | return 0 | |
1370 | # always pass integer line and offset values to editor hook |
|
1374 | # always pass integer line and offset values to editor hook | |
1371 | try: |
|
1375 | try: | |
1372 | self.hooks.fix_error_editor(e.filename, |
|
1376 | self.hooks.fix_error_editor(e.filename, | |
1373 | int0(e.lineno),int0(e.offset),e.msg) |
|
1377 | int0(e.lineno),int0(e.offset),e.msg) | |
1374 | except TryNext: |
|
1378 | except TryNext: | |
1375 | warn('Could not open editor') |
|
1379 | warn('Could not open editor') | |
1376 | return False |
|
1380 | return False | |
1377 | return True |
|
1381 | return True | |
1378 |
|
1382 | |||
1379 | #------------------------------------------------------------------------- |
|
1383 | #------------------------------------------------------------------------- | |
1380 | # Things related to tab completion |
|
1384 | # Things related to tab completion | |
1381 | #------------------------------------------------------------------------- |
|
1385 | #------------------------------------------------------------------------- | |
1382 |
|
1386 | |||
1383 | def complete(self, text): |
|
1387 | def complete(self, text): | |
1384 | """Return a sorted list of all possible completions on text. |
|
1388 | """Return a sorted list of all possible completions on text. | |
1385 |
|
1389 | |||
1386 | Inputs: |
|
1390 | Inputs: | |
1387 |
|
1391 | |||
1388 | - text: a string of text to be completed on. |
|
1392 | - text: a string of text to be completed on. | |
1389 |
|
1393 | |||
1390 | This is a wrapper around the completion mechanism, similar to what |
|
1394 | This is a wrapper around the completion mechanism, similar to what | |
1391 | readline does at the command line when the TAB key is hit. By |
|
1395 | readline does at the command line when the TAB key is hit. By | |
1392 | exposing it as a method, it can be used by other non-readline |
|
1396 | exposing it as a method, it can be used by other non-readline | |
1393 | environments (such as GUIs) for text completion. |
|
1397 | environments (such as GUIs) for text completion. | |
1394 |
|
1398 | |||
1395 | Simple usage example: |
|
1399 | Simple usage example: | |
1396 |
|
1400 | |||
1397 | In [7]: x = 'hello' |
|
1401 | In [7]: x = 'hello' | |
1398 |
|
1402 | |||
1399 | In [8]: x |
|
1403 | In [8]: x | |
1400 | Out[8]: 'hello' |
|
1404 | Out[8]: 'hello' | |
1401 |
|
1405 | |||
1402 | In [9]: print x |
|
1406 | In [9]: print x | |
1403 | hello |
|
1407 | hello | |
1404 |
|
1408 | |||
1405 | In [10]: _ip.complete('x.l') |
|
1409 | In [10]: _ip.complete('x.l') | |
1406 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1410 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1407 | """ |
|
1411 | """ | |
1408 |
|
1412 | |||
1409 | # Inject names into __builtin__ so we can complete on the added names. |
|
1413 | # Inject names into __builtin__ so we can complete on the added names. | |
1410 | with self.builtin_trap: |
|
1414 | with self.builtin_trap: | |
1411 | complete = self.Completer.complete |
|
1415 | complete = self.Completer.complete | |
1412 | state = 0 |
|
1416 | state = 0 | |
1413 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1417 | # use a dict so we get unique keys, since ipyhton's multiple | |
1414 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1418 | # completers can return duplicates. When we make 2.4 a requirement, | |
1415 | # start using sets instead, which are faster. |
|
1419 | # start using sets instead, which are faster. | |
1416 | comps = {} |
|
1420 | comps = {} | |
1417 | while True: |
|
1421 | while True: | |
1418 | newcomp = complete(text,state,line_buffer=text) |
|
1422 | newcomp = complete(text,state,line_buffer=text) | |
1419 | if newcomp is None: |
|
1423 | if newcomp is None: | |
1420 | break |
|
1424 | break | |
1421 | comps[newcomp] = 1 |
|
1425 | comps[newcomp] = 1 | |
1422 | state += 1 |
|
1426 | state += 1 | |
1423 | outcomps = comps.keys() |
|
1427 | outcomps = comps.keys() | |
1424 | outcomps.sort() |
|
1428 | outcomps.sort() | |
1425 | #print "T:",text,"OC:",outcomps # dbg |
|
1429 | #print "T:",text,"OC:",outcomps # dbg | |
1426 | #print "vars:",self.user_ns.keys() |
|
1430 | #print "vars:",self.user_ns.keys() | |
1427 | return outcomps |
|
1431 | return outcomps | |
1428 |
|
1432 | |||
1429 | def set_custom_completer(self,completer,pos=0): |
|
1433 | def set_custom_completer(self,completer,pos=0): | |
1430 | """set_custom_completer(completer,pos=0) |
|
1434 | """set_custom_completer(completer,pos=0) | |
1431 |
|
1435 | |||
1432 | Adds a new custom completer function. |
|
1436 | Adds a new custom completer function. | |
1433 |
|
1437 | |||
1434 | The position argument (defaults to 0) is the index in the completers |
|
1438 | The position argument (defaults to 0) is the index in the completers | |
1435 | list where you want the completer to be inserted.""" |
|
1439 | list where you want the completer to be inserted.""" | |
1436 |
|
1440 | |||
1437 | newcomp = new.instancemethod(completer,self.Completer, |
|
1441 | newcomp = new.instancemethod(completer,self.Completer, | |
1438 | self.Completer.__class__) |
|
1442 | self.Completer.__class__) | |
1439 | self.Completer.matchers.insert(pos,newcomp) |
|
1443 | self.Completer.matchers.insert(pos,newcomp) | |
1440 |
|
1444 | |||
1441 | def set_completer(self): |
|
1445 | def set_completer(self): | |
1442 | """reset readline's completer to be our own.""" |
|
1446 | """reset readline's completer to be our own.""" | |
1443 | self.readline.set_completer(self.Completer.complete) |
|
1447 | self.readline.set_completer(self.Completer.complete) | |
1444 |
|
1448 | |||
1445 | #------------------------------------------------------------------------- |
|
1449 | #------------------------------------------------------------------------- | |
1446 | # Things related to readline |
|
1450 | # Things related to readline | |
1447 | #------------------------------------------------------------------------- |
|
1451 | #------------------------------------------------------------------------- | |
1448 |
|
1452 | |||
1449 | def init_readline(self): |
|
1453 | def init_readline(self): | |
1450 | """Command history completion/saving/reloading.""" |
|
1454 | """Command history completion/saving/reloading.""" | |
1451 |
|
1455 | |||
1452 | self.rl_next_input = None |
|
1456 | self.rl_next_input = None | |
1453 | self.rl_do_indent = False |
|
1457 | self.rl_do_indent = False | |
1454 |
|
1458 | |||
1455 | if not self.readline_use: |
|
1459 | if not self.readline_use: | |
1456 | return |
|
1460 | return | |
1457 |
|
1461 | |||
1458 | import IPython.utils.rlineimpl as readline |
|
1462 | import IPython.utils.rlineimpl as readline | |
1459 |
|
1463 | |||
1460 | if not readline.have_readline: |
|
1464 | if not readline.have_readline: | |
1461 | self.has_readline = 0 |
|
1465 | self.has_readline = 0 | |
1462 | self.readline = None |
|
1466 | self.readline = None | |
1463 | # no point in bugging windows users with this every time: |
|
1467 | # no point in bugging windows users with this every time: | |
1464 | warn('Readline services not available on this platform.') |
|
1468 | warn('Readline services not available on this platform.') | |
1465 | else: |
|
1469 | else: | |
1466 | sys.modules['readline'] = readline |
|
1470 | sys.modules['readline'] = readline | |
1467 | import atexit |
|
1471 | import atexit | |
1468 | from IPython.core.completer import IPCompleter |
|
1472 | from IPython.core.completer import IPCompleter | |
1469 | self.Completer = IPCompleter(self, |
|
1473 | self.Completer = IPCompleter(self, | |
1470 | self.user_ns, |
|
1474 | self.user_ns, | |
1471 | self.user_global_ns, |
|
1475 | self.user_global_ns, | |
1472 | self.readline_omit__names, |
|
1476 | self.readline_omit__names, | |
1473 | self.alias_table) |
|
1477 | self.alias_table) | |
1474 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1478 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1475 | self.strdispatchers['complete_command'] = sdisp |
|
1479 | self.strdispatchers['complete_command'] = sdisp | |
1476 | self.Completer.custom_completers = sdisp |
|
1480 | self.Completer.custom_completers = sdisp | |
1477 | # Platform-specific configuration |
|
1481 | # Platform-specific configuration | |
1478 | if os.name == 'nt': |
|
1482 | if os.name == 'nt': | |
1479 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1483 | self.readline_startup_hook = readline.set_pre_input_hook | |
1480 | else: |
|
1484 | else: | |
1481 | self.readline_startup_hook = readline.set_startup_hook |
|
1485 | self.readline_startup_hook = readline.set_startup_hook | |
1482 |
|
1486 | |||
1483 | # Load user's initrc file (readline config) |
|
1487 | # Load user's initrc file (readline config) | |
1484 | # Or if libedit is used, load editrc. |
|
1488 | # Or if libedit is used, load editrc. | |
1485 | inputrc_name = os.environ.get('INPUTRC') |
|
1489 | inputrc_name = os.environ.get('INPUTRC') | |
1486 | if inputrc_name is None: |
|
1490 | if inputrc_name is None: | |
1487 | home_dir = get_home_dir() |
|
1491 | home_dir = get_home_dir() | |
1488 | if home_dir is not None: |
|
1492 | if home_dir is not None: | |
1489 | inputrc_name = '.inputrc' |
|
1493 | inputrc_name = '.inputrc' | |
1490 | if readline.uses_libedit: |
|
1494 | if readline.uses_libedit: | |
1491 | inputrc_name = '.editrc' |
|
1495 | inputrc_name = '.editrc' | |
1492 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1496 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1493 | if os.path.isfile(inputrc_name): |
|
1497 | if os.path.isfile(inputrc_name): | |
1494 | try: |
|
1498 | try: | |
1495 | readline.read_init_file(inputrc_name) |
|
1499 | readline.read_init_file(inputrc_name) | |
1496 | except: |
|
1500 | except: | |
1497 | warn('Problems reading readline initialization file <%s>' |
|
1501 | warn('Problems reading readline initialization file <%s>' | |
1498 | % inputrc_name) |
|
1502 | % inputrc_name) | |
1499 |
|
1503 | |||
1500 | self.has_readline = 1 |
|
1504 | self.has_readline = 1 | |
1501 | self.readline = readline |
|
1505 | self.readline = readline | |
1502 | # save this in sys so embedded copies can restore it properly |
|
1506 | # save this in sys so embedded copies can restore it properly | |
1503 | sys.ipcompleter = self.Completer.complete |
|
1507 | sys.ipcompleter = self.Completer.complete | |
1504 | self.set_completer() |
|
1508 | self.set_completer() | |
1505 |
|
1509 | |||
1506 | # Configure readline according to user's prefs |
|
1510 | # Configure readline according to user's prefs | |
1507 | # This is only done if GNU readline is being used. If libedit |
|
1511 | # This is only done if GNU readline is being used. If libedit | |
1508 | # is being used (as on Leopard) the readline config is |
|
1512 | # is being used (as on Leopard) the readline config is | |
1509 | # not run as the syntax for libedit is different. |
|
1513 | # not run as the syntax for libedit is different. | |
1510 | if not readline.uses_libedit: |
|
1514 | if not readline.uses_libedit: | |
1511 | for rlcommand in self.readline_parse_and_bind: |
|
1515 | for rlcommand in self.readline_parse_and_bind: | |
1512 | #print "loading rl:",rlcommand # dbg |
|
1516 | #print "loading rl:",rlcommand # dbg | |
1513 | readline.parse_and_bind(rlcommand) |
|
1517 | readline.parse_and_bind(rlcommand) | |
1514 |
|
1518 | |||
1515 | # Remove some chars from the delimiters list. If we encounter |
|
1519 | # Remove some chars from the delimiters list. If we encounter | |
1516 | # unicode chars, discard them. |
|
1520 | # unicode chars, discard them. | |
1517 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1521 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1518 | delims = delims.translate(string._idmap, |
|
1522 | delims = delims.translate(string._idmap, | |
1519 | self.readline_remove_delims) |
|
1523 | self.readline_remove_delims) | |
1520 | readline.set_completer_delims(delims) |
|
1524 | readline.set_completer_delims(delims) | |
1521 | # otherwise we end up with a monster history after a while: |
|
1525 | # otherwise we end up with a monster history after a while: | |
1522 | readline.set_history_length(1000) |
|
1526 | readline.set_history_length(1000) | |
1523 | try: |
|
1527 | try: | |
1524 | #print '*** Reading readline history' # dbg |
|
1528 | #print '*** Reading readline history' # dbg | |
1525 | readline.read_history_file(self.histfile) |
|
1529 | readline.read_history_file(self.histfile) | |
1526 | except IOError: |
|
1530 | except IOError: | |
1527 | pass # It doesn't exist yet. |
|
1531 | pass # It doesn't exist yet. | |
1528 |
|
1532 | |||
1529 | atexit.register(self.atexit_operations) |
|
1533 | atexit.register(self.atexit_operations) | |
1530 | del atexit |
|
1534 | del atexit | |
1531 |
|
1535 | |||
1532 | # Configure auto-indent for all platforms |
|
1536 | # Configure auto-indent for all platforms | |
1533 | self.set_autoindent(self.autoindent) |
|
1537 | self.set_autoindent(self.autoindent) | |
1534 |
|
1538 | |||
1535 | def set_next_input(self, s): |
|
1539 | def set_next_input(self, s): | |
1536 | """ Sets the 'default' input string for the next command line. |
|
1540 | """ Sets the 'default' input string for the next command line. | |
1537 |
|
1541 | |||
1538 | Requires readline. |
|
1542 | Requires readline. | |
1539 |
|
1543 | |||
1540 | Example: |
|
1544 | Example: | |
1541 |
|
1545 | |||
1542 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1546 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1543 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1547 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1544 | """ |
|
1548 | """ | |
1545 |
|
1549 | |||
1546 | self.rl_next_input = s |
|
1550 | self.rl_next_input = s | |
1547 |
|
1551 | |||
1548 | def pre_readline(self): |
|
1552 | def pre_readline(self): | |
1549 | """readline hook to be used at the start of each line. |
|
1553 | """readline hook to be used at the start of each line. | |
1550 |
|
1554 | |||
1551 | Currently it handles auto-indent only.""" |
|
1555 | Currently it handles auto-indent only.""" | |
1552 |
|
1556 | |||
1553 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1557 | #debugx('self.indent_current_nsp','pre_readline:') | |
1554 |
|
1558 | |||
1555 | if self.rl_do_indent: |
|
1559 | if self.rl_do_indent: | |
1556 | self.readline.insert_text(self._indent_current_str()) |
|
1560 | self.readline.insert_text(self._indent_current_str()) | |
1557 | if self.rl_next_input is not None: |
|
1561 | if self.rl_next_input is not None: | |
1558 | self.readline.insert_text(self.rl_next_input) |
|
1562 | self.readline.insert_text(self.rl_next_input) | |
1559 | self.rl_next_input = None |
|
1563 | self.rl_next_input = None | |
1560 |
|
1564 | |||
1561 | def _indent_current_str(self): |
|
1565 | def _indent_current_str(self): | |
1562 | """return the current level of indentation as a string""" |
|
1566 | """return the current level of indentation as a string""" | |
1563 | return self.indent_current_nsp * ' ' |
|
1567 | return self.indent_current_nsp * ' ' | |
1564 |
|
1568 | |||
1565 | #------------------------------------------------------------------------- |
|
1569 | #------------------------------------------------------------------------- | |
1566 | # Things related to magics |
|
1570 | # Things related to magics | |
1567 | #------------------------------------------------------------------------- |
|
1571 | #------------------------------------------------------------------------- | |
1568 |
|
1572 | |||
1569 | def init_magics(self): |
|
1573 | def init_magics(self): | |
1570 | # Set user colors (don't do it in the constructor above so that it |
|
1574 | # Set user colors (don't do it in the constructor above so that it | |
1571 | # doesn't crash if colors option is invalid) |
|
1575 | # doesn't crash if colors option is invalid) | |
1572 | self.magic_colors(self.colors) |
|
1576 | self.magic_colors(self.colors) | |
1573 |
|
1577 | |||
1574 | def magic(self,arg_s): |
|
1578 | def magic(self,arg_s): | |
1575 | """Call a magic function by name. |
|
1579 | """Call a magic function by name. | |
1576 |
|
1580 | |||
1577 | Input: a string containing the name of the magic function to call and any |
|
1581 | Input: a string containing the name of the magic function to call and any | |
1578 | additional arguments to be passed to the magic. |
|
1582 | additional arguments to be passed to the magic. | |
1579 |
|
1583 | |||
1580 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1584 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1581 | prompt: |
|
1585 | prompt: | |
1582 |
|
1586 | |||
1583 | In[1]: %name -opt foo bar |
|
1587 | In[1]: %name -opt foo bar | |
1584 |
|
1588 | |||
1585 | To call a magic without arguments, simply use magic('name'). |
|
1589 | To call a magic without arguments, simply use magic('name'). | |
1586 |
|
1590 | |||
1587 | This provides a proper Python function to call IPython's magics in any |
|
1591 | This provides a proper Python function to call IPython's magics in any | |
1588 | valid Python code you can type at the interpreter, including loops and |
|
1592 | valid Python code you can type at the interpreter, including loops and | |
1589 | compound statements. |
|
1593 | compound statements. | |
1590 | """ |
|
1594 | """ | |
1591 |
|
1595 | |||
1592 | args = arg_s.split(' ',1) |
|
1596 | args = arg_s.split(' ',1) | |
1593 | magic_name = args[0] |
|
1597 | magic_name = args[0] | |
1594 | magic_name = magic_name.lstrip(self.ESC_MAGIC) |
|
1598 | magic_name = magic_name.lstrip(self.ESC_MAGIC) | |
1595 |
|
1599 | |||
1596 | try: |
|
1600 | try: | |
1597 | magic_args = args[1] |
|
1601 | magic_args = args[1] | |
1598 | except IndexError: |
|
1602 | except IndexError: | |
1599 | magic_args = '' |
|
1603 | magic_args = '' | |
1600 | fn = getattr(self,'magic_'+magic_name,None) |
|
1604 | fn = getattr(self,'magic_'+magic_name,None) | |
1601 | if fn is None: |
|
1605 | if fn is None: | |
1602 | error("Magic function `%s` not found." % magic_name) |
|
1606 | error("Magic function `%s` not found." % magic_name) | |
1603 | else: |
|
1607 | else: | |
1604 | magic_args = self.var_expand(magic_args,1) |
|
1608 | magic_args = self.var_expand(magic_args,1) | |
1605 | with nested(self.builtin_trap, self.display_trap): |
|
1609 | with nested(self.builtin_trap, self.display_trap): | |
1606 | return fn(magic_args) |
|
1610 | return fn(magic_args) | |
1607 | # return result |
|
1611 | # return result | |
1608 |
|
1612 | |||
1609 | def define_magic(self, magicname, func): |
|
1613 | def define_magic(self, magicname, func): | |
1610 | """Expose own function as magic function for ipython |
|
1614 | """Expose own function as magic function for ipython | |
1611 |
|
1615 | |||
1612 | def foo_impl(self,parameter_s=''): |
|
1616 | def foo_impl(self,parameter_s=''): | |
1613 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1617 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1614 | print 'Magic function. Passed parameter is between < >:' |
|
1618 | print 'Magic function. Passed parameter is between < >:' | |
1615 | print '<%s>' % parameter_s |
|
1619 | print '<%s>' % parameter_s | |
1616 | print 'The self object is:',self |
|
1620 | print 'The self object is:',self | |
1617 |
|
1621 | |||
1618 | self.define_magic('foo',foo_impl) |
|
1622 | self.define_magic('foo',foo_impl) | |
1619 | """ |
|
1623 | """ | |
1620 |
|
1624 | |||
1621 | import new |
|
1625 | import new | |
1622 | im = new.instancemethod(func,self, self.__class__) |
|
1626 | im = new.instancemethod(func,self, self.__class__) | |
1623 | old = getattr(self, "magic_" + magicname, None) |
|
1627 | old = getattr(self, "magic_" + magicname, None) | |
1624 | setattr(self, "magic_" + magicname, im) |
|
1628 | setattr(self, "magic_" + magicname, im) | |
1625 | return old |
|
1629 | return old | |
1626 |
|
1630 | |||
1627 | #------------------------------------------------------------------------- |
|
1631 | #------------------------------------------------------------------------- | |
1628 | # Things related to macros |
|
1632 | # Things related to macros | |
1629 | #------------------------------------------------------------------------- |
|
1633 | #------------------------------------------------------------------------- | |
1630 |
|
1634 | |||
1631 | def define_macro(self, name, themacro): |
|
1635 | def define_macro(self, name, themacro): | |
1632 | """Define a new macro |
|
1636 | """Define a new macro | |
1633 |
|
1637 | |||
1634 | Parameters |
|
1638 | Parameters | |
1635 | ---------- |
|
1639 | ---------- | |
1636 | name : str |
|
1640 | name : str | |
1637 | The name of the macro. |
|
1641 | The name of the macro. | |
1638 | themacro : str or Macro |
|
1642 | themacro : str or Macro | |
1639 | The action to do upon invoking the macro. If a string, a new |
|
1643 | The action to do upon invoking the macro. If a string, a new | |
1640 | Macro object is created by passing the string to it. |
|
1644 | Macro object is created by passing the string to it. | |
1641 | """ |
|
1645 | """ | |
1642 |
|
1646 | |||
1643 | from IPython.core import macro |
|
1647 | from IPython.core import macro | |
1644 |
|
1648 | |||
1645 | if isinstance(themacro, basestring): |
|
1649 | if isinstance(themacro, basestring): | |
1646 | themacro = macro.Macro(themacro) |
|
1650 | themacro = macro.Macro(themacro) | |
1647 | if not isinstance(themacro, macro.Macro): |
|
1651 | if not isinstance(themacro, macro.Macro): | |
1648 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1652 | raise ValueError('A macro must be a string or a Macro instance.') | |
1649 | self.user_ns[name] = themacro |
|
1653 | self.user_ns[name] = themacro | |
1650 |
|
1654 | |||
1651 | #------------------------------------------------------------------------- |
|
1655 | #------------------------------------------------------------------------- | |
1652 | # Things related to the running of system commands |
|
1656 | # Things related to the running of system commands | |
1653 | #------------------------------------------------------------------------- |
|
1657 | #------------------------------------------------------------------------- | |
1654 |
|
1658 | |||
1655 | def system(self, cmd): |
|
1659 | def system(self, cmd): | |
1656 | """Make a system call, using IPython.""" |
|
1660 | """Make a system call, using IPython.""" | |
1657 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1661 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1658 |
|
1662 | |||
1659 | #------------------------------------------------------------------------- |
|
1663 | #------------------------------------------------------------------------- | |
1660 | # Things related to aliases |
|
1664 | # Things related to aliases | |
1661 | #------------------------------------------------------------------------- |
|
1665 | #------------------------------------------------------------------------- | |
1662 |
|
1666 | |||
1663 |
def init_alias |
|
1667 | def init_alias(self): | |
1664 | # dict of things NOT to alias (keywords, builtins and some magics) |
|
1668 | self.alias_manager = AliasManager(self, config=self.config) | |
1665 | no_alias = {} |
|
|||
1666 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
|||
1667 | for key in keyword.kwlist + no_alias_magics: |
|
|||
1668 | no_alias[key] = 1 |
|
|||
1669 | no_alias.update(__builtin__.__dict__) |
|
|||
1670 | self.no_alias = no_alias |
|
|||
1671 |
|
||||
1672 | # Make some aliases automatically |
|
|||
1673 | # Prepare list of shell aliases to auto-define |
|
|||
1674 | if os.name == 'posix': |
|
|||
1675 | auto_alias = ('mkdir mkdir', 'rmdir rmdir', |
|
|||
1676 | 'mv mv -i','rm rm -i','cp cp -i', |
|
|||
1677 | 'cat cat','less less','clear clear', |
|
|||
1678 | # a better ls |
|
|||
1679 | 'ls ls -F', |
|
|||
1680 | # long ls |
|
|||
1681 | 'll ls -lF') |
|
|||
1682 | # Extra ls aliases with color, which need special treatment on BSD |
|
|||
1683 | # variants |
|
|||
1684 | ls_extra = ( # color ls |
|
|||
1685 | 'lc ls -F -o --color', |
|
|||
1686 | # ls normal files only |
|
|||
1687 | 'lf ls -F -o --color %l | grep ^-', |
|
|||
1688 | # ls symbolic links |
|
|||
1689 | 'lk ls -F -o --color %l | grep ^l', |
|
|||
1690 | # directories or links to directories, |
|
|||
1691 | 'ldir ls -F -o --color %l | grep /$', |
|
|||
1692 | # things which are executable |
|
|||
1693 | 'lx ls -F -o --color %l | grep ^-..x', |
|
|||
1694 | ) |
|
|||
1695 | # The BSDs don't ship GNU ls, so they don't understand the |
|
|||
1696 | # --color switch out of the box |
|
|||
1697 | if 'bsd' in sys.platform: |
|
|||
1698 | ls_extra = ( # ls normal files only |
|
|||
1699 | 'lf ls -lF | grep ^-', |
|
|||
1700 | # ls symbolic links |
|
|||
1701 | 'lk ls -lF | grep ^l', |
|
|||
1702 | # directories or links to directories, |
|
|||
1703 | 'ldir ls -lF | grep /$', |
|
|||
1704 | # things which are executable |
|
|||
1705 | 'lx ls -lF | grep ^-..x', |
|
|||
1706 | ) |
|
|||
1707 | auto_alias = auto_alias + ls_extra |
|
|||
1708 | elif os.name in ['nt','dos']: |
|
|||
1709 | auto_alias = ('ls dir /on', |
|
|||
1710 | 'ddir dir /ad /on', 'ldir dir /ad /on', |
|
|||
1711 | 'mkdir mkdir','rmdir rmdir','echo echo', |
|
|||
1712 | 'ren ren','cls cls','copy copy') |
|
|||
1713 | else: |
|
|||
1714 | auto_alias = () |
|
|||
1715 | self.auto_alias = [s.split(None,1) for s in auto_alias] |
|
|||
1716 |
|
||||
1717 | # Load default aliases |
|
|||
1718 | for alias, cmd in self.auto_alias: |
|
|||
1719 | self.define_alias(alias,cmd) |
|
|||
1720 |
|
||||
1721 | # Load user aliases |
|
|||
1722 | for alias in self.alias: |
|
|||
1723 | self.magic_alias(alias) |
|
|||
1724 |
|
||||
1725 | def call_alias(self,alias,rest=''): |
|
|||
1726 | """Call an alias given its name and the rest of the line. |
|
|||
1727 |
|
||||
1728 | This is only used to provide backwards compatibility for users of |
|
|||
1729 | ipalias(), use of which is not recommended for anymore.""" |
|
|||
1730 |
|
||||
1731 | # Now call the macro, evaluating in the user's namespace |
|
|||
1732 | cmd = self.transform_alias(alias, rest) |
|
|||
1733 | try: |
|
|||
1734 | self.system(cmd) |
|
|||
1735 | except: |
|
|||
1736 | self.showtraceback() |
|
|||
1737 |
|
||||
1738 | def define_alias(self, name, cmd): |
|
|||
1739 | """ Define a new alias.""" |
|
|||
1740 |
|
||||
1741 | if callable(cmd): |
|
|||
1742 | self.alias_table[name] = cmd |
|
|||
1743 | from IPython.core import shadowns |
|
|||
1744 | setattr(shadowns, name, cmd) |
|
|||
1745 | return |
|
|||
1746 |
|
||||
1747 | if isinstance(cmd, basestring): |
|
|||
1748 | nargs = cmd.count('%s') |
|
|||
1749 | if nargs>0 and cmd.find('%l')>=0: |
|
|||
1750 | raise Exception('The %s and %l specifiers are mutually ' |
|
|||
1751 | 'exclusive in alias definitions.') |
|
|||
1752 |
|
||||
1753 | self.alias_table[name] = (nargs,cmd) |
|
|||
1754 | return |
|
|||
1755 |
|
||||
1756 | self.alias_table[name] = cmd |
|
|||
1757 |
|
||||
1758 | def ipalias(self,arg_s): |
|
|||
1759 | """Call an alias by name. |
|
|||
1760 |
|
||||
1761 | Input: a string containing the name of the alias to call and any |
|
|||
1762 | additional arguments to be passed to the magic. |
|
|||
1763 |
|
||||
1764 | ipalias('name -opt foo bar') is equivalent to typing at the ipython |
|
|||
1765 | prompt: |
|
|||
1766 |
|
||||
1767 | In[1]: name -opt foo bar |
|
|||
1768 |
|
||||
1769 | To call an alias without arguments, simply use ipalias('name'). |
|
|||
1770 |
|
||||
1771 | This provides a proper Python function to call IPython's aliases in any |
|
|||
1772 | valid Python code you can type at the interpreter, including loops and |
|
|||
1773 | compound statements. It is added by IPython to the Python builtin |
|
|||
1774 | namespace upon initialization.""" |
|
|||
1775 |
|
||||
1776 | args = arg_s.split(' ',1) |
|
|||
1777 | alias_name = args[0] |
|
|||
1778 | try: |
|
|||
1779 | alias_args = args[1] |
|
|||
1780 | except IndexError: |
|
|||
1781 | alias_args = '' |
|
|||
1782 | if alias_name in self.alias_table: |
|
|||
1783 | self.call_alias(alias_name,alias_args) |
|
|||
1784 | else: |
|
|||
1785 | error("Alias `%s` not found." % alias_name) |
|
|||
1786 |
|
1669 | |||
1787 | def expand_alias(self, line): |
|
1670 | def expand_alias(self, line): | |
1788 | """ Expand an alias in the command line |
|
1671 | """ Expand an alias in the command line | |
1789 |
|
1672 | |||
1790 | Returns the provided command line, possibly with the first word |
|
1673 | Returns the provided command line, possibly with the first word | |
1791 | (command) translated according to alias expansion rules. |
|
1674 | (command) translated according to alias expansion rules. | |
1792 |
|
1675 | |||
1793 | [ipython]|16> _ip.expand_aliases("np myfile.txt") |
|
1676 | [ipython]|16> _ip.expand_aliases("np myfile.txt") | |
1794 | <16> 'q:/opt/np/notepad++.exe myfile.txt' |
|
1677 | <16> 'q:/opt/np/notepad++.exe myfile.txt' | |
1795 | """ |
|
1678 | """ | |
1796 |
|
1679 | |||
1797 | pre,fn,rest = self.split_user_input(line) |
|
1680 | pre,fn,rest = self.split_user_input(line) | |
1798 | res = pre + self.expand_aliases(fn, rest) |
|
1681 | res = pre + self.expand_aliases(fn, rest) | |
1799 | return res |
|
1682 | return res | |
1800 |
|
1683 | |||
1801 | def expand_aliases(self, fn, rest): |
|
1684 | def expand_aliases(self, fn, rest): | |
1802 | """Expand multiple levels of aliases: |
|
1685 | """Expand multiple levels of aliases: | |
1803 |
|
1686 | |||
1804 | if: |
|
1687 | if: | |
1805 |
|
1688 | |||
1806 | alias foo bar /tmp |
|
1689 | alias foo bar /tmp | |
1807 | alias baz foo |
|
1690 | alias baz foo | |
1808 |
|
1691 | |||
1809 | then: |
|
1692 | then: | |
1810 |
|
1693 | |||
1811 | baz huhhahhei -> bar /tmp huhhahhei |
|
1694 | baz huhhahhei -> bar /tmp huhhahhei | |
1812 |
|
1695 | |||
1813 | """ |
|
1696 | """ | |
1814 | line = fn + " " + rest |
|
1697 | line = fn + " " + rest | |
1815 |
|
1698 | |||
1816 | done = set() |
|
1699 | done = set() | |
1817 | while 1: |
|
1700 | while 1: | |
1818 | pre,fn,rest = prefilter.splitUserInput(line, |
|
1701 | pre,fn,rest = prefilter.splitUserInput(line, | |
1819 | prefilter.shell_line_split) |
|
1702 | prefilter.shell_line_split) | |
1820 | if fn in self.alias_table: |
|
1703 | if fn in self.alias_manager.alias_table: | |
1821 | if fn in done: |
|
1704 | if fn in done: | |
1822 | warn("Cyclic alias definition, repeated '%s'" % fn) |
|
1705 | warn("Cyclic alias definition, repeated '%s'" % fn) | |
1823 | return "" |
|
1706 | return "" | |
1824 | done.add(fn) |
|
1707 | done.add(fn) | |
1825 |
|
1708 | |||
1826 | l2 = self.transform_alias(fn,rest) |
|
1709 | l2 = self.alias_manager.transform_alias(fn, rest) | |
1827 | # dir -> dir |
|
|||
1828 | # print "alias",line, "->",l2 #dbg |
|
|||
1829 | if l2 == line: |
|
1710 | if l2 == line: | |
1830 | break |
|
1711 | break | |
1831 | # ls -> ls -F should not recurse forever |
|
1712 | # ls -> ls -F should not recurse forever | |
1832 | if l2.split(None,1)[0] == line.split(None,1)[0]: |
|
1713 | if l2.split(None,1)[0] == line.split(None,1)[0]: | |
1833 | line = l2 |
|
1714 | line = l2 | |
1834 | break |
|
1715 | break | |
1835 |
|
||||
1836 | line=l2 |
|
1716 | line=l2 | |
1837 |
|
||||
1838 |
|
||||
1839 | # print "al expand to",line #dbg |
|
|||
1840 | else: |
|
1717 | else: | |
1841 | break |
|
1718 | break | |
1842 |
|
1719 | |||
1843 | return line |
|
1720 | return line | |
1844 |
|
1721 | |||
1845 | def transform_alias(self, alias,rest=''): |
|
|||
1846 | """ Transform alias to system command string. |
|
|||
1847 | """ |
|
|||
1848 | trg = self.alias_table[alias] |
|
|||
1849 |
|
||||
1850 | nargs,cmd = trg |
|
|||
1851 | # print trg #dbg |
|
|||
1852 | if ' ' in cmd and os.path.isfile(cmd): |
|
|||
1853 | cmd = '"%s"' % cmd |
|
|||
1854 |
|
||||
1855 | # Expand the %l special to be the user's input line |
|
|||
1856 | if cmd.find('%l') >= 0: |
|
|||
1857 | cmd = cmd.replace('%l',rest) |
|
|||
1858 | rest = '' |
|
|||
1859 | if nargs==0: |
|
|||
1860 | # Simple, argument-less aliases |
|
|||
1861 | cmd = '%s %s' % (cmd,rest) |
|
|||
1862 | else: |
|
|||
1863 | # Handle aliases with positional arguments |
|
|||
1864 | args = rest.split(None,nargs) |
|
|||
1865 | if len(args)< nargs: |
|
|||
1866 | error('Alias <%s> requires %s arguments, %s given.' % |
|
|||
1867 | (alias,nargs,len(args))) |
|
|||
1868 | return None |
|
|||
1869 | cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) |
|
|||
1870 | # Now call the macro, evaluating in the user's namespace |
|
|||
1871 | #print 'new command: <%r>' % cmd # dbg |
|
|||
1872 | return cmd |
|
|||
1873 |
|
||||
1874 | def init_auto_alias(self): |
|
|||
1875 | """Define some aliases automatically. |
|
|||
1876 |
|
||||
1877 | These are ALL parameter-less aliases""" |
|
|||
1878 |
|
||||
1879 | for alias,cmd in self.auto_alias: |
|
|||
1880 | self.define_alias(alias,cmd) |
|
|||
1881 |
|
||||
1882 | def alias_table_validate(self,verbose=0): |
|
|||
1883 | """Update information about the alias table. |
|
|||
1884 |
|
||||
1885 | In particular, make sure no Python keywords/builtins are in it.""" |
|
|||
1886 |
|
||||
1887 | no_alias = self.no_alias |
|
|||
1888 | for k in self.alias_table.keys(): |
|
|||
1889 | if k in no_alias: |
|
|||
1890 | del self.alias_table[k] |
|
|||
1891 | if verbose: |
|
|||
1892 | print ("Deleting alias <%s>, it's a Python " |
|
|||
1893 | "keyword or builtin." % k) |
|
|||
1894 |
|
||||
1895 | #------------------------------------------------------------------------- |
|
1722 | #------------------------------------------------------------------------- | |
1896 | # Things related to the running of code |
|
1723 | # Things related to the running of code | |
1897 | #------------------------------------------------------------------------- |
|
1724 | #------------------------------------------------------------------------- | |
1898 |
|
1725 | |||
1899 | def ex(self, cmd): |
|
1726 | def ex(self, cmd): | |
1900 | """Execute a normal python statement in user namespace.""" |
|
1727 | """Execute a normal python statement in user namespace.""" | |
1901 | with nested(self.builtin_trap, self.display_trap): |
|
1728 | with nested(self.builtin_trap, self.display_trap): | |
1902 | exec cmd in self.user_global_ns, self.user_ns |
|
1729 | exec cmd in self.user_global_ns, self.user_ns | |
1903 |
|
1730 | |||
1904 | def ev(self, expr): |
|
1731 | def ev(self, expr): | |
1905 | """Evaluate python expression expr in user namespace. |
|
1732 | """Evaluate python expression expr in user namespace. | |
1906 |
|
1733 | |||
1907 | Returns the result of evaluation |
|
1734 | Returns the result of evaluation | |
1908 | """ |
|
1735 | """ | |
1909 | with nested(self.builtin_trap, self.display_trap): |
|
1736 | with nested(self.builtin_trap, self.display_trap): | |
1910 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1737 | return eval(expr, self.user_global_ns, self.user_ns) | |
1911 |
|
1738 | |||
1912 | def mainloop(self, banner=None): |
|
1739 | def mainloop(self, banner=None): | |
1913 | """Start the mainloop. |
|
1740 | """Start the mainloop. | |
1914 |
|
1741 | |||
1915 | If an optional banner argument is given, it will override the |
|
1742 | If an optional banner argument is given, it will override the | |
1916 | internally created default banner. |
|
1743 | internally created default banner. | |
1917 | """ |
|
1744 | """ | |
1918 |
|
1745 | |||
1919 | with nested(self.builtin_trap, self.display_trap): |
|
1746 | with nested(self.builtin_trap, self.display_trap): | |
1920 | if self.c: # Emulate Python's -c option |
|
1747 | if self.c: # Emulate Python's -c option | |
1921 | self.exec_init_cmd() |
|
1748 | self.exec_init_cmd() | |
1922 |
|
1749 | |||
1923 | if self.display_banner: |
|
1750 | if self.display_banner: | |
1924 | if banner is None: |
|
1751 | if banner is None: | |
1925 | banner = self.banner |
|
1752 | banner = self.banner | |
1926 |
|
1753 | |||
1927 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1754 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1928 | # ensure that it's in sync |
|
1755 | # ensure that it's in sync | |
1929 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1756 | if len(self.input_hist) != len (self.input_hist_raw): | |
1930 | self.input_hist_raw = InputList(self.input_hist) |
|
1757 | self.input_hist_raw = InputList(self.input_hist) | |
1931 |
|
1758 | |||
1932 | while 1: |
|
1759 | while 1: | |
1933 | try: |
|
1760 | try: | |
1934 | self.interact() |
|
1761 | self.interact() | |
1935 | #self.interact_with_readline() |
|
1762 | #self.interact_with_readline() | |
1936 | # XXX for testing of a readline-decoupled repl loop, call |
|
1763 | # XXX for testing of a readline-decoupled repl loop, call | |
1937 | # interact_with_readline above |
|
1764 | # interact_with_readline above | |
1938 | break |
|
1765 | break | |
1939 | except KeyboardInterrupt: |
|
1766 | except KeyboardInterrupt: | |
1940 | # this should not be necessary, but KeyboardInterrupt |
|
1767 | # this should not be necessary, but KeyboardInterrupt | |
1941 | # handling seems rather unpredictable... |
|
1768 | # handling seems rather unpredictable... | |
1942 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1769 | self.write("\nKeyboardInterrupt in interact()\n") | |
1943 |
|
1770 | |||
1944 | def exec_init_cmd(self): |
|
1771 | def exec_init_cmd(self): | |
1945 | """Execute a command given at the command line. |
|
1772 | """Execute a command given at the command line. | |
1946 |
|
1773 | |||
1947 | This emulates Python's -c option.""" |
|
1774 | This emulates Python's -c option.""" | |
1948 |
|
1775 | |||
1949 | #sys.argv = ['-c'] |
|
1776 | #sys.argv = ['-c'] | |
1950 | self.push_line(self.prefilter(self.c, False)) |
|
1777 | self.push_line(self.prefilter(self.c, False)) | |
1951 | if not self.interactive: |
|
1778 | if not self.interactive: | |
1952 | self.ask_exit() |
|
1779 | self.ask_exit() | |
1953 |
|
1780 | |||
1954 | def interact_prompt(self): |
|
1781 | def interact_prompt(self): | |
1955 | """ Print the prompt (in read-eval-print loop) |
|
1782 | """ Print the prompt (in read-eval-print loop) | |
1956 |
|
1783 | |||
1957 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1784 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1958 | used in standard IPython flow. |
|
1785 | used in standard IPython flow. | |
1959 | """ |
|
1786 | """ | |
1960 | if self.more: |
|
1787 | if self.more: | |
1961 | try: |
|
1788 | try: | |
1962 | prompt = self.hooks.generate_prompt(True) |
|
1789 | prompt = self.hooks.generate_prompt(True) | |
1963 | except: |
|
1790 | except: | |
1964 | self.showtraceback() |
|
1791 | self.showtraceback() | |
1965 | if self.autoindent: |
|
1792 | if self.autoindent: | |
1966 | self.rl_do_indent = True |
|
1793 | self.rl_do_indent = True | |
1967 |
|
1794 | |||
1968 | else: |
|
1795 | else: | |
1969 | try: |
|
1796 | try: | |
1970 | prompt = self.hooks.generate_prompt(False) |
|
1797 | prompt = self.hooks.generate_prompt(False) | |
1971 | except: |
|
1798 | except: | |
1972 | self.showtraceback() |
|
1799 | self.showtraceback() | |
1973 | self.write(prompt) |
|
1800 | self.write(prompt) | |
1974 |
|
1801 | |||
1975 | def interact_handle_input(self,line): |
|
1802 | def interact_handle_input(self,line): | |
1976 | """ Handle the input line (in read-eval-print loop) |
|
1803 | """ Handle the input line (in read-eval-print loop) | |
1977 |
|
1804 | |||
1978 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1805 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1979 | used in standard IPython flow. |
|
1806 | used in standard IPython flow. | |
1980 | """ |
|
1807 | """ | |
1981 | if line.lstrip() == line: |
|
1808 | if line.lstrip() == line: | |
1982 | self.shadowhist.add(line.strip()) |
|
1809 | self.shadowhist.add(line.strip()) | |
1983 | lineout = self.prefilter(line,self.more) |
|
1810 | lineout = self.prefilter(line,self.more) | |
1984 |
|
1811 | |||
1985 | if line.strip(): |
|
1812 | if line.strip(): | |
1986 | if self.more: |
|
1813 | if self.more: | |
1987 | self.input_hist_raw[-1] += '%s\n' % line |
|
1814 | self.input_hist_raw[-1] += '%s\n' % line | |
1988 | else: |
|
1815 | else: | |
1989 | self.input_hist_raw.append('%s\n' % line) |
|
1816 | self.input_hist_raw.append('%s\n' % line) | |
1990 |
|
1817 | |||
1991 |
|
1818 | |||
1992 | self.more = self.push_line(lineout) |
|
1819 | self.more = self.push_line(lineout) | |
1993 | if (self.SyntaxTB.last_syntax_error and |
|
1820 | if (self.SyntaxTB.last_syntax_error and | |
1994 | self.autoedit_syntax): |
|
1821 | self.autoedit_syntax): | |
1995 | self.edit_syntax_error() |
|
1822 | self.edit_syntax_error() | |
1996 |
|
1823 | |||
1997 | def interact_with_readline(self): |
|
1824 | def interact_with_readline(self): | |
1998 | """ Demo of using interact_handle_input, interact_prompt |
|
1825 | """ Demo of using interact_handle_input, interact_prompt | |
1999 |
|
1826 | |||
2000 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1827 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
2001 | it should work like this. |
|
1828 | it should work like this. | |
2002 | """ |
|
1829 | """ | |
2003 | self.readline_startup_hook(self.pre_readline) |
|
1830 | self.readline_startup_hook(self.pre_readline) | |
2004 | while not self.exit_now: |
|
1831 | while not self.exit_now: | |
2005 | self.interact_prompt() |
|
1832 | self.interact_prompt() | |
2006 | if self.more: |
|
1833 | if self.more: | |
2007 | self.rl_do_indent = True |
|
1834 | self.rl_do_indent = True | |
2008 | else: |
|
1835 | else: | |
2009 | self.rl_do_indent = False |
|
1836 | self.rl_do_indent = False | |
2010 | line = raw_input_original().decode(self.stdin_encoding) |
|
1837 | line = raw_input_original().decode(self.stdin_encoding) | |
2011 | self.interact_handle_input(line) |
|
1838 | self.interact_handle_input(line) | |
2012 |
|
1839 | |||
2013 | def interact(self, banner=None): |
|
1840 | def interact(self, banner=None): | |
2014 | """Closely emulate the interactive Python console.""" |
|
1841 | """Closely emulate the interactive Python console.""" | |
2015 |
|
1842 | |||
2016 | # batch run -> do not interact |
|
1843 | # batch run -> do not interact | |
2017 | if self.exit_now: |
|
1844 | if self.exit_now: | |
2018 | return |
|
1845 | return | |
2019 |
|
1846 | |||
2020 | if self.display_banner: |
|
1847 | if self.display_banner: | |
2021 | if banner is None: |
|
1848 | if banner is None: | |
2022 | banner = self.banner |
|
1849 | banner = self.banner | |
2023 | self.write(banner) |
|
1850 | self.write(banner) | |
2024 |
|
1851 | |||
2025 | more = 0 |
|
1852 | more = 0 | |
2026 |
|
1853 | |||
2027 | # Mark activity in the builtins |
|
1854 | # Mark activity in the builtins | |
2028 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1855 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
2029 |
|
1856 | |||
2030 | if self.has_readline: |
|
1857 | if self.has_readline: | |
2031 | self.readline_startup_hook(self.pre_readline) |
|
1858 | self.readline_startup_hook(self.pre_readline) | |
2032 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1859 | # exit_now is set by a call to %Exit or %Quit, through the | |
2033 | # ask_exit callback. |
|
1860 | # ask_exit callback. | |
2034 |
|
1861 | |||
2035 | while not self.exit_now: |
|
1862 | while not self.exit_now: | |
2036 | self.hooks.pre_prompt_hook() |
|
1863 | self.hooks.pre_prompt_hook() | |
2037 | if more: |
|
1864 | if more: | |
2038 | try: |
|
1865 | try: | |
2039 | prompt = self.hooks.generate_prompt(True) |
|
1866 | prompt = self.hooks.generate_prompt(True) | |
2040 | except: |
|
1867 | except: | |
2041 | self.showtraceback() |
|
1868 | self.showtraceback() | |
2042 | if self.autoindent: |
|
1869 | if self.autoindent: | |
2043 | self.rl_do_indent = True |
|
1870 | self.rl_do_indent = True | |
2044 |
|
1871 | |||
2045 | else: |
|
1872 | else: | |
2046 | try: |
|
1873 | try: | |
2047 | prompt = self.hooks.generate_prompt(False) |
|
1874 | prompt = self.hooks.generate_prompt(False) | |
2048 | except: |
|
1875 | except: | |
2049 | self.showtraceback() |
|
1876 | self.showtraceback() | |
2050 | try: |
|
1877 | try: | |
2051 | line = self.raw_input(prompt, more) |
|
1878 | line = self.raw_input(prompt, more) | |
2052 | if self.exit_now: |
|
1879 | if self.exit_now: | |
2053 | # quick exit on sys.std[in|out] close |
|
1880 | # quick exit on sys.std[in|out] close | |
2054 | break |
|
1881 | break | |
2055 | if self.autoindent: |
|
1882 | if self.autoindent: | |
2056 | self.rl_do_indent = False |
|
1883 | self.rl_do_indent = False | |
2057 |
|
1884 | |||
2058 | except KeyboardInterrupt: |
|
1885 | except KeyboardInterrupt: | |
2059 | #double-guard against keyboardinterrupts during kbdint handling |
|
1886 | #double-guard against keyboardinterrupts during kbdint handling | |
2060 | try: |
|
1887 | try: | |
2061 | self.write('\nKeyboardInterrupt\n') |
|
1888 | self.write('\nKeyboardInterrupt\n') | |
2062 | self.resetbuffer() |
|
1889 | self.resetbuffer() | |
2063 | # keep cache in sync with the prompt counter: |
|
1890 | # keep cache in sync with the prompt counter: | |
2064 | self.outputcache.prompt_count -= 1 |
|
1891 | self.outputcache.prompt_count -= 1 | |
2065 |
|
1892 | |||
2066 | if self.autoindent: |
|
1893 | if self.autoindent: | |
2067 | self.indent_current_nsp = 0 |
|
1894 | self.indent_current_nsp = 0 | |
2068 | more = 0 |
|
1895 | more = 0 | |
2069 | except KeyboardInterrupt: |
|
1896 | except KeyboardInterrupt: | |
2070 | pass |
|
1897 | pass | |
2071 | except EOFError: |
|
1898 | except EOFError: | |
2072 | if self.autoindent: |
|
1899 | if self.autoindent: | |
2073 | self.rl_do_indent = False |
|
1900 | self.rl_do_indent = False | |
2074 | self.readline_startup_hook(None) |
|
1901 | self.readline_startup_hook(None) | |
2075 | self.write('\n') |
|
1902 | self.write('\n') | |
2076 | self.exit() |
|
1903 | self.exit() | |
2077 | except bdb.BdbQuit: |
|
1904 | except bdb.BdbQuit: | |
2078 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1905 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
2079 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1906 | 'Because of how pdb handles the stack, it is impossible\n' | |
2080 | 'for IPython to properly format this particular exception.\n' |
|
1907 | 'for IPython to properly format this particular exception.\n' | |
2081 | 'IPython will resume normal operation.') |
|
1908 | 'IPython will resume normal operation.') | |
2082 | except: |
|
1909 | except: | |
2083 | # exceptions here are VERY RARE, but they can be triggered |
|
1910 | # exceptions here are VERY RARE, but they can be triggered | |
2084 | # asynchronously by signal handlers, for example. |
|
1911 | # asynchronously by signal handlers, for example. | |
2085 | self.showtraceback() |
|
1912 | self.showtraceback() | |
2086 | else: |
|
1913 | else: | |
2087 | more = self.push_line(line) |
|
1914 | more = self.push_line(line) | |
2088 | if (self.SyntaxTB.last_syntax_error and |
|
1915 | if (self.SyntaxTB.last_syntax_error and | |
2089 | self.autoedit_syntax): |
|
1916 | self.autoedit_syntax): | |
2090 | self.edit_syntax_error() |
|
1917 | self.edit_syntax_error() | |
2091 |
|
1918 | |||
2092 | # We are off again... |
|
1919 | # We are off again... | |
2093 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1920 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
2094 |
|
1921 | |||
2095 | def safe_execfile(self,fname,*where,**kw): |
|
1922 | def safe_execfile(self,fname,*where,**kw): | |
2096 | """A safe version of the builtin execfile(). |
|
1923 | """A safe version of the builtin execfile(). | |
2097 |
|
1924 | |||
2098 | This version will never throw an exception, and knows how to handle |
|
1925 | This version will never throw an exception, and knows how to handle | |
2099 | ipython logs as well. |
|
1926 | ipython logs as well. | |
2100 |
|
1927 | |||
2101 | :Parameters: |
|
1928 | :Parameters: | |
2102 | fname : string |
|
1929 | fname : string | |
2103 | Name of the file to be executed. |
|
1930 | Name of the file to be executed. | |
2104 |
|
1931 | |||
2105 | where : tuple |
|
1932 | where : tuple | |
2106 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1933 | One or two namespaces, passed to execfile() as (globals,locals). | |
2107 | If only one is given, it is passed as both. |
|
1934 | If only one is given, it is passed as both. | |
2108 |
|
1935 | |||
2109 | :Keywords: |
|
1936 | :Keywords: | |
2110 | islog : boolean (False) |
|
1937 | islog : boolean (False) | |
2111 |
|
1938 | |||
2112 | quiet : boolean (True) |
|
1939 | quiet : boolean (True) | |
2113 |
|
1940 | |||
2114 | exit_ignore : boolean (False) |
|
1941 | exit_ignore : boolean (False) | |
2115 | """ |
|
1942 | """ | |
2116 |
|
1943 | |||
2117 | def syspath_cleanup(): |
|
1944 | def syspath_cleanup(): | |
2118 | """Internal cleanup routine for sys.path.""" |
|
1945 | """Internal cleanup routine for sys.path.""" | |
2119 | if add_dname: |
|
1946 | if add_dname: | |
2120 | try: |
|
1947 | try: | |
2121 | sys.path.remove(dname) |
|
1948 | sys.path.remove(dname) | |
2122 | except ValueError: |
|
1949 | except ValueError: | |
2123 | # For some reason the user has already removed it, ignore. |
|
1950 | # For some reason the user has already removed it, ignore. | |
2124 | pass |
|
1951 | pass | |
2125 |
|
1952 | |||
2126 | fname = os.path.expanduser(fname) |
|
1953 | fname = os.path.expanduser(fname) | |
2127 |
|
1954 | |||
2128 | # Find things also in current directory. This is needed to mimic the |
|
1955 | # Find things also in current directory. This is needed to mimic the | |
2129 | # behavior of running a script from the system command line, where |
|
1956 | # behavior of running a script from the system command line, where | |
2130 | # Python inserts the script's directory into sys.path |
|
1957 | # Python inserts the script's directory into sys.path | |
2131 | dname = os.path.dirname(os.path.abspath(fname)) |
|
1958 | dname = os.path.dirname(os.path.abspath(fname)) | |
2132 | add_dname = False |
|
1959 | add_dname = False | |
2133 | if dname not in sys.path: |
|
1960 | if dname not in sys.path: | |
2134 | sys.path.insert(0,dname) |
|
1961 | sys.path.insert(0,dname) | |
2135 | add_dname = True |
|
1962 | add_dname = True | |
2136 |
|
1963 | |||
2137 | try: |
|
1964 | try: | |
2138 | xfile = open(fname) |
|
1965 | xfile = open(fname) | |
2139 | except: |
|
1966 | except: | |
2140 | print >> Term.cerr, \ |
|
1967 | print >> Term.cerr, \ | |
2141 | 'Could not open file <%s> for safe execution.' % fname |
|
1968 | 'Could not open file <%s> for safe execution.' % fname | |
2142 | syspath_cleanup() |
|
1969 | syspath_cleanup() | |
2143 | return None |
|
1970 | return None | |
2144 |
|
1971 | |||
2145 | kw.setdefault('islog',0) |
|
1972 | kw.setdefault('islog',0) | |
2146 | kw.setdefault('quiet',1) |
|
1973 | kw.setdefault('quiet',1) | |
2147 | kw.setdefault('exit_ignore',0) |
|
1974 | kw.setdefault('exit_ignore',0) | |
2148 |
|
1975 | |||
2149 | first = xfile.readline() |
|
1976 | first = xfile.readline() | |
2150 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() |
|
1977 | loghead = str(self.loghead_tpl).split('\n',1)[0].strip() | |
2151 | xfile.close() |
|
1978 | xfile.close() | |
2152 | # line by line execution |
|
1979 | # line by line execution | |
2153 | if first.startswith(loghead) or kw['islog']: |
|
1980 | if first.startswith(loghead) or kw['islog']: | |
2154 | print 'Loading log file <%s> one line at a time...' % fname |
|
1981 | print 'Loading log file <%s> one line at a time...' % fname | |
2155 | if kw['quiet']: |
|
1982 | if kw['quiet']: | |
2156 | stdout_save = sys.stdout |
|
1983 | stdout_save = sys.stdout | |
2157 | sys.stdout = StringIO.StringIO() |
|
1984 | sys.stdout = StringIO.StringIO() | |
2158 | try: |
|
1985 | try: | |
2159 | globs,locs = where[0:2] |
|
1986 | globs,locs = where[0:2] | |
2160 | except: |
|
1987 | except: | |
2161 | try: |
|
1988 | try: | |
2162 | globs = locs = where[0] |
|
1989 | globs = locs = where[0] | |
2163 | except: |
|
1990 | except: | |
2164 | globs = locs = globals() |
|
1991 | globs = locs = globals() | |
2165 | badblocks = [] |
|
1992 | badblocks = [] | |
2166 |
|
1993 | |||
2167 | # we also need to identify indented blocks of code when replaying |
|
1994 | # we also need to identify indented blocks of code when replaying | |
2168 | # logs and put them together before passing them to an exec |
|
1995 | # logs and put them together before passing them to an exec | |
2169 | # statement. This takes a bit of regexp and look-ahead work in the |
|
1996 | # statement. This takes a bit of regexp and look-ahead work in the | |
2170 | # file. It's easiest if we swallow the whole thing in memory |
|
1997 | # file. It's easiest if we swallow the whole thing in memory | |
2171 | # first, and manually walk through the lines list moving the |
|
1998 | # first, and manually walk through the lines list moving the | |
2172 | # counter ourselves. |
|
1999 | # counter ourselves. | |
2173 | indent_re = re.compile('\s+\S') |
|
2000 | indent_re = re.compile('\s+\S') | |
2174 | xfile = open(fname) |
|
2001 | xfile = open(fname) | |
2175 | filelines = xfile.readlines() |
|
2002 | filelines = xfile.readlines() | |
2176 | xfile.close() |
|
2003 | xfile.close() | |
2177 | nlines = len(filelines) |
|
2004 | nlines = len(filelines) | |
2178 | lnum = 0 |
|
2005 | lnum = 0 | |
2179 | while lnum < nlines: |
|
2006 | while lnum < nlines: | |
2180 | line = filelines[lnum] |
|
2007 | line = filelines[lnum] | |
2181 | lnum += 1 |
|
2008 | lnum += 1 | |
2182 | # don't re-insert logger status info into cache |
|
2009 | # don't re-insert logger status info into cache | |
2183 | if line.startswith('#log#'): |
|
2010 | if line.startswith('#log#'): | |
2184 | continue |
|
2011 | continue | |
2185 | else: |
|
2012 | else: | |
2186 | # build a block of code (maybe a single line) for execution |
|
2013 | # build a block of code (maybe a single line) for execution | |
2187 | block = line |
|
2014 | block = line | |
2188 | try: |
|
2015 | try: | |
2189 | next = filelines[lnum] # lnum has already incremented |
|
2016 | next = filelines[lnum] # lnum has already incremented | |
2190 | except: |
|
2017 | except: | |
2191 | next = None |
|
2018 | next = None | |
2192 | while next and indent_re.match(next): |
|
2019 | while next and indent_re.match(next): | |
2193 | block += next |
|
2020 | block += next | |
2194 | lnum += 1 |
|
2021 | lnum += 1 | |
2195 | try: |
|
2022 | try: | |
2196 | next = filelines[lnum] |
|
2023 | next = filelines[lnum] | |
2197 | except: |
|
2024 | except: | |
2198 | next = None |
|
2025 | next = None | |
2199 | # now execute the block of one or more lines |
|
2026 | # now execute the block of one or more lines | |
2200 | try: |
|
2027 | try: | |
2201 | exec block in globs,locs |
|
2028 | exec block in globs,locs | |
2202 | except SystemExit: |
|
2029 | except SystemExit: | |
2203 | pass |
|
2030 | pass | |
2204 | except: |
|
2031 | except: | |
2205 | badblocks.append(block.rstrip()) |
|
2032 | badblocks.append(block.rstrip()) | |
2206 | if kw['quiet']: # restore stdout |
|
2033 | if kw['quiet']: # restore stdout | |
2207 | sys.stdout.close() |
|
2034 | sys.stdout.close() | |
2208 | sys.stdout = stdout_save |
|
2035 | sys.stdout = stdout_save | |
2209 | print 'Finished replaying log file <%s>' % fname |
|
2036 | print 'Finished replaying log file <%s>' % fname | |
2210 | if badblocks: |
|
2037 | if badblocks: | |
2211 | print >> sys.stderr, ('\nThe following lines/blocks in file ' |
|
2038 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2212 | '<%s> reported errors:' % fname) |
|
2039 | '<%s> reported errors:' % fname) | |
2213 |
|
2040 | |||
2214 | for badline in badblocks: |
|
2041 | for badline in badblocks: | |
2215 | print >> sys.stderr, badline |
|
2042 | print >> sys.stderr, badline | |
2216 | else: # regular file execution |
|
2043 | else: # regular file execution | |
2217 | try: |
|
2044 | try: | |
2218 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
2045 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
2219 | # Work around a bug in Python for Windows. The bug was |
|
2046 | # Work around a bug in Python for Windows. The bug was | |
2220 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
2047 | # fixed in in Python 2.5 r54159 and 54158, but that's still | |
2221 | # SVN Python as of March/07. For details, see: |
|
2048 | # SVN Python as of March/07. For details, see: | |
2222 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
2049 | # http://projects.scipy.org/ipython/ipython/ticket/123 | |
2223 | try: |
|
2050 | try: | |
2224 | globs,locs = where[0:2] |
|
2051 | globs,locs = where[0:2] | |
2225 | except: |
|
2052 | except: | |
2226 | try: |
|
2053 | try: | |
2227 | globs = locs = where[0] |
|
2054 | globs = locs = where[0] | |
2228 | except: |
|
2055 | except: | |
2229 | globs = locs = globals() |
|
2056 | globs = locs = globals() | |
2230 | exec file(fname) in globs,locs |
|
2057 | exec file(fname) in globs,locs | |
2231 | else: |
|
2058 | else: | |
2232 | execfile(fname,*where) |
|
2059 | execfile(fname,*where) | |
2233 | except SyntaxError: |
|
2060 | except SyntaxError: | |
2234 | self.showsyntaxerror() |
|
2061 | self.showsyntaxerror() | |
2235 | warn('Failure executing file: <%s>' % fname) |
|
2062 | warn('Failure executing file: <%s>' % fname) | |
2236 | except SystemExit,status: |
|
2063 | except SystemExit,status: | |
2237 | # Code that correctly sets the exit status flag to success (0) |
|
2064 | # Code that correctly sets the exit status flag to success (0) | |
2238 | # shouldn't be bothered with a traceback. Note that a plain |
|
2065 | # shouldn't be bothered with a traceback. Note that a plain | |
2239 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
2066 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
2240 | # will still get a traceback. Note that the structure of the |
|
2067 | # will still get a traceback. Note that the structure of the | |
2241 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
2068 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
2242 | # the checks must be done in a version-dependent way. |
|
2069 | # the checks must be done in a version-dependent way. | |
2243 | show = False |
|
2070 | show = False | |
2244 |
|
2071 | |||
2245 | if sys.version_info[:2] > (2,5): |
|
2072 | if sys.version_info[:2] > (2,5): | |
2246 | if status.message!=0 and not kw['exit_ignore']: |
|
2073 | if status.message!=0 and not kw['exit_ignore']: | |
2247 | show = True |
|
2074 | show = True | |
2248 | else: |
|
2075 | else: | |
2249 | if status.code and not kw['exit_ignore']: |
|
2076 | if status.code and not kw['exit_ignore']: | |
2250 | show = True |
|
2077 | show = True | |
2251 | if show: |
|
2078 | if show: | |
2252 | self.showtraceback() |
|
2079 | self.showtraceback() | |
2253 | warn('Failure executing file: <%s>' % fname) |
|
2080 | warn('Failure executing file: <%s>' % fname) | |
2254 | except: |
|
2081 | except: | |
2255 | self.showtraceback() |
|
2082 | self.showtraceback() | |
2256 | warn('Failure executing file: <%s>' % fname) |
|
2083 | warn('Failure executing file: <%s>' % fname) | |
2257 |
|
2084 | |||
2258 | syspath_cleanup() |
|
2085 | syspath_cleanup() | |
2259 |
|
2086 | |||
2260 | def cleanup_ipy_script(self, script): |
|
2087 | def cleanup_ipy_script(self, script): | |
2261 | """Make a script safe for self.runlines() |
|
2088 | """Make a script safe for self.runlines() | |
2262 |
|
2089 | |||
2263 | Notes |
|
2090 | Notes | |
2264 | ----- |
|
2091 | ----- | |
2265 | This was copied over from the old ipapi and probably can be done |
|
2092 | This was copied over from the old ipapi and probably can be done | |
2266 | away with once we move to block based interpreter. |
|
2093 | away with once we move to block based interpreter. | |
2267 |
|
2094 | |||
2268 | - Removes empty lines Suffixes all indented blocks that end with |
|
2095 | - Removes empty lines Suffixes all indented blocks that end with | |
2269 | - unindented lines with empty lines |
|
2096 | - unindented lines with empty lines | |
2270 | """ |
|
2097 | """ | |
2271 |
|
2098 | |||
2272 | res = [] |
|
2099 | res = [] | |
2273 | lines = script.splitlines() |
|
2100 | lines = script.splitlines() | |
2274 |
|
2101 | |||
2275 | level = 0 |
|
2102 | level = 0 | |
2276 | for l in lines: |
|
2103 | for l in lines: | |
2277 | lstripped = l.lstrip() |
|
2104 | lstripped = l.lstrip() | |
2278 | stripped = l.strip() |
|
2105 | stripped = l.strip() | |
2279 | if not stripped: |
|
2106 | if not stripped: | |
2280 | continue |
|
2107 | continue | |
2281 | newlevel = len(l) - len(lstripped) |
|
2108 | newlevel = len(l) - len(lstripped) | |
2282 | def is_secondary_block_start(s): |
|
2109 | def is_secondary_block_start(s): | |
2283 | if not s.endswith(':'): |
|
2110 | if not s.endswith(':'): | |
2284 | return False |
|
2111 | return False | |
2285 | if (s.startswith('elif') or |
|
2112 | if (s.startswith('elif') or | |
2286 | s.startswith('else') or |
|
2113 | s.startswith('else') or | |
2287 | s.startswith('except') or |
|
2114 | s.startswith('except') or | |
2288 | s.startswith('finally')): |
|
2115 | s.startswith('finally')): | |
2289 | return True |
|
2116 | return True | |
2290 |
|
2117 | |||
2291 | if level > 0 and newlevel == 0 and \ |
|
2118 | if level > 0 and newlevel == 0 and \ | |
2292 | not is_secondary_block_start(stripped): |
|
2119 | not is_secondary_block_start(stripped): | |
2293 | # add empty line |
|
2120 | # add empty line | |
2294 | res.append('') |
|
2121 | res.append('') | |
2295 |
|
2122 | |||
2296 | res.append(l) |
|
2123 | res.append(l) | |
2297 | level = newlevel |
|
2124 | level = newlevel | |
2298 | return '\n'.join(res) + '\n' |
|
2125 | return '\n'.join(res) + '\n' | |
2299 |
|
2126 | |||
2300 | def runlines(self, lines, clean=False): |
|
2127 | def runlines(self, lines, clean=False): | |
2301 | """Run a string of one or more lines of source. |
|
2128 | """Run a string of one or more lines of source. | |
2302 |
|
2129 | |||
2303 | This method is capable of running a string containing multiple source |
|
2130 | This method is capable of running a string containing multiple source | |
2304 | lines, as if they had been entered at the IPython prompt. Since it |
|
2131 | lines, as if they had been entered at the IPython prompt. Since it | |
2305 | exposes IPython's processing machinery, the given strings can contain |
|
2132 | exposes IPython's processing machinery, the given strings can contain | |
2306 | magic calls (%magic), special shell access (!cmd), etc. |
|
2133 | magic calls (%magic), special shell access (!cmd), etc. | |
2307 | """ |
|
2134 | """ | |
2308 |
|
2135 | |||
2309 | if isinstance(lines, (list, tuple)): |
|
2136 | if isinstance(lines, (list, tuple)): | |
2310 | lines = '\n'.join(lines) |
|
2137 | lines = '\n'.join(lines) | |
2311 |
|
2138 | |||
2312 | if clean: |
|
2139 | if clean: | |
2313 | lines = self.cleanup_ipy_script(lines) |
|
2140 | lines = self.cleanup_ipy_script(lines) | |
2314 |
|
2141 | |||
2315 | # We must start with a clean buffer, in case this is run from an |
|
2142 | # We must start with a clean buffer, in case this is run from an | |
2316 | # interactive IPython session (via a magic, for example). |
|
2143 | # interactive IPython session (via a magic, for example). | |
2317 | self.resetbuffer() |
|
2144 | self.resetbuffer() | |
2318 | lines = lines.splitlines() |
|
2145 | lines = lines.splitlines() | |
2319 | more = 0 |
|
2146 | more = 0 | |
2320 |
|
2147 | |||
2321 | with nested(self.builtin_trap, self.display_trap): |
|
2148 | with nested(self.builtin_trap, self.display_trap): | |
2322 | for line in lines: |
|
2149 | for line in lines: | |
2323 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2150 | # skip blank lines so we don't mess up the prompt counter, but do | |
2324 | # NOT skip even a blank line if we are in a code block (more is |
|
2151 | # NOT skip even a blank line if we are in a code block (more is | |
2325 | # true) |
|
2152 | # true) | |
2326 |
|
2153 | |||
2327 | if line or more: |
|
2154 | if line or more: | |
2328 | # push to raw history, so hist line numbers stay in sync |
|
2155 | # push to raw history, so hist line numbers stay in sync | |
2329 | self.input_hist_raw.append("# " + line + "\n") |
|
2156 | self.input_hist_raw.append("# " + line + "\n") | |
2330 | more = self.push_line(self.prefilter(line,more)) |
|
2157 | more = self.push_line(self.prefilter(line,more)) | |
2331 | # IPython's runsource returns None if there was an error |
|
2158 | # IPython's runsource returns None if there was an error | |
2332 | # compiling the code. This allows us to stop processing right |
|
2159 | # compiling the code. This allows us to stop processing right | |
2333 | # away, so the user gets the error message at the right place. |
|
2160 | # away, so the user gets the error message at the right place. | |
2334 | if more is None: |
|
2161 | if more is None: | |
2335 | break |
|
2162 | break | |
2336 | else: |
|
2163 | else: | |
2337 | self.input_hist_raw.append("\n") |
|
2164 | self.input_hist_raw.append("\n") | |
2338 | # final newline in case the input didn't have it, so that the code |
|
2165 | # final newline in case the input didn't have it, so that the code | |
2339 | # actually does get executed |
|
2166 | # actually does get executed | |
2340 | if more: |
|
2167 | if more: | |
2341 | self.push_line('\n') |
|
2168 | self.push_line('\n') | |
2342 |
|
2169 | |||
2343 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2170 | def runsource(self, source, filename='<input>', symbol='single'): | |
2344 | """Compile and run some source in the interpreter. |
|
2171 | """Compile and run some source in the interpreter. | |
2345 |
|
2172 | |||
2346 | Arguments are as for compile_command(). |
|
2173 | Arguments are as for compile_command(). | |
2347 |
|
2174 | |||
2348 | One several things can happen: |
|
2175 | One several things can happen: | |
2349 |
|
2176 | |||
2350 | 1) The input is incorrect; compile_command() raised an |
|
2177 | 1) The input is incorrect; compile_command() raised an | |
2351 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2178 | exception (SyntaxError or OverflowError). A syntax traceback | |
2352 | will be printed by calling the showsyntaxerror() method. |
|
2179 | will be printed by calling the showsyntaxerror() method. | |
2353 |
|
2180 | |||
2354 | 2) The input is incomplete, and more input is required; |
|
2181 | 2) The input is incomplete, and more input is required; | |
2355 | compile_command() returned None. Nothing happens. |
|
2182 | compile_command() returned None. Nothing happens. | |
2356 |
|
2183 | |||
2357 | 3) The input is complete; compile_command() returned a code |
|
2184 | 3) The input is complete; compile_command() returned a code | |
2358 | object. The code is executed by calling self.runcode() (which |
|
2185 | object. The code is executed by calling self.runcode() (which | |
2359 | also handles run-time exceptions, except for SystemExit). |
|
2186 | also handles run-time exceptions, except for SystemExit). | |
2360 |
|
2187 | |||
2361 | The return value is: |
|
2188 | The return value is: | |
2362 |
|
2189 | |||
2363 | - True in case 2 |
|
2190 | - True in case 2 | |
2364 |
|
2191 | |||
2365 | - False in the other cases, unless an exception is raised, where |
|
2192 | - False in the other cases, unless an exception is raised, where | |
2366 | None is returned instead. This can be used by external callers to |
|
2193 | None is returned instead. This can be used by external callers to | |
2367 | know whether to continue feeding input or not. |
|
2194 | know whether to continue feeding input or not. | |
2368 |
|
2195 | |||
2369 | The return value can be used to decide whether to use sys.ps1 or |
|
2196 | The return value can be used to decide whether to use sys.ps1 or | |
2370 | sys.ps2 to prompt the next line.""" |
|
2197 | sys.ps2 to prompt the next line.""" | |
2371 |
|
2198 | |||
2372 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2199 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2373 | # this allows execution of indented pasted code. It is tempting |
|
2200 | # this allows execution of indented pasted code. It is tempting | |
2374 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2201 | # to add '\n' at the end of source to run commands like ' a=1' | |
2375 | # directly, but this fails for more complicated scenarios |
|
2202 | # directly, but this fails for more complicated scenarios | |
2376 | source=source.encode(self.stdin_encoding) |
|
2203 | source=source.encode(self.stdin_encoding) | |
2377 | if source[:1] in [' ', '\t']: |
|
2204 | if source[:1] in [' ', '\t']: | |
2378 | source = 'if 1:\n%s' % source |
|
2205 | source = 'if 1:\n%s' % source | |
2379 |
|
2206 | |||
2380 | try: |
|
2207 | try: | |
2381 | code = self.compile(source,filename,symbol) |
|
2208 | code = self.compile(source,filename,symbol) | |
2382 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2209 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2383 | # Case 1 |
|
2210 | # Case 1 | |
2384 | self.showsyntaxerror(filename) |
|
2211 | self.showsyntaxerror(filename) | |
2385 | return None |
|
2212 | return None | |
2386 |
|
2213 | |||
2387 | if code is None: |
|
2214 | if code is None: | |
2388 | # Case 2 |
|
2215 | # Case 2 | |
2389 | return True |
|
2216 | return True | |
2390 |
|
2217 | |||
2391 | # Case 3 |
|
2218 | # Case 3 | |
2392 | # We store the code object so that threaded shells and |
|
2219 | # We store the code object so that threaded shells and | |
2393 | # custom exception handlers can access all this info if needed. |
|
2220 | # custom exception handlers can access all this info if needed. | |
2394 | # The source corresponding to this can be obtained from the |
|
2221 | # The source corresponding to this can be obtained from the | |
2395 | # buffer attribute as '\n'.join(self.buffer). |
|
2222 | # buffer attribute as '\n'.join(self.buffer). | |
2396 | self.code_to_run = code |
|
2223 | self.code_to_run = code | |
2397 | # now actually execute the code object |
|
2224 | # now actually execute the code object | |
2398 | if self.runcode(code) == 0: |
|
2225 | if self.runcode(code) == 0: | |
2399 | return False |
|
2226 | return False | |
2400 | else: |
|
2227 | else: | |
2401 | return None |
|
2228 | return None | |
2402 |
|
2229 | |||
2403 | def runcode(self,code_obj): |
|
2230 | def runcode(self,code_obj): | |
2404 | """Execute a code object. |
|
2231 | """Execute a code object. | |
2405 |
|
2232 | |||
2406 | When an exception occurs, self.showtraceback() is called to display a |
|
2233 | When an exception occurs, self.showtraceback() is called to display a | |
2407 | traceback. |
|
2234 | traceback. | |
2408 |
|
2235 | |||
2409 | Return value: a flag indicating whether the code to be run completed |
|
2236 | Return value: a flag indicating whether the code to be run completed | |
2410 | successfully: |
|
2237 | successfully: | |
2411 |
|
2238 | |||
2412 | - 0: successful execution. |
|
2239 | - 0: successful execution. | |
2413 | - 1: an error occurred. |
|
2240 | - 1: an error occurred. | |
2414 | """ |
|
2241 | """ | |
2415 |
|
2242 | |||
2416 | # Set our own excepthook in case the user code tries to call it |
|
2243 | # Set our own excepthook in case the user code tries to call it | |
2417 | # directly, so that the IPython crash handler doesn't get triggered |
|
2244 | # directly, so that the IPython crash handler doesn't get triggered | |
2418 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2245 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2419 |
|
2246 | |||
2420 | # we save the original sys.excepthook in the instance, in case config |
|
2247 | # we save the original sys.excepthook in the instance, in case config | |
2421 | # code (such as magics) needs access to it. |
|
2248 | # code (such as magics) needs access to it. | |
2422 | self.sys_excepthook = old_excepthook |
|
2249 | self.sys_excepthook = old_excepthook | |
2423 | outflag = 1 # happens in more places, so it's easier as default |
|
2250 | outflag = 1 # happens in more places, so it's easier as default | |
2424 | try: |
|
2251 | try: | |
2425 | try: |
|
2252 | try: | |
2426 | self.hooks.pre_runcode_hook() |
|
2253 | self.hooks.pre_runcode_hook() | |
2427 | exec code_obj in self.user_global_ns, self.user_ns |
|
2254 | exec code_obj in self.user_global_ns, self.user_ns | |
2428 | finally: |
|
2255 | finally: | |
2429 | # Reset our crash handler in place |
|
2256 | # Reset our crash handler in place | |
2430 | sys.excepthook = old_excepthook |
|
2257 | sys.excepthook = old_excepthook | |
2431 | except SystemExit: |
|
2258 | except SystemExit: | |
2432 | self.resetbuffer() |
|
2259 | self.resetbuffer() | |
2433 | self.showtraceback() |
|
2260 | self.showtraceback() | |
2434 | warn("Type %exit or %quit to exit IPython " |
|
2261 | warn("Type %exit or %quit to exit IPython " | |
2435 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
2262 | "(%Exit or %Quit do so unconditionally).",level=1) | |
2436 | except self.custom_exceptions: |
|
2263 | except self.custom_exceptions: | |
2437 | etype,value,tb = sys.exc_info() |
|
2264 | etype,value,tb = sys.exc_info() | |
2438 | self.CustomTB(etype,value,tb) |
|
2265 | self.CustomTB(etype,value,tb) | |
2439 | except: |
|
2266 | except: | |
2440 | self.showtraceback() |
|
2267 | self.showtraceback() | |
2441 | else: |
|
2268 | else: | |
2442 | outflag = 0 |
|
2269 | outflag = 0 | |
2443 | if softspace(sys.stdout, 0): |
|
2270 | if softspace(sys.stdout, 0): | |
2444 |
|
2271 | |||
2445 | # Flush out code object which has been run (and source) |
|
2272 | # Flush out code object which has been run (and source) | |
2446 | self.code_to_run = None |
|
2273 | self.code_to_run = None | |
2447 | return outflag |
|
2274 | return outflag | |
2448 |
|
2275 | |||
2449 | def push_line(self, line): |
|
2276 | def push_line(self, line): | |
2450 | """Push a line to the interpreter. |
|
2277 | """Push a line to the interpreter. | |
2451 |
|
2278 | |||
2452 | The line should not have a trailing newline; it may have |
|
2279 | The line should not have a trailing newline; it may have | |
2453 | internal newlines. The line is appended to a buffer and the |
|
2280 | internal newlines. The line is appended to a buffer and the | |
2454 | interpreter's runsource() method is called with the |
|
2281 | interpreter's runsource() method is called with the | |
2455 | concatenated contents of the buffer as source. If this |
|
2282 | concatenated contents of the buffer as source. If this | |
2456 | indicates that the command was executed or invalid, the buffer |
|
2283 | indicates that the command was executed or invalid, the buffer | |
2457 | is reset; otherwise, the command is incomplete, and the buffer |
|
2284 | is reset; otherwise, the command is incomplete, and the buffer | |
2458 | is left as it was after the line was appended. The return |
|
2285 | is left as it was after the line was appended. The return | |
2459 | value is 1 if more input is required, 0 if the line was dealt |
|
2286 | value is 1 if more input is required, 0 if the line was dealt | |
2460 | with in some way (this is the same as runsource()). |
|
2287 | with in some way (this is the same as runsource()). | |
2461 | """ |
|
2288 | """ | |
2462 |
|
2289 | |||
2463 | # autoindent management should be done here, and not in the |
|
2290 | # autoindent management should be done here, and not in the | |
2464 | # interactive loop, since that one is only seen by keyboard input. We |
|
2291 | # interactive loop, since that one is only seen by keyboard input. We | |
2465 | # need this done correctly even for code run via runlines (which uses |
|
2292 | # need this done correctly even for code run via runlines (which uses | |
2466 | # push). |
|
2293 | # push). | |
2467 |
|
2294 | |||
2468 | #print 'push line: <%s>' % line # dbg |
|
2295 | #print 'push line: <%s>' % line # dbg | |
2469 | for subline in line.splitlines(): |
|
2296 | for subline in line.splitlines(): | |
2470 | self._autoindent_update(subline) |
|
2297 | self._autoindent_update(subline) | |
2471 | self.buffer.append(line) |
|
2298 | self.buffer.append(line) | |
2472 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2299 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2473 | if not more: |
|
2300 | if not more: | |
2474 | self.resetbuffer() |
|
2301 | self.resetbuffer() | |
2475 | return more |
|
2302 | return more | |
2476 |
|
2303 | |||
2477 | def _autoindent_update(self,line): |
|
2304 | def _autoindent_update(self,line): | |
2478 | """Keep track of the indent level.""" |
|
2305 | """Keep track of the indent level.""" | |
2479 |
|
2306 | |||
2480 | #debugx('line') |
|
2307 | #debugx('line') | |
2481 | #debugx('self.indent_current_nsp') |
|
2308 | #debugx('self.indent_current_nsp') | |
2482 | if self.autoindent: |
|
2309 | if self.autoindent: | |
2483 | if line: |
|
2310 | if line: | |
2484 | inisp = num_ini_spaces(line) |
|
2311 | inisp = num_ini_spaces(line) | |
2485 | if inisp < self.indent_current_nsp: |
|
2312 | if inisp < self.indent_current_nsp: | |
2486 | self.indent_current_nsp = inisp |
|
2313 | self.indent_current_nsp = inisp | |
2487 |
|
2314 | |||
2488 | if line[-1] == ':': |
|
2315 | if line[-1] == ':': | |
2489 | self.indent_current_nsp += 4 |
|
2316 | self.indent_current_nsp += 4 | |
2490 | elif dedent_re.match(line): |
|
2317 | elif dedent_re.match(line): | |
2491 | self.indent_current_nsp -= 4 |
|
2318 | self.indent_current_nsp -= 4 | |
2492 | else: |
|
2319 | else: | |
2493 | self.indent_current_nsp = 0 |
|
2320 | self.indent_current_nsp = 0 | |
2494 |
|
2321 | |||
2495 | def split_user_input(self, line): |
|
2322 | def split_user_input(self, line): | |
2496 | # This is really a hold-over to support ipapi and some extensions |
|
2323 | # This is really a hold-over to support ipapi and some extensions | |
2497 | return prefilter.splitUserInput(line) |
|
2324 | return prefilter.splitUserInput(line) | |
2498 |
|
2325 | |||
2499 | def resetbuffer(self): |
|
2326 | def resetbuffer(self): | |
2500 | """Reset the input buffer.""" |
|
2327 | """Reset the input buffer.""" | |
2501 | self.buffer[:] = [] |
|
2328 | self.buffer[:] = [] | |
2502 |
|
2329 | |||
2503 | def raw_input(self,prompt='',continue_prompt=False): |
|
2330 | def raw_input(self,prompt='',continue_prompt=False): | |
2504 | """Write a prompt and read a line. |
|
2331 | """Write a prompt and read a line. | |
2505 |
|
2332 | |||
2506 | The returned line does not include the trailing newline. |
|
2333 | The returned line does not include the trailing newline. | |
2507 | When the user enters the EOF key sequence, EOFError is raised. |
|
2334 | When the user enters the EOF key sequence, EOFError is raised. | |
2508 |
|
2335 | |||
2509 | Optional inputs: |
|
2336 | Optional inputs: | |
2510 |
|
2337 | |||
2511 | - prompt(''): a string to be printed to prompt the user. |
|
2338 | - prompt(''): a string to be printed to prompt the user. | |
2512 |
|
2339 | |||
2513 | - continue_prompt(False): whether this line is the first one or a |
|
2340 | - continue_prompt(False): whether this line is the first one or a | |
2514 | continuation in a sequence of inputs. |
|
2341 | continuation in a sequence of inputs. | |
2515 | """ |
|
2342 | """ | |
2516 |
|
2343 | growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) | ||
2517 | # Code run by the user may have modified the readline completer state. |
|
2344 | # Code run by the user may have modified the readline completer state. | |
2518 | # We must ensure that our completer is back in place. |
|
2345 | # We must ensure that our completer is back in place. | |
|
2346 | ||||
2519 | if self.has_readline: |
|
2347 | if self.has_readline: | |
2520 | self.set_completer() |
|
2348 | self.set_completer() | |
2521 |
|
2349 | |||
2522 | try: |
|
2350 | try: | |
2523 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2351 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2524 | except ValueError: |
|
2352 | except ValueError: | |
2525 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2353 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2526 | " or sys.stdout.close()!\nExiting IPython!") |
|
2354 | " or sys.stdout.close()!\nExiting IPython!") | |
2527 | self.ask_exit() |
|
2355 | self.ask_exit() | |
2528 | return "" |
|
2356 | return "" | |
2529 |
|
2357 | |||
2530 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2358 | # Try to be reasonably smart about not re-indenting pasted input more | |
2531 | # than necessary. We do this by trimming out the auto-indent initial |
|
2359 | # than necessary. We do this by trimming out the auto-indent initial | |
2532 | # spaces, if the user's actual input started itself with whitespace. |
|
2360 | # spaces, if the user's actual input started itself with whitespace. | |
2533 | #debugx('self.buffer[-1]') |
|
2361 | #debugx('self.buffer[-1]') | |
2534 |
|
2362 | |||
2535 | if self.autoindent: |
|
2363 | if self.autoindent: | |
2536 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2364 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2537 | line = line[self.indent_current_nsp:] |
|
2365 | line = line[self.indent_current_nsp:] | |
2538 | self.indent_current_nsp = 0 |
|
2366 | self.indent_current_nsp = 0 | |
2539 |
|
2367 | |||
2540 | # store the unfiltered input before the user has any chance to modify |
|
2368 | # store the unfiltered input before the user has any chance to modify | |
2541 | # it. |
|
2369 | # it. | |
2542 | if line.strip(): |
|
2370 | if line.strip(): | |
2543 | if continue_prompt: |
|
2371 | if continue_prompt: | |
2544 | self.input_hist_raw[-1] += '%s\n' % line |
|
2372 | self.input_hist_raw[-1] += '%s\n' % line | |
2545 | if self.has_readline: # and some config option is set? |
|
2373 | if self.has_readline: # and some config option is set? | |
2546 | try: |
|
2374 | try: | |
2547 | histlen = self.readline.get_current_history_length() |
|
2375 | histlen = self.readline.get_current_history_length() | |
2548 | if histlen > 1: |
|
2376 | if histlen > 1: | |
2549 | newhist = self.input_hist_raw[-1].rstrip() |
|
2377 | newhist = self.input_hist_raw[-1].rstrip() | |
2550 | self.readline.remove_history_item(histlen-1) |
|
2378 | self.readline.remove_history_item(histlen-1) | |
2551 | self.readline.replace_history_item(histlen-2, |
|
2379 | self.readline.replace_history_item(histlen-2, | |
2552 | newhist.encode(self.stdin_encoding)) |
|
2380 | newhist.encode(self.stdin_encoding)) | |
2553 | except AttributeError: |
|
2381 | except AttributeError: | |
2554 | pass # re{move,place}_history_item are new in 2.4. |
|
2382 | pass # re{move,place}_history_item are new in 2.4. | |
2555 | else: |
|
2383 | else: | |
2556 | self.input_hist_raw.append('%s\n' % line) |
|
2384 | self.input_hist_raw.append('%s\n' % line) | |
2557 | # only entries starting at first column go to shadow history |
|
2385 | # only entries starting at first column go to shadow history | |
2558 | if line.lstrip() == line: |
|
2386 | if line.lstrip() == line: | |
2559 | self.shadowhist.add(line.strip()) |
|
2387 | self.shadowhist.add(line.strip()) | |
2560 | elif not continue_prompt: |
|
2388 | elif not continue_prompt: | |
2561 | self.input_hist_raw.append('\n') |
|
2389 | self.input_hist_raw.append('\n') | |
2562 | try: |
|
2390 | try: | |
2563 | lineout = self.prefilter(line,continue_prompt) |
|
2391 | lineout = self.prefilter(line,continue_prompt) | |
2564 | except: |
|
2392 | except: | |
2565 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2393 | # blanket except, in case a user-defined prefilter crashes, so it | |
2566 | # can't take all of ipython with it. |
|
2394 | # can't take all of ipython with it. | |
2567 | self.showtraceback() |
|
2395 | self.showtraceback() | |
2568 | return '' |
|
2396 | return '' | |
2569 | else: |
|
2397 | else: | |
2570 | return lineout |
|
2398 | return lineout | |
2571 |
|
2399 | |||
2572 | # def init_exec_commands(self): |
|
2400 | # def init_exec_commands(self): | |
2573 | # for cmd in self.config.EXECUTE: |
|
2401 | # for cmd in self.config.EXECUTE: | |
2574 | # print "execute:", cmd |
|
2402 | # print "execute:", cmd | |
2575 | # self.api.runlines(cmd) |
|
2403 | # self.api.runlines(cmd) | |
2576 | # |
|
2404 | # | |
2577 | # batchrun = False |
|
2405 | # batchrun = False | |
2578 | # if self.config.has_key('EXECFILE'): |
|
2406 | # if self.config.has_key('EXECFILE'): | |
2579 | # for batchfile in [path(arg) for arg in self.config.EXECFILE |
|
2407 | # for batchfile in [path(arg) for arg in self.config.EXECFILE | |
2580 | # if arg.lower().endswith('.ipy')]: |
|
2408 | # if arg.lower().endswith('.ipy')]: | |
2581 | # if not batchfile.isfile(): |
|
2409 | # if not batchfile.isfile(): | |
2582 | # print "No such batch file:", batchfile |
|
2410 | # print "No such batch file:", batchfile | |
2583 | # continue |
|
2411 | # continue | |
2584 | # self.api.runlines(batchfile.text()) |
|
2412 | # self.api.runlines(batchfile.text()) | |
2585 | # batchrun = True |
|
2413 | # batchrun = True | |
2586 | # # without -i option, exit after running the batch file |
|
2414 | # # without -i option, exit after running the batch file | |
2587 | # if batchrun and not self.interactive: |
|
2415 | # if batchrun and not self.interactive: | |
2588 | # self.ask_exit() |
|
2416 | # self.ask_exit() | |
2589 |
|
2417 | |||
2590 | # def load(self, mod): |
|
2418 | # def load(self, mod): | |
2591 | # """ Load an extension. |
|
2419 | # """ Load an extension. | |
2592 | # |
|
2420 | # | |
2593 | # Some modules should (or must) be 'load()':ed, rather than just imported. |
|
2421 | # Some modules should (or must) be 'load()':ed, rather than just imported. | |
2594 | # |
|
2422 | # | |
2595 | # Loading will do: |
|
2423 | # Loading will do: | |
2596 | # |
|
2424 | # | |
2597 | # - run init_ipython(ip) |
|
2425 | # - run init_ipython(ip) | |
2598 | # - run ipython_firstrun(ip) |
|
2426 | # - run ipython_firstrun(ip) | |
2599 | # """ |
|
2427 | # """ | |
2600 | # |
|
2428 | # | |
2601 | # if mod in self.extensions: |
|
2429 | # if mod in self.extensions: | |
2602 | # # just to make sure we don't init it twice |
|
2430 | # # just to make sure we don't init it twice | |
2603 | # # note that if you 'load' a module that has already been |
|
2431 | # # note that if you 'load' a module that has already been | |
2604 | # # imported, init_ipython gets run anyway |
|
2432 | # # imported, init_ipython gets run anyway | |
2605 | # |
|
2433 | # | |
2606 | # return self.extensions[mod] |
|
2434 | # return self.extensions[mod] | |
2607 | # __import__(mod) |
|
2435 | # __import__(mod) | |
2608 | # m = sys.modules[mod] |
|
2436 | # m = sys.modules[mod] | |
2609 | # if hasattr(m,'init_ipython'): |
|
2437 | # if hasattr(m,'init_ipython'): | |
2610 | # m.init_ipython(self) |
|
2438 | # m.init_ipython(self) | |
2611 | # |
|
2439 | # | |
2612 | # if hasattr(m,'ipython_firstrun'): |
|
2440 | # if hasattr(m,'ipython_firstrun'): | |
2613 | # already_loaded = self.db.get('firstrun_done', set()) |
|
2441 | # already_loaded = self.db.get('firstrun_done', set()) | |
2614 | # if mod not in already_loaded: |
|
2442 | # if mod not in already_loaded: | |
2615 | # m.ipython_firstrun(self) |
|
2443 | # m.ipython_firstrun(self) | |
2616 | # already_loaded.add(mod) |
|
2444 | # already_loaded.add(mod) | |
2617 | # self.db['firstrun_done'] = already_loaded |
|
2445 | # self.db['firstrun_done'] = already_loaded | |
2618 | # |
|
2446 | # | |
2619 | # self.extensions[mod] = m |
|
2447 | # self.extensions[mod] = m | |
2620 | # return m |
|
2448 | # return m | |
2621 |
|
2449 | |||
2622 | #------------------------------------------------------------------------- |
|
2450 | #------------------------------------------------------------------------- | |
2623 | # Things related to the prefilter |
|
2451 | # Things related to the prefilter | |
2624 | #------------------------------------------------------------------------- |
|
2452 | #------------------------------------------------------------------------- | |
2625 |
|
2453 | |||
2626 | def init_handlers(self): |
|
2454 | def init_handlers(self): | |
2627 | # escapes for automatic behavior on the command line |
|
2455 | # escapes for automatic behavior on the command line | |
2628 | self.ESC_SHELL = '!' |
|
2456 | self.ESC_SHELL = '!' | |
2629 | self.ESC_SH_CAP = '!!' |
|
2457 | self.ESC_SH_CAP = '!!' | |
2630 | self.ESC_HELP = '?' |
|
2458 | self.ESC_HELP = '?' | |
2631 | self.ESC_MAGIC = '%' |
|
2459 | self.ESC_MAGIC = '%' | |
2632 | self.ESC_QUOTE = ',' |
|
2460 | self.ESC_QUOTE = ',' | |
2633 | self.ESC_QUOTE2 = ';' |
|
2461 | self.ESC_QUOTE2 = ';' | |
2634 | self.ESC_PAREN = '/' |
|
2462 | self.ESC_PAREN = '/' | |
2635 |
|
2463 | |||
2636 | # And their associated handlers |
|
2464 | # And their associated handlers | |
2637 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, |
|
2465 | self.esc_handlers = {self.ESC_PAREN : self.handle_auto, | |
2638 | self.ESC_QUOTE : self.handle_auto, |
|
2466 | self.ESC_QUOTE : self.handle_auto, | |
2639 | self.ESC_QUOTE2 : self.handle_auto, |
|
2467 | self.ESC_QUOTE2 : self.handle_auto, | |
2640 | self.ESC_MAGIC : self.handle_magic, |
|
2468 | self.ESC_MAGIC : self.handle_magic, | |
2641 | self.ESC_HELP : self.handle_help, |
|
2469 | self.ESC_HELP : self.handle_help, | |
2642 | self.ESC_SHELL : self.handle_shell_escape, |
|
2470 | self.ESC_SHELL : self.handle_shell_escape, | |
2643 | self.ESC_SH_CAP : self.handle_shell_escape, |
|
2471 | self.ESC_SH_CAP : self.handle_shell_escape, | |
2644 | } |
|
2472 | } | |
2645 |
|
2473 | |||
2646 | def _prefilter(self, line, continue_prompt): |
|
2474 | def _prefilter(self, line, continue_prompt): | |
2647 | """Calls different preprocessors, depending on the form of line.""" |
|
2475 | """Calls different preprocessors, depending on the form of line.""" | |
2648 |
|
2476 | |||
2649 | # All handlers *must* return a value, even if it's blank (''). |
|
2477 | # All handlers *must* return a value, even if it's blank (''). | |
2650 |
|
2478 | |||
2651 | # Lines are NOT logged here. Handlers should process the line as |
|
2479 | # Lines are NOT logged here. Handlers should process the line as | |
2652 | # needed, update the cache AND log it (so that the input cache array |
|
2480 | # needed, update the cache AND log it (so that the input cache array | |
2653 | # stays synced). |
|
2481 | # stays synced). | |
2654 |
|
2482 | |||
2655 | #..................................................................... |
|
2483 | #..................................................................... | |
2656 | # Code begins |
|
2484 | # Code begins | |
2657 |
|
2485 | |||
2658 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg |
|
2486 | #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg | |
2659 |
|
2487 | |||
2660 | # save the line away in case we crash, so the post-mortem handler can |
|
2488 | # save the line away in case we crash, so the post-mortem handler can | |
2661 | # record it |
|
2489 | # record it | |
|
2490 | growl.notify("_prefilter: ", "line = %s\ncontinue_prompt = %s" % (line, continue_prompt)) | |||
|
2491 | ||||
2662 | self._last_input_line = line |
|
2492 | self._last_input_line = line | |
2663 |
|
2493 | |||
2664 | #print '***line: <%s>' % line # dbg |
|
2494 | #print '***line: <%s>' % line # dbg | |
2665 |
|
2495 | |||
2666 | if not line: |
|
2496 | if not line: | |
2667 | # Return immediately on purely empty lines, so that if the user |
|
2497 | # Return immediately on purely empty lines, so that if the user | |
2668 | # previously typed some whitespace that started a continuation |
|
2498 | # previously typed some whitespace that started a continuation | |
2669 | # prompt, he can break out of that loop with just an empty line. |
|
2499 | # prompt, he can break out of that loop with just an empty line. | |
2670 | # This is how the default python prompt works. |
|
2500 | # This is how the default python prompt works. | |
2671 |
|
2501 | |||
2672 | # Only return if the accumulated input buffer was just whitespace! |
|
2502 | # Only return if the accumulated input buffer was just whitespace! | |
2673 | if ''.join(self.buffer).isspace(): |
|
2503 | if ''.join(self.buffer).isspace(): | |
2674 | self.buffer[:] = [] |
|
2504 | self.buffer[:] = [] | |
2675 | return '' |
|
2505 | return '' | |
2676 |
|
2506 | |||
2677 | line_info = prefilter.LineInfo(line, continue_prompt) |
|
2507 | line_info = prefilter.LineInfo(line, continue_prompt) | |
2678 |
|
2508 | |||
2679 | # the input history needs to track even empty lines |
|
2509 | # the input history needs to track even empty lines | |
2680 | stripped = line.strip() |
|
2510 | stripped = line.strip() | |
2681 |
|
2511 | |||
2682 | if not stripped: |
|
2512 | if not stripped: | |
2683 | if not continue_prompt: |
|
2513 | if not continue_prompt: | |
2684 | self.outputcache.prompt_count -= 1 |
|
2514 | self.outputcache.prompt_count -= 1 | |
2685 | return self.handle_normal(line_info) |
|
2515 | return self.handle_normal(line_info) | |
2686 |
|
2516 | |||
2687 | # print '***cont',continue_prompt # dbg |
|
2517 | # print '***cont',continue_prompt # dbg | |
2688 | # special handlers are only allowed for single line statements |
|
2518 | # special handlers are only allowed for single line statements | |
2689 | if continue_prompt and not self.multi_line_specials: |
|
2519 | if continue_prompt and not self.multi_line_specials: | |
2690 | return self.handle_normal(line_info) |
|
2520 | return self.handle_normal(line_info) | |
2691 |
|
2521 | |||
2692 |
|
2522 | |||
2693 | # See whether any pre-existing handler can take care of it |
|
2523 | # See whether any pre-existing handler can take care of it | |
2694 | rewritten = self.hooks.input_prefilter(stripped) |
|
2524 | rewritten = self.hooks.input_prefilter(stripped) | |
2695 | if rewritten != stripped: # ok, some prefilter did something |
|
2525 | if rewritten != stripped: # ok, some prefilter did something | |
2696 | rewritten = line_info.pre + rewritten # add indentation |
|
2526 | rewritten = line_info.pre + rewritten # add indentation | |
2697 | return self.handle_normal(prefilter.LineInfo(rewritten, |
|
2527 | return self.handle_normal(prefilter.LineInfo(rewritten, | |
2698 | continue_prompt)) |
|
2528 | continue_prompt)) | |
2699 |
|
2529 | |||
2700 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2530 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2701 |
|
2531 | |||
2702 | return prefilter.prefilter(line_info, self) |
|
2532 | return prefilter.prefilter(line_info, self) | |
2703 |
|
2533 | |||
2704 |
|
2534 | |||
2705 | def _prefilter_dumb(self, line, continue_prompt): |
|
2535 | def _prefilter_dumb(self, line, continue_prompt): | |
2706 | """simple prefilter function, for debugging""" |
|
2536 | """simple prefilter function, for debugging""" | |
2707 | return self.handle_normal(line,continue_prompt) |
|
2537 | return self.handle_normal(line,continue_prompt) | |
2708 |
|
2538 | |||
2709 |
|
2539 | |||
2710 | def multiline_prefilter(self, line, continue_prompt): |
|
2540 | def multiline_prefilter(self, line, continue_prompt): | |
2711 | """ Run _prefilter for each line of input |
|
2541 | """ Run _prefilter for each line of input | |
2712 |
|
2542 | |||
2713 | Covers cases where there are multiple lines in the user entry, |
|
2543 | Covers cases where there are multiple lines in the user entry, | |
2714 | which is the case when the user goes back to a multiline history |
|
2544 | which is the case when the user goes back to a multiline history | |
2715 | entry and presses enter. |
|
2545 | entry and presses enter. | |
2716 |
|
2546 | |||
2717 | """ |
|
2547 | """ | |
|
2548 | growl.notify("multiline_prefilter: ", "%s\n%s" % (line, continue_prompt)) | |||
2718 | out = [] |
|
2549 | out = [] | |
2719 | for l in line.rstrip('\n').split('\n'): |
|
2550 | for l in line.rstrip('\n').split('\n'): | |
2720 | out.append(self._prefilter(l, continue_prompt)) |
|
2551 | out.append(self._prefilter(l, continue_prompt)) | |
|
2552 | growl.notify("multiline_prefilter return: ", '\n'.join(out)) | |||
2721 | return '\n'.join(out) |
|
2553 | return '\n'.join(out) | |
2722 |
|
2554 | |||
2723 | # Set the default prefilter() function (this can be user-overridden) |
|
2555 | # Set the default prefilter() function (this can be user-overridden) | |
2724 | prefilter = multiline_prefilter |
|
2556 | prefilter = multiline_prefilter | |
2725 |
|
2557 | |||
2726 | def handle_normal(self,line_info): |
|
2558 | def handle_normal(self, line_info): | |
2727 | """Handle normal input lines. Use as a template for handlers.""" |
|
2559 | """Handle normal input lines. Use as a template for handlers.""" | |
2728 |
|
2560 | |||
2729 | # With autoindent on, we need some way to exit the input loop, and I |
|
2561 | # With autoindent on, we need some way to exit the input loop, and I | |
2730 | # don't want to force the user to have to backspace all the way to |
|
2562 | # don't want to force the user to have to backspace all the way to | |
2731 | # clear the line. The rule will be in this case, that either two |
|
2563 | # clear the line. The rule will be in this case, that either two | |
2732 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
2564 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
2733 | # of a size different to the indent level, will exit the input loop. |
|
2565 | # of a size different to the indent level, will exit the input loop. | |
2734 | line = line_info.line |
|
2566 | line = line_info.line | |
2735 | continue_prompt = line_info.continue_prompt |
|
2567 | continue_prompt = line_info.continue_prompt | |
2736 |
|
2568 | |||
2737 | if (continue_prompt and self.autoindent and line.isspace() and |
|
2569 | if (continue_prompt and self.autoindent and line.isspace() and | |
2738 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or |
|
2570 | (0 < abs(len(line) - self.indent_current_nsp) <= 2 or | |
2739 | (self.buffer[-1]).isspace() )): |
|
2571 | (self.buffer[-1]).isspace() )): | |
2740 | line = '' |
|
2572 | line = '' | |
2741 |
|
2573 | |||
2742 | self.log(line,line,continue_prompt) |
|
2574 | self.log(line,line,continue_prompt) | |
2743 | return line |
|
2575 | return line | |
2744 |
|
2576 | |||
2745 | def handle_alias(self,line_info): |
|
2577 | def handle_alias(self, line_info): | |
2746 | """Handle alias input lines. """ |
|
2578 | """Handle alias input lines. """ | |
2747 | tgt = self.alias_table[line_info.iFun] |
|
2579 | tgt = self.alias_manager.alias_table[line_info.iFun] | |
2748 | # print "=>",tgt #dbg |
|
|||
2749 | if callable(tgt): |
|
2580 | if callable(tgt): | |
2750 | if '$' in line_info.line: |
|
2581 | if '$' in line_info.line: | |
2751 | call_meth = '(_ip, _ip.var_expand(%s))' |
|
2582 | call_meth = '(_ip, _ip.var_expand(%s))' | |
2752 | else: |
|
2583 | else: | |
2753 | call_meth = '(_ip,%s)' |
|
2584 | call_meth = '(_ip,%s)' | |
2754 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, |
|
2585 | line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace, | |
2755 | line_info.iFun, |
|
2586 | line_info.iFun, | |
2756 | make_quoted_expr(line_info.line)) |
|
2587 | make_quoted_expr(line_info.line)) | |
2757 | else: |
|
2588 | else: | |
2758 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) |
|
2589 | transformed = self.expand_aliases(line_info.iFun,line_info.theRest) | |
2759 |
|
2590 | |||
2760 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
2591 | # pre is needed, because it carries the leading whitespace. Otherwise | |
2761 | # aliases won't work in indented sections. |
|
2592 | # aliases won't work in indented sections. | |
2762 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2593 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2763 | make_quoted_expr( transformed )) |
|
2594 | make_quoted_expr( transformed )) | |
2764 |
|
2595 | |||
2765 | self.log(line_info.line,line_out,line_info.continue_prompt) |
|
2596 | self.log(line_info.line,line_out,line_info.continue_prompt) | |
2766 | #print 'line out:',line_out # dbg |
|
2597 | #print 'line out:',line_out # dbg | |
2767 | return line_out |
|
2598 | return line_out | |
2768 |
|
2599 | |||
2769 | def handle_shell_escape(self, line_info): |
|
2600 | def handle_shell_escape(self, line_info): | |
2770 | """Execute the line in a shell, empty return value""" |
|
2601 | """Execute the line in a shell, empty return value""" | |
2771 | #print 'line in :', `line` # dbg |
|
2602 | #print 'line in :', `line` # dbg | |
2772 | line = line_info.line |
|
2603 | line = line_info.line | |
2773 | if line.lstrip().startswith('!!'): |
|
2604 | if line.lstrip().startswith('!!'): | |
2774 | # rewrite LineInfo's line, iFun and theRest to properly hold the |
|
2605 | # rewrite LineInfo's line, iFun and theRest to properly hold the | |
2775 | # call to %sx and the actual command to be executed, so |
|
2606 | # call to %sx and the actual command to be executed, so | |
2776 | # handle_magic can work correctly. Note that this works even if |
|
2607 | # handle_magic can work correctly. Note that this works even if | |
2777 | # the line is indented, so it handles multi_line_specials |
|
2608 | # the line is indented, so it handles multi_line_specials | |
2778 | # properly. |
|
2609 | # properly. | |
2779 | new_rest = line.lstrip()[2:] |
|
2610 | new_rest = line.lstrip()[2:] | |
2780 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) |
|
2611 | line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest) | |
2781 | line_info.iFun = 'sx' |
|
2612 | line_info.iFun = 'sx' | |
2782 | line_info.theRest = new_rest |
|
2613 | line_info.theRest = new_rest | |
2783 | return self.handle_magic(line_info) |
|
2614 | return self.handle_magic(line_info) | |
2784 | else: |
|
2615 | else: | |
2785 | cmd = line.lstrip().lstrip('!') |
|
2616 | cmd = line.lstrip().lstrip('!') | |
2786 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, |
|
2617 | line_out = '%s_ip.system(%s)' % (line_info.preWhitespace, | |
2787 | make_quoted_expr(cmd)) |
|
2618 | make_quoted_expr(cmd)) | |
2788 | # update cache/log and return |
|
2619 | # update cache/log and return | |
2789 | self.log(line,line_out,line_info.continue_prompt) |
|
2620 | self.log(line,line_out,line_info.continue_prompt) | |
2790 | return line_out |
|
2621 | return line_out | |
2791 |
|
2622 | |||
2792 | def handle_magic(self, line_info): |
|
2623 | def handle_magic(self, line_info): | |
2793 | """Execute magic functions.""" |
|
2624 | """Execute magic functions.""" | |
2794 | iFun = line_info.iFun |
|
2625 | iFun = line_info.iFun | |
2795 | theRest = line_info.theRest |
|
2626 | theRest = line_info.theRest | |
2796 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, |
|
2627 | cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace, | |
2797 | make_quoted_expr(iFun + " " + theRest)) |
|
2628 | make_quoted_expr(iFun + " " + theRest)) | |
2798 | self.log(line_info.line,cmd,line_info.continue_prompt) |
|
2629 | self.log(line_info.line,cmd,line_info.continue_prompt) | |
2799 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg |
|
2630 | #print 'in handle_magic, cmd=<%s>' % cmd # dbg | |
2800 | return cmd |
|
2631 | return cmd | |
2801 |
|
2632 | |||
2802 | def handle_auto(self, line_info): |
|
2633 | def handle_auto(self, line_info): | |
2803 | """Hande lines which can be auto-executed, quoting if requested.""" |
|
2634 | """Hande lines which can be auto-executed, quoting if requested.""" | |
2804 |
|
2635 | |||
2805 | line = line_info.line |
|
2636 | line = line_info.line | |
2806 | iFun = line_info.iFun |
|
2637 | iFun = line_info.iFun | |
2807 | theRest = line_info.theRest |
|
2638 | theRest = line_info.theRest | |
2808 | pre = line_info.pre |
|
2639 | pre = line_info.pre | |
2809 | continue_prompt = line_info.continue_prompt |
|
2640 | continue_prompt = line_info.continue_prompt | |
2810 | obj = line_info.ofind(self)['obj'] |
|
2641 | obj = line_info.ofind(self)['obj'] | |
2811 |
|
2642 | |||
2812 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg |
|
2643 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg | |
2813 |
|
2644 | |||
2814 | # This should only be active for single-line input! |
|
2645 | # This should only be active for single-line input! | |
2815 | if continue_prompt: |
|
2646 | if continue_prompt: | |
2816 | self.log(line,line,continue_prompt) |
|
2647 | self.log(line,line,continue_prompt) | |
2817 | return line |
|
2648 | return line | |
2818 |
|
2649 | |||
2819 | force_auto = isinstance(obj, IPyAutocall) |
|
2650 | force_auto = isinstance(obj, IPyAutocall) | |
2820 | auto_rewrite = True |
|
2651 | auto_rewrite = True | |
2821 |
|
2652 | |||
2822 | if pre == self.ESC_QUOTE: |
|
2653 | if pre == self.ESC_QUOTE: | |
2823 | # Auto-quote splitting on whitespace |
|
2654 | # Auto-quote splitting on whitespace | |
2824 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) |
|
2655 | newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) ) | |
2825 | elif pre == self.ESC_QUOTE2: |
|
2656 | elif pre == self.ESC_QUOTE2: | |
2826 | # Auto-quote whole string |
|
2657 | # Auto-quote whole string | |
2827 | newcmd = '%s("%s")' % (iFun,theRest) |
|
2658 | newcmd = '%s("%s")' % (iFun,theRest) | |
2828 | elif pre == self.ESC_PAREN: |
|
2659 | elif pre == self.ESC_PAREN: | |
2829 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) |
|
2660 | newcmd = '%s(%s)' % (iFun,",".join(theRest.split())) | |
2830 | else: |
|
2661 | else: | |
2831 | # Auto-paren. |
|
2662 | # Auto-paren. | |
2832 | # We only apply it to argument-less calls if the autocall |
|
2663 | # We only apply it to argument-less calls if the autocall | |
2833 | # parameter is set to 2. We only need to check that autocall is < |
|
2664 | # parameter is set to 2. We only need to check that autocall is < | |
2834 | # 2, since this function isn't called unless it's at least 1. |
|
2665 | # 2, since this function isn't called unless it's at least 1. | |
2835 | if not theRest and (self.autocall < 2) and not force_auto: |
|
2666 | if not theRest and (self.autocall < 2) and not force_auto: | |
2836 | newcmd = '%s %s' % (iFun,theRest) |
|
2667 | newcmd = '%s %s' % (iFun,theRest) | |
2837 | auto_rewrite = False |
|
2668 | auto_rewrite = False | |
2838 | else: |
|
2669 | else: | |
2839 | if not force_auto and theRest.startswith('['): |
|
2670 | if not force_auto and theRest.startswith('['): | |
2840 | if hasattr(obj,'__getitem__'): |
|
2671 | if hasattr(obj,'__getitem__'): | |
2841 | # Don't autocall in this case: item access for an object |
|
2672 | # Don't autocall in this case: item access for an object | |
2842 | # which is BOTH callable and implements __getitem__. |
|
2673 | # which is BOTH callable and implements __getitem__. | |
2843 | newcmd = '%s %s' % (iFun,theRest) |
|
2674 | newcmd = '%s %s' % (iFun,theRest) | |
2844 | auto_rewrite = False |
|
2675 | auto_rewrite = False | |
2845 | else: |
|
2676 | else: | |
2846 | # if the object doesn't support [] access, go ahead and |
|
2677 | # if the object doesn't support [] access, go ahead and | |
2847 | # autocall |
|
2678 | # autocall | |
2848 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) |
|
2679 | newcmd = '%s(%s)' % (iFun.rstrip(),theRest) | |
2849 | elif theRest.endswith(';'): |
|
2680 | elif theRest.endswith(';'): | |
2850 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) |
|
2681 | newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1]) | |
2851 | else: |
|
2682 | else: | |
2852 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) |
|
2683 | newcmd = '%s(%s)' % (iFun.rstrip(), theRest) | |
2853 |
|
2684 | |||
2854 | if auto_rewrite: |
|
2685 | if auto_rewrite: | |
2855 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd |
|
2686 | rw = self.outputcache.prompt1.auto_rewrite() + newcmd | |
2856 |
|
2687 | |||
2857 | try: |
|
2688 | try: | |
2858 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2689 | # plain ascii works better w/ pyreadline, on some machines, so | |
2859 | # we use it and only print uncolored rewrite if we have unicode |
|
2690 | # we use it and only print uncolored rewrite if we have unicode | |
2860 | rw = str(rw) |
|
2691 | rw = str(rw) | |
2861 | print >>Term.cout, rw |
|
2692 | print >>Term.cout, rw | |
2862 | except UnicodeEncodeError: |
|
2693 | except UnicodeEncodeError: | |
2863 | print "-------------->" + newcmd |
|
2694 | print "-------------->" + newcmd | |
2864 |
|
2695 | |||
2865 | # log what is now valid Python, not the actual user input (without the |
|
2696 | # log what is now valid Python, not the actual user input (without the | |
2866 | # final newline) |
|
2697 | # final newline) | |
2867 | self.log(line,newcmd,continue_prompt) |
|
2698 | self.log(line,newcmd,continue_prompt) | |
2868 | return newcmd |
|
2699 | return newcmd | |
2869 |
|
2700 | |||
2870 | def handle_help(self, line_info): |
|
2701 | def handle_help(self, line_info): | |
2871 | """Try to get some help for the object. |
|
2702 | """Try to get some help for the object. | |
2872 |
|
2703 | |||
2873 | obj? or ?obj -> basic information. |
|
2704 | obj? or ?obj -> basic information. | |
2874 | obj?? or ??obj -> more details. |
|
2705 | obj?? or ??obj -> more details. | |
2875 | """ |
|
2706 | """ | |
2876 |
|
2707 | |||
2877 | line = line_info.line |
|
2708 | line = line_info.line | |
2878 | # We need to make sure that we don't process lines which would be |
|
2709 | # We need to make sure that we don't process lines which would be | |
2879 | # otherwise valid python, such as "x=1 # what?" |
|
2710 | # otherwise valid python, such as "x=1 # what?" | |
2880 | try: |
|
2711 | try: | |
2881 | codeop.compile_command(line) |
|
2712 | codeop.compile_command(line) | |
2882 | except SyntaxError: |
|
2713 | except SyntaxError: | |
2883 | # We should only handle as help stuff which is NOT valid syntax |
|
2714 | # We should only handle as help stuff which is NOT valid syntax | |
2884 | if line[0]==self.ESC_HELP: |
|
2715 | if line[0]==self.ESC_HELP: | |
2885 | line = line[1:] |
|
2716 | line = line[1:] | |
2886 | elif line[-1]==self.ESC_HELP: |
|
2717 | elif line[-1]==self.ESC_HELP: | |
2887 | line = line[:-1] |
|
2718 | line = line[:-1] | |
2888 | self.log(line,'#?'+line,line_info.continue_prompt) |
|
2719 | self.log(line,'#?'+line,line_info.continue_prompt) | |
2889 | if line: |
|
2720 | if line: | |
2890 | #print 'line:<%r>' % line # dbg |
|
2721 | #print 'line:<%r>' % line # dbg | |
2891 | self.magic_pinfo(line) |
|
2722 | self.magic_pinfo(line) | |
2892 | else: |
|
2723 | else: | |
2893 | page(self.usage,screen_lines=self.usable_screen_length) |
|
2724 | page(self.usage,screen_lines=self.usable_screen_length) | |
2894 | return '' # Empty string is needed here! |
|
2725 | return '' # Empty string is needed here! | |
2895 | except: |
|
2726 | except: | |
2896 | # Pass any other exceptions through to the normal handler |
|
2727 | # Pass any other exceptions through to the normal handler | |
2897 | return self.handle_normal(line_info) |
|
2728 | return self.handle_normal(line_info) | |
2898 | else: |
|
2729 | else: | |
2899 | # If the code compiles ok, we should handle it normally |
|
2730 | # If the code compiles ok, we should handle it normally | |
2900 | return self.handle_normal(line_info) |
|
2731 | return self.handle_normal(line_info) | |
2901 |
|
2732 | |||
2902 | def handle_emacs(self, line_info): |
|
2733 | def handle_emacs(self, line_info): | |
2903 | """Handle input lines marked by python-mode.""" |
|
2734 | """Handle input lines marked by python-mode.""" | |
2904 |
|
2735 | |||
2905 | # Currently, nothing is done. Later more functionality can be added |
|
2736 | # Currently, nothing is done. Later more functionality can be added | |
2906 | # here if needed. |
|
2737 | # here if needed. | |
2907 |
|
2738 | |||
2908 | # The input cache shouldn't be updated |
|
2739 | # The input cache shouldn't be updated | |
2909 | return line_info.line |
|
2740 | return line_info.line | |
2910 |
|
2741 | |||
2911 | #------------------------------------------------------------------------- |
|
2742 | #------------------------------------------------------------------------- | |
2912 | # Utilities |
|
2743 | # Utilities | |
2913 | #------------------------------------------------------------------------- |
|
2744 | #------------------------------------------------------------------------- | |
2914 |
|
2745 | |||
2915 | def getoutput(self, cmd): |
|
2746 | def getoutput(self, cmd): | |
2916 | return getoutput(self.var_expand(cmd,depth=2), |
|
2747 | return getoutput(self.var_expand(cmd,depth=2), | |
2917 | header=self.system_header, |
|
2748 | header=self.system_header, | |
2918 | verbose=self.system_verbose) |
|
2749 | verbose=self.system_verbose) | |
2919 |
|
2750 | |||
2920 | def getoutputerror(self, cmd): |
|
2751 | def getoutputerror(self, cmd): | |
2921 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2752 | return getoutputerror(self.var_expand(cmd,depth=2), | |
2922 | header=self.system_header, |
|
2753 | header=self.system_header, | |
2923 | verbose=self.system_verbose) |
|
2754 | verbose=self.system_verbose) | |
2924 |
|
2755 | |||
2925 | def var_expand(self,cmd,depth=0): |
|
2756 | def var_expand(self,cmd,depth=0): | |
2926 | """Expand python variables in a string. |
|
2757 | """Expand python variables in a string. | |
2927 |
|
2758 | |||
2928 | The depth argument indicates how many frames above the caller should |
|
2759 | The depth argument indicates how many frames above the caller should | |
2929 | be walked to look for the local namespace where to expand variables. |
|
2760 | be walked to look for the local namespace where to expand variables. | |
2930 |
|
2761 | |||
2931 | The global namespace for expansion is always the user's interactive |
|
2762 | The global namespace for expansion is always the user's interactive | |
2932 | namespace. |
|
2763 | namespace. | |
2933 | """ |
|
2764 | """ | |
2934 |
|
2765 | |||
2935 | return str(ItplNS(cmd, |
|
2766 | return str(ItplNS(cmd, | |
2936 | self.user_ns, # globals |
|
2767 | self.user_ns, # globals | |
2937 | # Skip our own frame in searching for locals: |
|
2768 | # Skip our own frame in searching for locals: | |
2938 | sys._getframe(depth+1).f_locals # locals |
|
2769 | sys._getframe(depth+1).f_locals # locals | |
2939 | )) |
|
2770 | )) | |
2940 |
|
2771 | |||
2941 | def mktempfile(self,data=None): |
|
2772 | def mktempfile(self,data=None): | |
2942 | """Make a new tempfile and return its filename. |
|
2773 | """Make a new tempfile and return its filename. | |
2943 |
|
2774 | |||
2944 | This makes a call to tempfile.mktemp, but it registers the created |
|
2775 | This makes a call to tempfile.mktemp, but it registers the created | |
2945 | filename internally so ipython cleans it up at exit time. |
|
2776 | filename internally so ipython cleans it up at exit time. | |
2946 |
|
2777 | |||
2947 | Optional inputs: |
|
2778 | Optional inputs: | |
2948 |
|
2779 | |||
2949 | - data(None): if data is given, it gets written out to the temp file |
|
2780 | - data(None): if data is given, it gets written out to the temp file | |
2950 | immediately, and the file is closed again.""" |
|
2781 | immediately, and the file is closed again.""" | |
2951 |
|
2782 | |||
2952 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2783 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2953 | self.tempfiles.append(filename) |
|
2784 | self.tempfiles.append(filename) | |
2954 |
|
2785 | |||
2955 | if data: |
|
2786 | if data: | |
2956 | tmp_file = open(filename,'w') |
|
2787 | tmp_file = open(filename,'w') | |
2957 | tmp_file.write(data) |
|
2788 | tmp_file.write(data) | |
2958 | tmp_file.close() |
|
2789 | tmp_file.close() | |
2959 | return filename |
|
2790 | return filename | |
2960 |
|
2791 | |||
2961 | def write(self,data): |
|
2792 | def write(self,data): | |
2962 | """Write a string to the default output""" |
|
2793 | """Write a string to the default output""" | |
2963 | Term.cout.write(data) |
|
2794 | Term.cout.write(data) | |
2964 |
|
2795 | |||
2965 | def write_err(self,data): |
|
2796 | def write_err(self,data): | |
2966 | """Write a string to the default error output""" |
|
2797 | """Write a string to the default error output""" | |
2967 | Term.cerr.write(data) |
|
2798 | Term.cerr.write(data) | |
2968 |
|
2799 | |||
2969 | def ask_yes_no(self,prompt,default=True): |
|
2800 | def ask_yes_no(self,prompt,default=True): | |
2970 | if self.quiet: |
|
2801 | if self.quiet: | |
2971 | return True |
|
2802 | return True | |
2972 | return ask_yes_no(prompt,default) |
|
2803 | return ask_yes_no(prompt,default) | |
2973 |
|
2804 | |||
2974 | #------------------------------------------------------------------------- |
|
2805 | #------------------------------------------------------------------------- | |
2975 | # Things related to IPython exiting |
|
2806 | # Things related to IPython exiting | |
2976 | #------------------------------------------------------------------------- |
|
2807 | #------------------------------------------------------------------------- | |
2977 |
|
2808 | |||
2978 | def ask_exit(self): |
|
2809 | def ask_exit(self): | |
2979 | """ Call for exiting. Can be overiden and used as a callback. """ |
|
2810 | """ Call for exiting. Can be overiden and used as a callback. """ | |
2980 | self.exit_now = True |
|
2811 | self.exit_now = True | |
2981 |
|
2812 | |||
2982 | def exit(self): |
|
2813 | def exit(self): | |
2983 | """Handle interactive exit. |
|
2814 | """Handle interactive exit. | |
2984 |
|
2815 | |||
2985 | This method calls the ask_exit callback.""" |
|
2816 | This method calls the ask_exit callback.""" | |
2986 | if self.confirm_exit: |
|
2817 | if self.confirm_exit: | |
2987 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2818 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2988 | self.ask_exit() |
|
2819 | self.ask_exit() | |
2989 | else: |
|
2820 | else: | |
2990 | self.ask_exit() |
|
2821 | self.ask_exit() | |
2991 |
|
2822 | |||
2992 | def atexit_operations(self): |
|
2823 | def atexit_operations(self): | |
2993 | """This will be executed at the time of exit. |
|
2824 | """This will be executed at the time of exit. | |
2994 |
|
2825 | |||
2995 | Saving of persistent data should be performed here. |
|
2826 | Saving of persistent data should be performed here. | |
2996 | """ |
|
2827 | """ | |
2997 | self.savehist() |
|
2828 | self.savehist() | |
2998 |
|
2829 | |||
2999 | # Cleanup all tempfiles left around |
|
2830 | # Cleanup all tempfiles left around | |
3000 | for tfile in self.tempfiles: |
|
2831 | for tfile in self.tempfiles: | |
3001 | try: |
|
2832 | try: | |
3002 | os.unlink(tfile) |
|
2833 | os.unlink(tfile) | |
3003 | except OSError: |
|
2834 | except OSError: | |
3004 | pass |
|
2835 | pass | |
3005 |
|
2836 | |||
3006 | # Clear all user namespaces to release all references cleanly. |
|
2837 | # Clear all user namespaces to release all references cleanly. | |
3007 | self.reset() |
|
2838 | self.reset() | |
3008 |
|
2839 | |||
3009 | # Run user hooks |
|
2840 | # Run user hooks | |
3010 | self.hooks.shutdown_hook() |
|
2841 | self.hooks.shutdown_hook() | |
3011 |
|
2842 | |||
3012 | def cleanup(self): |
|
2843 | def cleanup(self): | |
3013 | self.restore_sys_module_state() |
|
2844 | self.restore_sys_module_state() | |
3014 |
|
2845 | |||
3015 |
|
2846 | |||
3016 |
|
2847 | |||
3017 |
|
2848 | |||
3018 |
|
2849 |
@@ -1,321 +1,321 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Classes and functions for prefiltering (transforming) a line of user input. |
|
3 | Classes and functions for prefiltering (transforming) a line of user input. | |
4 | This module is responsible, primarily, for breaking the line up into useful |
|
4 | This module is responsible, primarily, for breaking the line up into useful | |
5 | pieces and triggering the appropriate handlers in iplib to do the actual |
|
5 | pieces and triggering the appropriate handlers in iplib to do the actual | |
6 | transforming work. |
|
6 | transforming work. | |
7 | """ |
|
7 | """ | |
8 | __docformat__ = "restructuredtext en" |
|
8 | __docformat__ = "restructuredtext en" | |
9 |
|
9 | |||
10 | import re |
|
10 | import re | |
11 | from IPython.core.autocall import IPyAutocall |
|
11 | from IPython.core.autocall import IPyAutocall | |
12 |
|
12 | |||
13 |
|
13 | |||
14 | class LineInfo(object): |
|
14 | class LineInfo(object): | |
15 | """A single line of input and associated info. |
|
15 | """A single line of input and associated info. | |
16 |
|
16 | |||
17 | Includes the following as properties: |
|
17 | Includes the following as properties: | |
18 |
|
18 | |||
19 | line |
|
19 | line | |
20 | The original, raw line |
|
20 | The original, raw line | |
21 |
|
21 | |||
22 | continue_prompt |
|
22 | continue_prompt | |
23 | Is this line a continuation in a sequence of multiline input? |
|
23 | Is this line a continuation in a sequence of multiline input? | |
24 |
|
24 | |||
25 | pre |
|
25 | pre | |
26 | The initial esc character or whitespace. |
|
26 | The initial esc character or whitespace. | |
27 |
|
27 | |||
28 | preChar |
|
28 | preChar | |
29 | The escape character(s) in pre or the empty string if there isn't one. |
|
29 | The escape character(s) in pre or the empty string if there isn't one. | |
30 | Note that '!!' is a possible value for preChar. Otherwise it will |
|
30 | Note that '!!' is a possible value for preChar. Otherwise it will | |
31 | always be a single character. |
|
31 | always be a single character. | |
32 |
|
32 | |||
33 | preWhitespace |
|
33 | preWhitespace | |
34 | The leading whitespace from pre if it exists. If there is a preChar, |
|
34 | The leading whitespace from pre if it exists. If there is a preChar, | |
35 | this is just ''. |
|
35 | this is just ''. | |
36 |
|
36 | |||
37 | iFun |
|
37 | iFun | |
38 | The 'function part', which is basically the maximal initial sequence |
|
38 | The 'function part', which is basically the maximal initial sequence | |
39 | of valid python identifiers and the '.' character. This is what is |
|
39 | of valid python identifiers and the '.' character. This is what is | |
40 | checked for alias and magic transformations, used for auto-calling, |
|
40 | checked for alias and magic transformations, used for auto-calling, | |
41 | etc. |
|
41 | etc. | |
42 |
|
42 | |||
43 | theRest |
|
43 | theRest | |
44 | Everything else on the line. |
|
44 | Everything else on the line. | |
45 | """ |
|
45 | """ | |
46 | def __init__(self, line, continue_prompt): |
|
46 | def __init__(self, line, continue_prompt): | |
47 | self.line = line |
|
47 | self.line = line | |
48 | self.continue_prompt = continue_prompt |
|
48 | self.continue_prompt = continue_prompt | |
49 | self.pre, self.iFun, self.theRest = splitUserInput(line) |
|
49 | self.pre, self.iFun, self.theRest = splitUserInput(line) | |
50 |
|
50 | |||
51 | self.preChar = self.pre.strip() |
|
51 | self.preChar = self.pre.strip() | |
52 | if self.preChar: |
|
52 | if self.preChar: | |
53 | self.preWhitespace = '' # No whitespace allowd before esc chars |
|
53 | self.preWhitespace = '' # No whitespace allowd before esc chars | |
54 | else: |
|
54 | else: | |
55 | self.preWhitespace = self.pre |
|
55 | self.preWhitespace = self.pre | |
56 |
|
56 | |||
57 | self._oinfo = None |
|
57 | self._oinfo = None | |
58 |
|
58 | |||
59 | def ofind(self, ip): |
|
59 | def ofind(self, ip): | |
60 | """Do a full, attribute-walking lookup of the iFun in the various |
|
60 | """Do a full, attribute-walking lookup of the iFun in the various | |
61 | namespaces for the given IPython InteractiveShell instance. |
|
61 | namespaces for the given IPython InteractiveShell instance. | |
62 |
|
62 | |||
63 | Return a dict with keys: found,obj,ospace,ismagic |
|
63 | Return a dict with keys: found,obj,ospace,ismagic | |
64 |
|
64 | |||
65 | Note: can cause state changes because of calling getattr, but should |
|
65 | Note: can cause state changes because of calling getattr, but should | |
66 | only be run if autocall is on and if the line hasn't matched any |
|
66 | only be run if autocall is on and if the line hasn't matched any | |
67 | other, less dangerous handlers. |
|
67 | other, less dangerous handlers. | |
68 |
|
68 | |||
69 | Does cache the results of the call, so can be called multiple times |
|
69 | Does cache the results of the call, so can be called multiple times | |
70 | without worrying about *further* damaging state. |
|
70 | without worrying about *further* damaging state. | |
71 | """ |
|
71 | """ | |
72 | if not self._oinfo: |
|
72 | if not self._oinfo: | |
73 | self._oinfo = ip._ofind(self.iFun) |
|
73 | self._oinfo = ip._ofind(self.iFun) | |
74 | return self._oinfo |
|
74 | return self._oinfo | |
75 | def __str__(self): |
|
75 | def __str__(self): | |
76 | return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest) |
|
76 | return "Lineinfo [%s|%s|%s]" %(self.pre,self.iFun,self.theRest) | |
77 |
|
77 | |||
78 | def splitUserInput(line, pattern=None): |
|
78 | def splitUserInput(line, pattern=None): | |
79 | """Split user input into pre-char/whitespace, function part and rest. |
|
79 | """Split user input into pre-char/whitespace, function part and rest. | |
80 |
|
80 | |||
81 | Mostly internal to this module, but also used by iplib.expand_aliases, |
|
81 | Mostly internal to this module, but also used by iplib.expand_aliases, | |
82 | which passes in a shell pattern. |
|
82 | which passes in a shell pattern. | |
83 | """ |
|
83 | """ | |
84 | # It seems to me that the shell splitting should be a separate method. |
|
84 | # It seems to me that the shell splitting should be a separate method. | |
85 |
|
85 | |||
86 | if not pattern: |
|
86 | if not pattern: | |
87 | pattern = line_split |
|
87 | pattern = line_split | |
88 | match = pattern.match(line) |
|
88 | match = pattern.match(line) | |
89 | if not match: |
|
89 | if not match: | |
90 | #print "match failed for line '%s'" % line |
|
90 | #print "match failed for line '%s'" % line | |
91 | try: |
|
91 | try: | |
92 | iFun,theRest = line.split(None,1) |
|
92 | iFun,theRest = line.split(None,1) | |
93 | except ValueError: |
|
93 | except ValueError: | |
94 | #print "split failed for line '%s'" % line |
|
94 | #print "split failed for line '%s'" % line | |
95 | iFun,theRest = line,'' |
|
95 | iFun,theRest = line,'' | |
96 | pre = re.match('^(\s*)(.*)',line).groups()[0] |
|
96 | pre = re.match('^(\s*)(.*)',line).groups()[0] | |
97 | else: |
|
97 | else: | |
98 | pre,iFun,theRest = match.groups() |
|
98 | pre,iFun,theRest = match.groups() | |
99 |
|
99 | |||
100 | # iFun has to be a valid python identifier, so it better be only pure |
|
100 | # iFun has to be a valid python identifier, so it better be only pure | |
101 | # ascii, no unicode: |
|
101 | # ascii, no unicode: | |
102 | try: |
|
102 | try: | |
103 | iFun = iFun.encode('ascii') |
|
103 | iFun = iFun.encode('ascii') | |
104 | except UnicodeEncodeError: |
|
104 | except UnicodeEncodeError: | |
105 | theRest = iFun + u' ' + theRest |
|
105 | theRest = iFun + u' ' + theRest | |
106 | iFun = u'' |
|
106 | iFun = u'' | |
107 |
|
107 | |||
108 | #print 'line:<%s>' % line # dbg |
|
108 | #print 'line:<%s>' % line # dbg | |
109 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg |
|
109 | #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg | |
110 | return pre,iFun.strip(),theRest.lstrip() |
|
110 | return pre,iFun.strip(),theRest.lstrip() | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | # RegExp for splitting line contents into pre-char//first word-method//rest. |
|
113 | # RegExp for splitting line contents into pre-char//first word-method//rest. | |
114 | # For clarity, each group in on one line. |
|
114 | # For clarity, each group in on one line. | |
115 |
|
115 | |||
116 | # WARNING: update the regexp if the escapes in iplib are changed, as they |
|
116 | # WARNING: update the regexp if the escapes in iplib are changed, as they | |
117 | # are hardwired in. |
|
117 | # are hardwired in. | |
118 |
|
118 | |||
119 | # Although it's not solely driven by the regex, note that: |
|
119 | # Although it's not solely driven by the regex, note that: | |
120 | # ,;/% only trigger if they are the first character on the line |
|
120 | # ,;/% only trigger if they are the first character on the line | |
121 | # ! and !! trigger if they are first char(s) *or* follow an indent |
|
121 | # ! and !! trigger if they are first char(s) *or* follow an indent | |
122 | # ? triggers as first or last char. |
|
122 | # ? triggers as first or last char. | |
123 |
|
123 | |||
124 | # The three parts of the regex are: |
|
124 | # The three parts of the regex are: | |
125 | # 1) pre: pre_char *or* initial whitespace |
|
125 | # 1) pre: pre_char *or* initial whitespace | |
126 | # 2) iFun: first word/method (mix of \w and '.') |
|
126 | # 2) iFun: first word/method (mix of \w and '.') | |
127 | # 3) theRest: rest of line (separated from iFun by space if non-empty) |
|
127 | # 3) theRest: rest of line (separated from iFun by space if non-empty) | |
128 | line_split = re.compile(r'^([,;/%?]|!!?|\s*)' |
|
128 | line_split = re.compile(r'^([,;/%?]|!!?|\s*)' | |
129 | r'\s*([\w\.]+)' |
|
129 | r'\s*([\w\.]+)' | |
130 | r'(\s+.*$|$)') |
|
130 | r'(\s+.*$|$)') | |
131 |
|
131 | |||
132 | shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)') |
|
132 | shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)') | |
133 |
|
133 | |||
134 | def prefilter(line_info, ip): |
|
134 | def prefilter(line_info, ip): | |
135 | """Call one of the passed-in InteractiveShell's handler preprocessors, |
|
135 | """Call one of the passed-in InteractiveShell's handler preprocessors, | |
136 | depending on the form of the line. Return the results, which must be a |
|
136 | depending on the form of the line. Return the results, which must be a | |
137 | value, even if it's a blank ('').""" |
|
137 | value, even if it's a blank ('').""" | |
138 | # Note: the order of these checks does matter. |
|
138 | # Note: the order of these checks does matter. | |
139 | for check in [ checkEmacs, |
|
139 | for check in [ checkEmacs, | |
140 | checkShellEscape, |
|
140 | checkShellEscape, | |
141 | checkIPyAutocall, |
|
141 | checkIPyAutocall, | |
142 | checkMultiLineMagic, |
|
142 | checkMultiLineMagic, | |
143 | checkEscChars, |
|
143 | checkEscChars, | |
144 | checkAssignment, |
|
144 | checkAssignment, | |
145 | checkAutomagic, |
|
145 | checkAutomagic, | |
146 | checkAlias, |
|
146 | checkAlias, | |
147 | checkPythonOps, |
|
147 | checkPythonOps, | |
148 | checkAutocall, |
|
148 | checkAutocall, | |
149 | ]: |
|
149 | ]: | |
150 | handler = check(line_info, ip) |
|
150 | handler = check(line_info, ip) | |
151 | if handler: |
|
151 | if handler: | |
152 | return handler(line_info) |
|
152 | return handler(line_info) | |
153 |
|
153 | |||
154 | return ip.handle_normal(line_info) |
|
154 | return ip.handle_normal(line_info) | |
155 |
|
155 | |||
156 | # Handler checks |
|
156 | # Handler checks | |
157 | # |
|
157 | # | |
158 | # All have the same interface: they take a LineInfo object and a ref to the |
|
158 | # All have the same interface: they take a LineInfo object and a ref to the | |
159 | # iplib.InteractiveShell object. They check the line to see if a particular |
|
159 | # iplib.InteractiveShell object. They check the line to see if a particular | |
160 | # handler should be called, and return either a handler or None. The |
|
160 | # handler should be called, and return either a handler or None. The | |
161 | # handlers which they return are *bound* methods of the InteractiveShell |
|
161 | # handlers which they return are *bound* methods of the InteractiveShell | |
162 | # object. |
|
162 | # object. | |
163 | # |
|
163 | # | |
164 | # In general, these checks should only take responsibility for their 'own' |
|
164 | # In general, these checks should only take responsibility for their 'own' | |
165 | # handler. If it doesn't get triggered, they should just return None and |
|
165 | # handler. If it doesn't get triggered, they should just return None and | |
166 | # let the rest of the check sequence run. |
|
166 | # let the rest of the check sequence run. | |
167 |
|
167 | |||
168 | def checkShellEscape(l_info,ip): |
|
168 | def checkShellEscape(l_info,ip): | |
169 | if l_info.line.lstrip().startswith(ip.ESC_SHELL): |
|
169 | if l_info.line.lstrip().startswith(ip.ESC_SHELL): | |
170 | return ip.handle_shell_escape |
|
170 | return ip.handle_shell_escape | |
171 |
|
171 | |||
172 | def checkEmacs(l_info,ip): |
|
172 | def checkEmacs(l_info,ip): | |
173 | "Emacs ipython-mode tags certain input lines." |
|
173 | "Emacs ipython-mode tags certain input lines." | |
174 | if l_info.line.endswith('# PYTHON-MODE'): |
|
174 | if l_info.line.endswith('# PYTHON-MODE'): | |
175 | return ip.handle_emacs |
|
175 | return ip.handle_emacs | |
176 | else: |
|
176 | else: | |
177 | return None |
|
177 | return None | |
178 |
|
178 | |||
179 | def checkIPyAutocall(l_info,ip): |
|
179 | def checkIPyAutocall(l_info,ip): | |
180 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
180 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
181 | obj = ip.user_ns.get(l_info.iFun, None) |
|
181 | obj = ip.user_ns.get(l_info.iFun, None) | |
182 | if isinstance(obj, IPyAutocall): |
|
182 | if isinstance(obj, IPyAutocall): | |
183 | obj.set_ip(ip) |
|
183 | obj.set_ip(ip) | |
184 | return ip.handle_auto |
|
184 | return ip.handle_auto | |
185 | else: |
|
185 | else: | |
186 | return None |
|
186 | return None | |
187 |
|
187 | |||
188 |
|
188 | |||
189 | def checkMultiLineMagic(l_info,ip): |
|
189 | def checkMultiLineMagic(l_info,ip): | |
190 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
190 | "Allow ! and !! in multi-line statements if multi_line_specials is on" | |
191 | # Note that this one of the only places we check the first character of |
|
191 | # Note that this one of the only places we check the first character of | |
192 | # iFun and *not* the preChar. Also note that the below test matches |
|
192 | # iFun and *not* the preChar. Also note that the below test matches | |
193 | # both ! and !!. |
|
193 | # both ! and !!. | |
194 | if l_info.continue_prompt \ |
|
194 | if l_info.continue_prompt \ | |
195 | and ip.multi_line_specials: |
|
195 | and ip.multi_line_specials: | |
196 | if l_info.iFun.startswith(ip.ESC_MAGIC): |
|
196 | if l_info.iFun.startswith(ip.ESC_MAGIC): | |
197 | return ip.handle_magic |
|
197 | return ip.handle_magic | |
198 | else: |
|
198 | else: | |
199 | return None |
|
199 | return None | |
200 |
|
200 | |||
201 | def checkEscChars(l_info,ip): |
|
201 | def checkEscChars(l_info,ip): | |
202 | """Check for escape character and return either a handler to handle it, |
|
202 | """Check for escape character and return either a handler to handle it, | |
203 | or None if there is no escape char.""" |
|
203 | or None if there is no escape char.""" | |
204 | if l_info.line[-1] == ip.ESC_HELP \ |
|
204 | if l_info.line[-1] == ip.ESC_HELP \ | |
205 | and l_info.preChar != ip.ESC_SHELL \ |
|
205 | and l_info.preChar != ip.ESC_SHELL \ | |
206 | and l_info.preChar != ip.ESC_SH_CAP: |
|
206 | and l_info.preChar != ip.ESC_SH_CAP: | |
207 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
207 | # the ? can be at the end, but *not* for either kind of shell escape, | |
208 | # because a ? can be a vaild final char in a shell cmd |
|
208 | # because a ? can be a vaild final char in a shell cmd | |
209 | return ip.handle_help |
|
209 | return ip.handle_help | |
210 | elif l_info.preChar in ip.esc_handlers: |
|
210 | elif l_info.preChar in ip.esc_handlers: | |
211 | return ip.esc_handlers[l_info.preChar] |
|
211 | return ip.esc_handlers[l_info.preChar] | |
212 | else: |
|
212 | else: | |
213 | return None |
|
213 | return None | |
214 |
|
214 | |||
215 |
|
215 | |||
216 | def checkAssignment(l_info,ip): |
|
216 | def checkAssignment(l_info,ip): | |
217 | """Check to see if user is assigning to a var for the first time, in |
|
217 | """Check to see if user is assigning to a var for the first time, in | |
218 | which case we want to avoid any sort of automagic / autocall games. |
|
218 | which case we want to avoid any sort of automagic / autocall games. | |
219 |
|
219 | |||
220 | This allows users to assign to either alias or magic names true python |
|
220 | This allows users to assign to either alias or magic names true python | |
221 | variables (the magic/alias systems always take second seat to true |
|
221 | variables (the magic/alias systems always take second seat to true | |
222 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
222 | python code). E.g. ls='hi', or ls,that=1,2""" | |
223 | if l_info.theRest and l_info.theRest[0] in '=,': |
|
223 | if l_info.theRest and l_info.theRest[0] in '=,': | |
224 | return ip.handle_normal |
|
224 | return ip.handle_normal | |
225 | else: |
|
225 | else: | |
226 | return None |
|
226 | return None | |
227 |
|
227 | |||
228 |
|
228 | |||
229 | def checkAutomagic(l_info,ip): |
|
229 | def checkAutomagic(l_info,ip): | |
230 | """If the iFun is magic, and automagic is on, run it. Note: normal, |
|
230 | """If the iFun is magic, and automagic is on, run it. Note: normal, | |
231 | non-auto magic would already have been triggered via '%' in |
|
231 | non-auto magic would already have been triggered via '%' in | |
232 | check_esc_chars. This just checks for automagic. Also, before |
|
232 | check_esc_chars. This just checks for automagic. Also, before | |
233 | triggering the magic handler, make sure that there is nothing in the |
|
233 | triggering the magic handler, make sure that there is nothing in the | |
234 | user namespace which could shadow it.""" |
|
234 | user namespace which could shadow it.""" | |
235 | if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun): |
|
235 | if not ip.automagic or not hasattr(ip,'magic_'+l_info.iFun): | |
236 | return None |
|
236 | return None | |
237 |
|
237 | |||
238 | # We have a likely magic method. Make sure we should actually call it. |
|
238 | # We have a likely magic method. Make sure we should actually call it. | |
239 | if l_info.continue_prompt and not ip.multi_line_specials: |
|
239 | if l_info.continue_prompt and not ip.multi_line_specials: | |
240 | return None |
|
240 | return None | |
241 |
|
241 | |||
242 | head = l_info.iFun.split('.',1)[0] |
|
242 | head = l_info.iFun.split('.',1)[0] | |
243 | if isShadowed(head,ip): |
|
243 | if isShadowed(head,ip): | |
244 | return None |
|
244 | return None | |
245 |
|
245 | |||
246 | return ip.handle_magic |
|
246 | return ip.handle_magic | |
247 |
|
247 | |||
248 |
|
248 | |||
249 | def checkAlias(l_info,ip): |
|
249 | def checkAlias(l_info,ip): | |
250 | "Check if the initital identifier on the line is an alias." |
|
250 | "Check if the initital identifier on the line is an alias." | |
251 | # Note: aliases can not contain '.' |
|
251 | # Note: aliases can not contain '.' | |
252 | head = l_info.iFun.split('.',1)[0] |
|
252 | head = l_info.iFun.split('.',1)[0] | |
253 |
|
253 | |||
254 |
if l_info.iFun not in ip.alias_ |
|
254 | if l_info.iFun not in ip.alias_manager \ | |
255 |
or head not in ip.alias_ |
|
255 | or head not in ip.alias_manager \ | |
256 | or isShadowed(head,ip): |
|
256 | or isShadowed(head,ip): | |
257 | return None |
|
257 | return None | |
258 |
|
258 | |||
259 | return ip.handle_alias |
|
259 | return ip.handle_alias | |
260 |
|
260 | |||
261 |
|
261 | |||
262 | def checkPythonOps(l_info,ip): |
|
262 | def checkPythonOps(l_info,ip): | |
263 | """If the 'rest' of the line begins with a function call or pretty much |
|
263 | """If the 'rest' of the line begins with a function call or pretty much | |
264 | any python operator, we should simply execute the line (regardless of |
|
264 | any python operator, we should simply execute the line (regardless of | |
265 | whether or not there's a possible autocall expansion). This avoids |
|
265 | whether or not there's a possible autocall expansion). This avoids | |
266 | spurious (and very confusing) geattr() accesses.""" |
|
266 | spurious (and very confusing) geattr() accesses.""" | |
267 | if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|': |
|
267 | if l_info.theRest and l_info.theRest[0] in '!=()<>,+*/%^&|': | |
268 | return ip.handle_normal |
|
268 | return ip.handle_normal | |
269 | else: |
|
269 | else: | |
270 | return None |
|
270 | return None | |
271 |
|
271 | |||
272 |
|
272 | |||
273 | def checkAutocall(l_info,ip): |
|
273 | def checkAutocall(l_info,ip): | |
274 | "Check if the initial word/function is callable and autocall is on." |
|
274 | "Check if the initial word/function is callable and autocall is on." | |
275 | if not ip.autocall: |
|
275 | if not ip.autocall: | |
276 | return None |
|
276 | return None | |
277 |
|
277 | |||
278 | oinfo = l_info.ofind(ip) # This can mutate state via getattr |
|
278 | oinfo = l_info.ofind(ip) # This can mutate state via getattr | |
279 | if not oinfo['found']: |
|
279 | if not oinfo['found']: | |
280 | return None |
|
280 | return None | |
281 |
|
281 | |||
282 | if callable(oinfo['obj']) \ |
|
282 | if callable(oinfo['obj']) \ | |
283 | and (not re_exclude_auto.match(l_info.theRest)) \ |
|
283 | and (not re_exclude_auto.match(l_info.theRest)) \ | |
284 | and re_fun_name.match(l_info.iFun): |
|
284 | and re_fun_name.match(l_info.iFun): | |
285 | #print 'going auto' # dbg |
|
285 | #print 'going auto' # dbg | |
286 | return ip.handle_auto |
|
286 | return ip.handle_auto | |
287 | else: |
|
287 | else: | |
288 | #print 'was callable?', callable(l_info.oinfo['obj']) # dbg |
|
288 | #print 'was callable?', callable(l_info.oinfo['obj']) # dbg | |
289 | return None |
|
289 | return None | |
290 |
|
290 | |||
291 | # RegExp to identify potential function names |
|
291 | # RegExp to identify potential function names | |
292 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
292 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
293 |
|
293 | |||
294 | # RegExp to exclude strings with this start from autocalling. In |
|
294 | # RegExp to exclude strings with this start from autocalling. In | |
295 | # particular, all binary operators should be excluded, so that if foo is |
|
295 | # particular, all binary operators should be excluded, so that if foo is | |
296 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
296 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The | |
297 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
297 | # characters '!=()' don't need to be checked for, as the checkPythonChars | |
298 | # routine explicitely does so, to catch direct calls and rebindings of |
|
298 | # routine explicitely does so, to catch direct calls and rebindings of | |
299 | # existing names. |
|
299 | # existing names. | |
300 |
|
300 | |||
301 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
301 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
302 | # it affects the rest of the group in square brackets. |
|
302 | # it affects the rest of the group in square brackets. | |
303 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
303 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' | |
304 | r'|^is |^not |^in |^and |^or ') |
|
304 | r'|^is |^not |^in |^and |^or ') | |
305 |
|
305 | |||
306 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
306 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
307 | # (experimental). For this to work, the line_split regexp would need |
|
307 | # (experimental). For this to work, the line_split regexp would need | |
308 | # to be modified so it wouldn't break things at '['. That line is |
|
308 | # to be modified so it wouldn't break things at '['. That line is | |
309 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
309 | # nasty enough that I shouldn't change it until I can test it _well_. | |
310 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
310 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
311 |
|
311 | |||
312 | # Handler Check Utilities |
|
312 | # Handler Check Utilities | |
313 | def isShadowed(identifier,ip): |
|
313 | def isShadowed(identifier,ip): | |
314 | """Is the given identifier defined in one of the namespaces which shadow |
|
314 | """Is the given identifier defined in one of the namespaces which shadow | |
315 | the alias and magic namespaces? Note that an identifier is different |
|
315 | the alias and magic namespaces? Note that an identifier is different | |
316 | than iFun, because it can not contain a '.' character.""" |
|
316 | than iFun, because it can not contain a '.' character.""" | |
317 | # This is much safer than calling ofind, which can change state |
|
317 | # This is much safer than calling ofind, which can change state | |
318 | return (identifier in ip.user_ns \ |
|
318 | return (identifier in ip.user_ns \ | |
319 | or identifier in ip.internal_ns \ |
|
319 | or identifier in ip.internal_ns \ | |
320 | or identifier in ip.ns_table['builtin']) |
|
320 | or identifier in ip.ns_table['builtin']) | |
321 |
|
321 |
@@ -1,49 +1,49 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | class IPythonGrowlError(Exception): |
|
5 | class IPythonGrowlError(Exception): | |
6 | pass |
|
6 | pass | |
7 |
|
7 | |||
8 | class Notifier(object): |
|
8 | class Notifier(object): | |
9 |
|
9 | |||
10 | def __init__(self, app_name): |
|
10 | def __init__(self, app_name): | |
11 | try: |
|
11 | try: | |
12 | import Growl |
|
12 | import Growl | |
13 | except ImportError: |
|
13 | except ImportError: | |
14 | self.g_notifier = None |
|
14 | self.g_notifier = None | |
15 | else: |
|
15 | else: | |
16 | self.g_notifier = Growl.GrowlNotifier(app_name, ['kernel', 'core']) |
|
16 | self.g_notifier = Growl.GrowlNotifier(app_name, ['kernel', 'core']) | |
17 | self.g_notifier.register() |
|
17 | self.g_notifier.register() | |
18 |
|
18 | |||
19 | def _notify(self, title, msg): |
|
19 | def _notify(self, title, msg): | |
20 | if self.g_notifier is not None: |
|
20 | if self.g_notifier is not None: | |
21 |
self.g_notifier.notify(' |
|
21 | self.g_notifier.notify('core', title, msg) | |
22 |
|
22 | |||
23 | def notify(self, title, msg): |
|
23 | def notify(self, title, msg): | |
24 | self._notify(title, msg) |
|
24 | self._notify(title, msg) | |
25 |
|
25 | |||
26 | def notify_deferred(self, r, msg): |
|
26 | def notify_deferred(self, r, msg): | |
27 | title = "Deferred Result" |
|
27 | title = "Deferred Result" | |
28 | msg = msg + '\n' + repr(r) |
|
28 | msg = msg + '\n' + repr(r) | |
29 | self._notify(title, msg) |
|
29 | self._notify(title, msg) | |
30 | return r |
|
30 | return r | |
31 |
|
31 | |||
32 | _notifier = None |
|
32 | _notifier = None | |
33 |
|
33 | |||
34 | def notify(title, msg): |
|
34 | def notify(title, msg): | |
35 | pass |
|
35 | pass | |
36 |
|
36 | |||
37 | def notify_deferred(r, msg): |
|
37 | def notify_deferred(r, msg): | |
38 | return r |
|
38 | return r | |
39 |
|
39 | |||
40 | def start(app_name): |
|
40 | def start(app_name): | |
41 | global _notifier, notify, notify_deferred |
|
41 | global _notifier, notify, notify_deferred | |
42 | if _notifier is not None: |
|
42 | if _notifier is not None: | |
43 | raise IPythonGrowlError("this process is already registered with Growl") |
|
43 | raise IPythonGrowlError("this process is already registered with Growl") | |
44 | else: |
|
44 | else: | |
45 | _notifier = Notifier(app_name) |
|
45 | _notifier = Notifier(app_name) | |
46 | notify = _notifier.notify |
|
46 | notify = _notifier.notify | |
47 | notify_deferred = _notifier.notify_deferred |
|
47 | notify_deferred = _notifier.notify_deferred | |
48 |
|
48 | |||
49 |
|
49 |
General Comments 0
You need to be logged in to leave comments.
Login now