##// END OF EJS Templates
Merging from upstream trunk.
Brian Granger -
r2516:6b6d4719 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,184 b''
1 import os
2
3 c = get_config()
4
5 #-----------------------------------------------------------------------------
6 # Select which launchers to use
7 #-----------------------------------------------------------------------------
8
9 # This allows you to control what method is used to start the controller
10 # and engines. The following methods are currently supported:
11 # - Start as a regular process on localhost.
12 # - Start using mpiexec.
13 # - Start using the Windows HPC Server 2008 scheduler
14 # - Start using PBS
15 # - Start using SSH (currently broken)
16
17
18 # The selected launchers can be configured below.
19
20 # Options are:
21 # - LocalControllerLauncher
22 # - MPIExecControllerLauncher
23 # - PBSControllerLauncher
24 # - WindowsHPCControllerLauncher
25 # c.Global.controller_launcher = 'IPython.kernel.launcher.LocalControllerLauncher'
26
27 # Options are:
28 # - LocalEngineSetLauncher
29 # - MPIExecEngineSetLauncher
30 # - PBSEngineSetLauncher
31 # - WindowsHPCEngineSetLauncher
32 # c.Global.engine_launcher = 'IPython.kernel.launcher.LocalEngineSetLauncher'
33
34 #-----------------------------------------------------------------------------
35 # Global configuration
36 #-----------------------------------------------------------------------------
37
38 # The default number of engines that will be started. This is overridden by
39 # the -n command line option: "ipcluster start -n 4"
40 # c.Global.n = 2
41
42 # Log to a file in cluster_dir/log, otherwise just log to sys.stdout.
43 # c.Global.log_to_file = False
44
45 # Remove old logs from cluster_dir/log before starting.
46 # c.Global.clean_logs = True
47
48 # The working directory for the process. The application will use os.chdir
49 # to change to this directory before starting.
50 # c.Global.work_dir = os.getcwd()
51
52
53 #-----------------------------------------------------------------------------
54 # Local process launchers
55 #-----------------------------------------------------------------------------
56
57 # The command line arguments to call the controller with.
58 # c.LocalControllerLauncher.controller_args = \
59 # ['--log-to-file','--log-level', '40']
60
61 # The working directory for the controller
62 # c.LocalEngineSetLauncher.work_dir = u''
63
64 # Command line argument passed to the engines.
65 # c.LocalEngineSetLauncher.engine_args = ['--log-to-file','--log-level', '40']
66
67 #-----------------------------------------------------------------------------
68 # MPIExec launchers
69 #-----------------------------------------------------------------------------
70
71 # The mpiexec/mpirun command to use in started the controller.
72 # c.MPIExecControllerLauncher.mpi_cmd = ['mpiexec']
73
74 # Additional arguments to pass to the actual mpiexec command.
75 # c.MPIExecControllerLauncher.mpi_args = []
76
77 # The command line argument to call the controller with.
78 # c.MPIExecControllerLauncher.controller_args = \
79 # ['--log-to-file','--log-level', '40']
80
81
82 # The mpiexec/mpirun command to use in started the controller.
83 # c.MPIExecEngineSetLauncher.mpi_cmd = ['mpiexec']
84
85 # Additional arguments to pass to the actual mpiexec command.
86 # c.MPIExecEngineSetLauncher.mpi_args = []
87
88 # Command line argument passed to the engines.
89 # c.MPIExecEngineSetLauncher.engine_args = ['--log-to-file','--log-level', '40']
90
91 # The default number of engines to start if not given elsewhere.
92 # c.MPIExecEngineSetLauncher.n = 1
93
94 #-----------------------------------------------------------------------------
95 # SSH launchers
96 #-----------------------------------------------------------------------------
97
98 # Todo
99
100
101 #-----------------------------------------------------------------------------
102 # Unix batch (PBS) schedulers launchers
103 #-----------------------------------------------------------------------------
104
105 # The command line program to use to submit a PBS job.
106 # c.PBSControllerLauncher.submit_command = 'qsub'
107
108 # The command line program to use to delete a PBS job.
109 # c.PBSControllerLauncher.delete_command = 'qdel'
110
111 # A regular expression that takes the output of qsub and find the job id.
112 # c.PBSControllerLauncher.job_id_regexp = r'\d+'
113
114 # The batch submission script used to start the controller. This is where
115 # environment variables would be setup, etc. This string is interpolated using
116 # the Itpl module in IPython.external. Basically, you can use ${n} for the
117 # number of engine and ${cluster_dir} for the cluster_dir.
118 # c.PBSControllerLauncher.batch_template = """"""
119
120 # The name of the instantiated batch script that will actually be used to
121 # submit the job. This will be written to the cluster directory.
122 # c.PBSControllerLauncher.batch_file_name = u'pbs_batch_script_controller'
123
124
125 # The command line program to use to submit a PBS job.
126 # c.PBSEngineSetLauncher.submit_command = 'qsub'
127
128 # The command line program to use to delete a PBS job.
129 # c.PBSEngineSetLauncher.delete_command = 'qdel'
130
131 # A regular expression that takes the output of qsub and find the job id.
132 # c.PBSEngineSetLauncher.job_id_regexp = r'\d+'
133
134 # The batch submission script used to start the engines. This is where
135 # environment variables would be setup, etc. This string is interpolated using
136 # the Itpl module in IPython.external. Basically, you can use ${n} for the
137 # number of engine and ${cluster_dir} for the cluster_dir.
138 # c.PBSEngineSetLauncher.batch_template = """"""
139
140 # The name of the instantiated batch script that will actually be used to
141 # submit the job. This will be written to the cluster directory.
142 # c.PBSEngineSetLauncher.batch_file_name = u'pbs_batch_script_engines'
143
144 #-----------------------------------------------------------------------------
145 # Windows HPC Server 2008 launcher configuration
146 #-----------------------------------------------------------------------------
147
148 # c.IPControllerJob.job_name = 'IPController'
149 # c.IPControllerJob.is_exclusive = False
150 # c.IPControllerJob.username = r'USERDOMAIN\USERNAME'
151 # c.IPControllerJob.priority = 'Highest'
152 # c.IPControllerJob.requested_nodes = ''
153 # c.IPControllerJob.project = 'MyProject'
154
155 # c.IPControllerTask.task_name = 'IPController'
156 # c.IPControllerTask.controller_cmd = [u'ipcontroller.exe']
157 # c.IPControllerTask.controller_args = ['--log-to-file', '--log-level', '40']
158 # c.IPControllerTask.environment_variables = {}
159
160 # c.WindowsHPCControllerLauncher.scheduler = 'HEADNODE'
161 # c.WindowsHPCControllerLauncher.job_file_name = u'ipcontroller_job.xml'
162
163
164 # c.IPEngineSetJob.job_name = 'IPEngineSet'
165 # c.IPEngineSetJob.is_exclusive = False
166 # c.IPEngineSetJob.username = r'USERDOMAIN\USERNAME'
167 # c.IPEngineSetJob.priority = 'Highest'
168 # c.IPEngineSetJob.requested_nodes = ''
169 # c.IPEngineSetJob.project = 'MyProject'
170
171 # c.IPEngineTask.task_name = 'IPEngine'
172 # c.IPEngineTask.engine_cmd = [u'ipengine.exe']
173 # c.IPEngineTask.engine_args = ['--log-to-file', '--log-level', '40']
174 # c.IPEngineTask.environment_variables = {}
175
176 # c.WindowsHPCEngineSetLauncher.scheduler = 'HEADNODE'
177 # c.WindowsHPCEngineSetLauncher.job_file_name = u'ipengineset_job.xml'
178
179
180
181
182
183
184
@@ -0,0 +1,136 b''
1 from IPython.config.loader import Config
2
3 c = get_config()
4
5 #-----------------------------------------------------------------------------
6 # Global configuration
7 #-----------------------------------------------------------------------------
8
9 # Basic Global config attributes
10
11 # Start up messages are logged to stdout using the logging module.
12 # These all happen before the twisted reactor is started and are
13 # useful for debugging purposes. Can be (10=DEBUG,20=INFO,30=WARN,40=CRITICAL)
14 # and smaller is more verbose.
15 # c.Global.log_level = 20
16
17 # Log to a file in cluster_dir/log, otherwise just log to sys.stdout.
18 # c.Global.log_to_file = False
19
20 # Remove old logs from cluster_dir/log before starting.
21 # c.Global.clean_logs = True
22
23 # A list of Python statements that will be run before starting the
24 # controller. This is provided because occasionally certain things need to
25 # be imported in the controller for pickling to work.
26 # c.Global.import_statements = ['import math']
27
28 # Reuse the controller's FURL files. If False, FURL files are regenerated
29 # each time the controller is run. If True, they will be reused, *but*, you
30 # also must set the network ports by hand. If set, this will override the
31 # values set for the client and engine connections below.
32 # c.Global.reuse_furls = True
33
34 # Enable SSL encryption on all connections to the controller. If set, this
35 # will override the values set for the client and engine connections below.
36 # c.Global.secure = True
37
38 # The working directory for the process. The application will use os.chdir
39 # to change to this directory before starting.
40 # c.Global.work_dir = os.getcwd()
41
42 #-----------------------------------------------------------------------------
43 # Configure the client services
44 #-----------------------------------------------------------------------------
45
46 # Basic client service config attributes
47
48 # The network interface the controller will listen on for client connections.
49 # This should be an IP address or hostname of the controller's host. The empty
50 # string means listen on all interfaces.
51 # c.FCClientServiceFactory.ip = ''
52
53 # The TCP/IP port the controller will listen on for client connections. If 0
54 # a random port will be used. If the controller's host has a firewall running
55 # it must allow incoming traffic on this port.
56 # c.FCClientServiceFactory.port = 0
57
58 # The client learns how to connect to the controller by looking at the
59 # location field embedded in the FURL. If this field is empty, all network
60 # interfaces that the controller is listening on will be listed. To have the
61 # client connect on a particular interface, list it here.
62 # c.FCClientServiceFactory.location = ''
63
64 # Use SSL encryption for the client connection.
65 # c.FCClientServiceFactory.secure = True
66
67 # Reuse the client FURL each time the controller is started. If set, you must
68 # also pick a specific network port above (FCClientServiceFactory.port).
69 # c.FCClientServiceFactory.reuse_furls = False
70
71 #-----------------------------------------------------------------------------
72 # Configure the engine services
73 #-----------------------------------------------------------------------------
74
75 # Basic config attributes for the engine services.
76
77 # The network interface the controller will listen on for engine connections.
78 # This should be an IP address or hostname of the controller's host. The empty
79 # string means listen on all interfaces.
80 # c.FCEngineServiceFactory.ip = ''
81
82 # The TCP/IP port the controller will listen on for engine connections. If 0
83 # a random port will be used. If the controller's host has a firewall running
84 # it must allow incoming traffic on this port.
85 # c.FCEngineServiceFactory.port = 0
86
87 # The engine learns how to connect to the controller by looking at the
88 # location field embedded in the FURL. If this field is empty, all network
89 # interfaces that the controller is listening on will be listed. To have the
90 # client connect on a particular interface, list it here.
91 # c.FCEngineServiceFactory.location = ''
92
93 # Use SSL encryption for the engine connection.
94 # c.FCEngineServiceFactory.secure = True
95
96 # Reuse the client FURL each time the controller is started. If set, you must
97 # also pick a specific network port above (FCClientServiceFactory.port).
98 # c.FCEngineServiceFactory.reuse_furls = False
99
100 #-----------------------------------------------------------------------------
101 # Developer level configuration attributes
102 #-----------------------------------------------------------------------------
103
104 # You shouldn't have to modify anything in this section. These attributes
105 # are more for developers who want to change the behavior of the controller
106 # at a fundamental level.
107
108 # c.FCClientServiceFactory.cert_file = u'ipcontroller-client.pem'
109
110 # default_client_interfaces = Config()
111 # default_client_interfaces.Task.interface_chain = [
112 # 'IPython.kernel.task.ITaskController',
113 # 'IPython.kernel.taskfc.IFCTaskController'
114 # ]
115 #
116 # default_client_interfaces.Task.furl_file = u'ipcontroller-tc.furl'
117 #
118 # default_client_interfaces.MultiEngine.interface_chain = [
119 # 'IPython.kernel.multiengine.IMultiEngine',
120 # 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine'
121 # ]
122 #
123 # default_client_interfaces.MultiEngine.furl_file = u'ipcontroller-mec.furl'
124 #
125 # c.FCEngineServiceFactory.interfaces = default_client_interfaces
126
127 # c.FCEngineServiceFactory.cert_file = u'ipcontroller-engine.pem'
128
129 # default_engine_interfaces = Config()
130 # default_engine_interfaces.Default.interface_chain = [
131 # 'IPython.kernel.enginefc.IFCControllerBase'
132 # ]
133 #
134 # default_engine_interfaces.Default.furl_file = u'ipcontroller-engine.furl'
135 #
136 # c.FCEngineServiceFactory.interfaces = default_engine_interfaces
@@ -0,0 +1,90 b''
1 c = get_config()
2
3 #-----------------------------------------------------------------------------
4 # Global configuration
5 #-----------------------------------------------------------------------------
6
7 # Start up messages are logged to stdout using the logging module.
8 # These all happen before the twisted reactor is started and are
9 # useful for debugging purposes. Can be (10=DEBUG,20=INFO,30=WARN,40=CRITICAL)
10 # and smaller is more verbose.
11 # c.Global.log_level = 20
12
13 # Log to a file in cluster_dir/log, otherwise just log to sys.stdout.
14 # c.Global.log_to_file = False
15
16 # Remove old logs from cluster_dir/log before starting.
17 # c.Global.clean_logs = True
18
19 # A list of strings that will be executed in the users namespace on the engine
20 # before it connects to the controller.
21 # c.Global.exec_lines = ['import numpy']
22
23 # The engine will try to connect to the controller multiple times, to allow
24 # the controller time to startup and write its FURL file. These parameters
25 # control the number of retries (connect_max_tries) and the initial delay
26 # (connect_delay) between attemps. The actual delay between attempts gets
27 # longer each time by a factor of 1.5 (delay[i] = 1.5*delay[i-1])
28 # those attemps.
29 # c.Global.connect_delay = 0.1
30 # c.Global.connect_max_tries = 15
31
32 # By default, the engine will look for the controller's FURL file in its own
33 # cluster directory. Sometimes, the FURL file will be elsewhere and this
34 # attribute can be set to the full path of the FURL file.
35 # c.Global.furl_file = u''
36
37 # The working directory for the process. The application will use os.chdir
38 # to change to this directory before starting.
39 # c.Global.work_dir = os.getcwd()
40
41 #-----------------------------------------------------------------------------
42 # MPI configuration
43 #-----------------------------------------------------------------------------
44
45 # Upon starting the engine can be configured to call MPI_Init. This section
46 # configures that.
47
48 # Select which MPI section to execute to setup MPI. The value of this
49 # attribute must match the name of another attribute in the MPI config
50 # section (mpi4py, pytrilinos, etc.). This can also be set by the --mpi
51 # command line option.
52 # c.MPI.use = ''
53
54 # Initialize MPI using mpi4py. To use this, set c.MPI.use = 'mpi4py' to use
55 # --mpi=mpi4py at the command line.
56 # c.MPI.mpi4py = """from mpi4py import MPI as mpi
57 # mpi.size = mpi.COMM_WORLD.Get_size()
58 # mpi.rank = mpi.COMM_WORLD.Get_rank()
59 # """
60
61 # Initialize MPI using pytrilinos. To use this, set c.MPI.use = 'pytrilinos'
62 # to use --mpi=pytrilinos at the command line.
63 # c.MPI.pytrilinos = """from PyTrilinos import Epetra
64 # class SimpleStruct:
65 # pass
66 # mpi = SimpleStruct()
67 # mpi.rank = 0
68 # mpi.size = 0
69 # """
70
71 #-----------------------------------------------------------------------------
72 # Developer level configuration attributes
73 #-----------------------------------------------------------------------------
74
75 # You shouldn't have to modify anything in this section. These attributes
76 # are more for developers who want to change the behavior of the controller
77 # at a fundamental level.
78
79 # You should not have to change these attributes.
80
81 # c.Global.shell_class = 'IPython.kernel.core.interpreter.Interpreter'
82
83 # c.Global.furl_file_name = u'ipcontroller-engine.furl'
84
85
86
87
88
89
90
@@ -0,0 +1,148 b''
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
3
4 #-----------------------------------------------------------------------------
5 # Global options
6 #-----------------------------------------------------------------------------
7
8 # c.Global.display_banner = True
9
10 # c.Global.classic = False
11
12 # c.Global.nosep = True
13
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
17
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
24 # 'myextension'
25 # ]
26
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
30 # 'import numpy',
31 # 'a = 10; b = 20',
32 # '1/0'
33 # ]
34
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
40 # 'mycode.py',
41 # 'fancy.ipy'
42 # ]
43
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
47
48 # c.InteractiveShell.autocall = 1
49
50 # c.InteractiveShell.autoedit_syntax = False
51
52 # c.InteractiveShell.autoindent = True
53
54 # c.InteractiveShell.automagic = False
55
56 # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
58 # c.InteractiveShell.banner2 = "This is for extra banner text"
59
60 # c.InteractiveShell.cache_size = 1000
61
62 # c.InteractiveShell.colors = 'LightBG'
63
64 # c.InteractiveShell.color_info = True
65
66 # c.InteractiveShell.confirm_exit = True
67
68 # c.InteractiveShell.deep_reload = False
69
70 # c.InteractiveShell.editor = 'nano'
71
72 # c.InteractiveShell.logstart = True
73
74 # c.InteractiveShell.logfile = u'ipython_log.py'
75
76 # c.InteractiveShell.logappend = u'mylog.py'
77
78 # c.InteractiveShell.object_info_string_level = 0
79
80 # c.InteractiveShell.pager = 'less'
81
82 # c.InteractiveShell.pdb = False
83
84 # c.InteractiveShell.pprint = True
85
86 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
87 # c.InteractiveShell.prompt_in2 = ' .\D.: '
88 # c.InteractiveShell.prompt_out = 'Out[\#]: '
89 # c.InteractiveShell.prompts_pad_left = True
90
91 # c.InteractiveShell.quiet = False
92
93 # Readline
94 # c.InteractiveShell.readline_use = True
95
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit_names = 0
116
117 # c.InteractiveShell.screen_length = 0
118
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
122
123 # c.InteractiveShell.system_header = "IPython system call: "
124
125 # c.InteractiveShell.system_verbose = True
126
127 # c.InteractiveShell.term_title = False
128
129 # c.InteractiveShell.wildcards_case_sensitive = True
130
131 # c.InteractiveShell.xmode = 'Context'
132
133 #-----------------------------------------------------------------------------
134 # PrefilterManager options
135 #-----------------------------------------------------------------------------
136
137 # c.PrefilterManager.multi_line_specials = True
138
139 #-----------------------------------------------------------------------------
140 # AliasManager options
141 #-----------------------------------------------------------------------------
142
143 # Do this to disable all defaults
144 # c.AliasManager.default_aliases = []
145
146 # c.AliasManager.user_aliases = [
147 # ('foo', 'echo Hi')
148 # ] No newline at end of file
@@ -0,0 +1,370 b''
1 # coding: utf-8
2 """A simple configuration system.
3
4 Authors
5 -------
6 * Brian Granger
7 * Fernando Perez
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
16
17 #-----------------------------------------------------------------------------
18 # Imports
19 #-----------------------------------------------------------------------------
20
21 import __builtin__
22 import os
23 import sys
24
25 from IPython.external import argparse
26 from IPython.utils.path import filefind
27
28 #-----------------------------------------------------------------------------
29 # Exceptions
30 #-----------------------------------------------------------------------------
31
32
33 class ConfigError(Exception):
34 pass
35
36
37 class ConfigLoaderError(ConfigError):
38 pass
39
40 #-----------------------------------------------------------------------------
41 # Argparse fix
42 #-----------------------------------------------------------------------------
43
44 # Unfortunately argparse by default prints help messages to stderr instead of
45 # stdout. This makes it annoying to capture long help screens at the command
46 # line, since one must know how to pipe stderr, which many users don't know how
47 # to do. So we override the print_help method with one that defaults to
48 # stdout and use our class instead.
49
50 class ArgumentParser(argparse.ArgumentParser):
51 """Simple argparse subclass that prints help to stdout by default."""
52
53 def print_help(self, file=None):
54 if file is None:
55 file = sys.stdout
56 return super(ArgumentParser, self).print_help(file)
57
58 print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
59
60 #-----------------------------------------------------------------------------
61 # Config class for holding config information
62 #-----------------------------------------------------------------------------
63
64
65 class Config(dict):
66 """An attribute based dict that can do smart merges."""
67
68 def __init__(self, *args, **kwds):
69 dict.__init__(self, *args, **kwds)
70 # This sets self.__dict__ = self, but it has to be done this way
71 # because we are also overriding __setattr__.
72 dict.__setattr__(self, '__dict__', self)
73
74 def _merge(self, other):
75 to_update = {}
76 for k, v in other.items():
77 if not self.has_key(k):
78 to_update[k] = v
79 else: # I have this key
80 if isinstance(v, Config):
81 # Recursively merge common sub Configs
82 self[k]._merge(v)
83 else:
84 # Plain updates for non-Configs
85 to_update[k] = v
86
87 self.update(to_update)
88
89 def _is_section_key(self, key):
90 if key[0].upper()==key[0] and not key.startswith('_'):
91 return True
92 else:
93 return False
94
95 def has_key(self, key):
96 if self._is_section_key(key):
97 return True
98 else:
99 return dict.has_key(self, key)
100
101 def _has_section(self, key):
102 if self._is_section_key(key):
103 if dict.has_key(self, key):
104 return True
105 return False
106
107 def copy(self):
108 return type(self)(dict.copy(self))
109
110 def __copy__(self):
111 return self.copy()
112
113 def __deepcopy__(self, memo):
114 import copy
115 return type(self)(copy.deepcopy(self.items()))
116
117 def __getitem__(self, key):
118 # Because we use this for an exec namespace, we need to delegate
119 # the lookup of names in __builtin__ to itself. This means
120 # that you can't have section or attribute names that are
121 # builtins.
122 try:
123 return getattr(__builtin__, key)
124 except AttributeError:
125 pass
126 if self._is_section_key(key):
127 try:
128 return dict.__getitem__(self, key)
129 except KeyError:
130 c = Config()
131 dict.__setitem__(self, key, c)
132 return c
133 else:
134 return dict.__getitem__(self, key)
135
136 def __setitem__(self, key, value):
137 # Don't allow names in __builtin__ to be modified.
138 if hasattr(__builtin__, key):
139 raise ConfigError('Config variable names cannot have the same name '
140 'as a Python builtin: %s' % key)
141 if self._is_section_key(key):
142 if not isinstance(value, Config):
143 raise ValueError('values whose keys begin with an uppercase '
144 'char must be Config instances: %r, %r' % (key, value))
145 else:
146 dict.__setitem__(self, key, value)
147
148 def __getattr__(self, key):
149 try:
150 return self.__getitem__(key)
151 except KeyError, e:
152 raise AttributeError(e)
153
154 def __setattr__(self, key, value):
155 try:
156 self.__setitem__(key, value)
157 except KeyError, e:
158 raise AttributeError(e)
159
160 def __delattr__(self, key):
161 try:
162 dict.__delitem__(self, key)
163 except KeyError, e:
164 raise AttributeError(e)
165
166
167 #-----------------------------------------------------------------------------
168 # Config loading classes
169 #-----------------------------------------------------------------------------
170
171
172 class ConfigLoader(object):
173 """A object for loading configurations from just about anywhere.
174
175 The resulting configuration is packaged as a :class:`Struct`.
176
177 Notes
178 -----
179 A :class:`ConfigLoader` does one thing: load a config from a source
180 (file, command line arguments) and returns the data as a :class:`Struct`.
181 There are lots of things that :class:`ConfigLoader` does not do. It does
182 not implement complex logic for finding config files. It does not handle
183 default values or merge multiple configs. These things need to be
184 handled elsewhere.
185 """
186
187 def __init__(self):
188 """A base class for config loaders.
189
190 Examples
191 --------
192
193 >>> cl = ConfigLoader()
194 >>> config = cl.load_config()
195 >>> config
196 {}
197 """
198 self.clear()
199
200 def clear(self):
201 self.config = Config()
202
203 def load_config(self):
204 """Load a config from somewhere, return a :class:`Config` instance.
205
206 Usually, this will cause self.config to be set and then returned.
207 However, in most cases, :meth:`ConfigLoader.clear` should be called
208 to erase any previous state.
209 """
210 self.clear()
211 return self.config
212
213
214 class FileConfigLoader(ConfigLoader):
215 """A base class for file based configurations.
216
217 As we add more file based config loaders, the common logic should go
218 here.
219 """
220 pass
221
222
223 class PyFileConfigLoader(FileConfigLoader):
224 """A config loader for pure python files.
225
226 This calls execfile on a plain python file and looks for attributes
227 that are all caps. These attribute are added to the config Struct.
228 """
229
230 def __init__(self, filename, path=None):
231 """Build a config loader for a filename and path.
232
233 Parameters
234 ----------
235 filename : str
236 The file name of the config file.
237 path : str, list, tuple
238 The path to search for the config file on, or a sequence of
239 paths to try in order.
240 """
241 super(PyFileConfigLoader, self).__init__()
242 self.filename = filename
243 self.path = path
244 self.full_filename = ''
245 self.data = None
246
247 def load_config(self):
248 """Load the config from a file and return it as a Struct."""
249 self.clear()
250 self._find_file()
251 self._read_file_as_dict()
252 self._convert_to_config()
253 return self.config
254
255 def _find_file(self):
256 """Try to find the file by searching the paths."""
257 self.full_filename = filefind(self.filename, self.path)
258
259 def _read_file_as_dict(self):
260 """Load the config file into self.config, with recursive loading."""
261 # This closure is made available in the namespace that is used
262 # to exec the config file. This allows users to call
263 # load_subconfig('myconfig.py') to load config files recursively.
264 # It needs to be a closure because it has references to self.path
265 # and self.config. The sub-config is loaded with the same path
266 # as the parent, but it uses an empty config which is then merged
267 # with the parents.
268 def load_subconfig(fname):
269 loader = PyFileConfigLoader(fname, self.path)
270 try:
271 sub_config = loader.load_config()
272 except IOError:
273 # Pass silently if the sub config is not there. This happens
274 # when a user us using a profile, but not the default config.
275 pass
276 else:
277 self.config._merge(sub_config)
278
279 # Again, this needs to be a closure and should be used in config
280 # files to get the config being loaded.
281 def get_config():
282 return self.config
283
284 namespace = dict(load_subconfig=load_subconfig, get_config=get_config)
285 execfile(self.full_filename, namespace)
286
287 def _convert_to_config(self):
288 if self.data is None:
289 ConfigLoaderError('self.data does not exist')
290
291
292 class CommandLineConfigLoader(ConfigLoader):
293 """A config loader for command line arguments.
294
295 As we add more command line based loaders, the common logic should go
296 here.
297 """
298
299
300 class ArgParseConfigLoader(CommandLineConfigLoader):
301
302 def __init__(self, argv=None, *parser_args, **parser_kw):
303 """Create a config loader for use with argparse.
304
305 Parameters
306 ----------
307
308 argv : optional, list
309 If given, used to read command-line arguments from, otherwise
310 sys.argv[1:] is used.
311
312 parser_args : tuple
313 A tuple of positional arguments that will be passed to the
314 constructor of :class:`argparse.ArgumentParser`.
315
316 parser_kw : dict
317 A tuple of keyword arguments that will be passed to the
318 constructor of :class:`argparse.ArgumentParser`.
319 """
320 super(CommandLineConfigLoader, self).__init__()
321 if argv == None:
322 argv = sys.argv[1:]
323 self.argv = argv
324 self.parser_args = parser_args
325 kwargs = dict(argument_default=argparse.SUPPRESS)
326 kwargs.update(parser_kw)
327 self.parser_kw = kwargs
328
329 def load_config(self, args=None):
330 """Parse command line arguments and return as a Struct.
331
332 Parameters
333 ----------
334
335 args : optional, list
336 If given, a list with the structure of sys.argv[1:] to parse
337 arguments from. If not given, the instance's self.argv attribute
338 (given at construction time) is used."""
339 self.clear()
340 if args is None:
341 args = self.argv
342 self._create_parser()
343 self._parse_args(args)
344 self._convert_to_config()
345 return self.config
346
347 def get_extra_args(self):
348 if hasattr(self, 'extra_args'):
349 return self.extra_args
350 else:
351 return []
352
353 def _create_parser(self):
354 self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
355 self._add_arguments()
356
357 def _add_arguments(self):
358 raise NotImplementedError("subclasses must implement _add_arguments")
359
360 def _parse_args(self, args):
361 """self.parser->self.parsed_data"""
362 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
363
364 def _convert_to_config(self):
365 """self.parsed_data->self.config"""
366 for k, v in vars(self.parsed_data).items():
367 exec_str = 'self.config.' + k + '= v'
368 exec exec_str in locals(), globals()
369
370
@@ -0,0 +1,24 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 lines = """
8 from IPython.kernel.client import *
9 """
10
11 # You have to make sure that attributes that are containers already
12 # exist before using them. Simple assigning a new list will override
13 # all previous values.
14 if hasattr(c.Global, 'exec_lines'):
15 c.Global.exec_lines.append(lines)
16 else:
17 c.Global.exec_lines = [lines]
18
19 # Load the parallelmagic extension to enable %result, %px, %autopx magics.
20 if hasattr(c.Global, 'extensions'):
21 c.Global.extensions.append('parallelmagic')
22 else:
23 c.Global.extensions = ['parallelmagic']
24
@@ -0,0 +1,19 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 lines = """
8 import cmath
9 from math import *
10 """
11
12 # You have to make sure that attributes that are containers already
13 # exist before using them. Simple assigning a new list will override
14 # all previous values.
15 if hasattr(c.Global, 'exec_lines'):
16 c.Global.exec_lines.append(lines)
17 else:
18 c.Global.exec_lines = [lines]
19
@@ -0,0 +1,20 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 lines = """
8 import numpy
9 import scipy
10 import numpy as np
11 import scipy as sp
12 """
13
14 # You have to make sure that attributes that are containers already
15 # exist before using them. Simple assigning a new list will override
16 # all previous values.
17 if hasattr(c.Global, 'exec_lines'):
18 c.Global.exec_lines.append(lines)
19 else:
20 c.Global.exec_lines = [lines] No newline at end of file
@@ -0,0 +1,22 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 lines = """
8 import matplotlib
9 %gui -a wx
10 matplotlib.use('wxagg')
11 matplotlib.interactive(True)
12 from matplotlib import pyplot as plt
13 from matplotlib.pyplot import *
14 """
15
16 # You have to make sure that attributes that are containers already
17 # exist before using them. Simple assigning a new list will override
18 # all previous values.
19 if hasattr(c.Global, 'exec_lines'):
20 c.Global.exec_lines.append(lines)
21 else:
22 c.Global.exec_lines = [lines] No newline at end of file
@@ -0,0 +1,29 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 c.InteractiveShell.prompt_in1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
8 c.InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
9 c.InteractiveShell.prompt_out = '<\#> '
10
11 c.InteractiveShell.prompts_pad_left = True
12
13 c.InteractiveShell.separate_in = ''
14 c.InteractiveShell.separate_out = ''
15 c.InteractiveShell.separate_out2 = ''
16
17 c.PrefilterManager.multi_line_specials = True
18
19 lines = """
20 %rehashx
21 """
22
23 # You have to make sure that attributes that are containers already
24 # exist before using them. Simple assigning a new list will override
25 # all previous values.
26 if hasattr(c.Global, 'exec_lines'):
27 c.Global.exec_lines.append(lines)
28 else:
29 c.Global.exec_lines = [lines] No newline at end of file
@@ -0,0 +1,21 b''
1 c = get_config()
2
3 # This can be used at any point in a config file to load a sub config
4 # and merge it into the current one.
5 load_subconfig('ipython_config.py')
6
7 lines = """
8 from __future__ import division
9 from sympy import *
10 x, y, z = symbols('xyz')
11 k, m, n = symbols('kmn', integer=True)
12 f, g, h = map(Function, 'fgh')
13 """
14
15 # You have to make sure that attributes that are containers already
16 # exist before using them. Simple assigning a new list will override
17 # all previous values.
18 if hasattr(c.Global, 'exec_lines'):
19 c.Global.exec_lines.append(lines)
20 else:
21 c.Global.exec_lines = [lines]
@@ -0,0 +1,5 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3
4
5
@@ -0,0 +1,174 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Tests for IPython.config.loader
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez (design help)
10 """
11
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
18
19 #-----------------------------------------------------------------------------
20 # Imports
21 #-----------------------------------------------------------------------------
22
23 import os
24 from tempfile import mkstemp
25 from unittest import TestCase
26
27 from IPython.config.loader import (
28 Config,
29 PyFileConfigLoader,
30 ArgParseConfigLoader,
31 ConfigError
32 )
33
34 #-----------------------------------------------------------------------------
35 # Actual tests
36 #-----------------------------------------------------------------------------
37
38
39 pyfile = """
40 c = get_config()
41 c.a = 10
42 c.b = 20
43 c.Foo.Bar.value = 10
44 c.Foo.Bam.value = range(10)
45 c.D.C.value = 'hi there'
46 """
47
48 class TestPyFileCL(TestCase):
49
50 def test_basic(self):
51 fd, fname = mkstemp('.py')
52 f = os.fdopen(fd, 'w')
53 f.write(pyfile)
54 f.close()
55 # Unlink the file
56 cl = PyFileConfigLoader(fname)
57 config = cl.load_config()
58 self.assertEquals(config.a, 10)
59 self.assertEquals(config.b, 20)
60 self.assertEquals(config.Foo.Bar.value, 10)
61 self.assertEquals(config.Foo.Bam.value, range(10))
62 self.assertEquals(config.D.C.value, 'hi there')
63
64 class MyLoader1(ArgParseConfigLoader):
65 def _add_arguments(self):
66 p = self.parser
67 p.add_argument('-f', '--foo', dest='Global.foo', type=str)
68 p.add_argument('-b', dest='MyClass.bar', type=int)
69 p.add_argument('-n', dest='n', action='store_true')
70 p.add_argument('Global.bam', type=str)
71
72 class MyLoader2(ArgParseConfigLoader):
73 def _add_arguments(self):
74 subparsers = self.parser.add_subparsers(dest='subparser_name')
75 subparser1 = subparsers.add_parser('1')
76 subparser1.add_argument('-x',dest='Global.x')
77 subparser2 = subparsers.add_parser('2')
78 subparser2.add_argument('y')
79
80 class TestArgParseCL(TestCase):
81
82 def test_basic(self):
83 cl = MyLoader1()
84 config = cl.load_config('-f hi -b 10 -n wow'.split())
85 self.assertEquals(config.Global.foo, 'hi')
86 self.assertEquals(config.MyClass.bar, 10)
87 self.assertEquals(config.n, True)
88 self.assertEquals(config.Global.bam, 'wow')
89 config = cl.load_config(['wow'])
90 self.assertEquals(config.keys(), ['Global'])
91 self.assertEquals(config.Global.keys(), ['bam'])
92 self.assertEquals(config.Global.bam, 'wow')
93
94 def test_add_arguments(self):
95 cl = MyLoader2()
96 config = cl.load_config('2 frobble'.split())
97 self.assertEquals(config.subparser_name, '2')
98 self.assertEquals(config.y, 'frobble')
99 config = cl.load_config('1 -x frobble'.split())
100 self.assertEquals(config.subparser_name, '1')
101 self.assertEquals(config.Global.x, 'frobble')
102
103 def test_argv(self):
104 cl = MyLoader1(argv='-f hi -b 10 -n wow'.split())
105 config = cl.load_config()
106 self.assertEquals(config.Global.foo, 'hi')
107 self.assertEquals(config.MyClass.bar, 10)
108 self.assertEquals(config.n, True)
109 self.assertEquals(config.Global.bam, 'wow')
110
111
112 class TestConfig(TestCase):
113
114 def test_setget(self):
115 c = Config()
116 c.a = 10
117 self.assertEquals(c.a, 10)
118 self.assertEquals(c.has_key('b'), False)
119
120 def test_auto_section(self):
121 c = Config()
122 self.assertEquals(c.has_key('A'), True)
123 self.assertEquals(c._has_section('A'), False)
124 A = c.A
125 A.foo = 'hi there'
126 self.assertEquals(c._has_section('A'), True)
127 self.assertEquals(c.A.foo, 'hi there')
128 del c.A
129 self.assertEquals(len(c.A.keys()),0)
130
131 def test_merge_doesnt_exist(self):
132 c1 = Config()
133 c2 = Config()
134 c2.bar = 10
135 c2.Foo.bar = 10
136 c1._merge(c2)
137 self.assertEquals(c1.Foo.bar, 10)
138 self.assertEquals(c1.bar, 10)
139 c2.Bar.bar = 10
140 c1._merge(c2)
141 self.assertEquals(c1.Bar.bar, 10)
142
143 def test_merge_exists(self):
144 c1 = Config()
145 c2 = Config()
146 c1.Foo.bar = 10
147 c1.Foo.bam = 30
148 c2.Foo.bar = 20
149 c2.Foo.wow = 40
150 c1._merge(c2)
151 self.assertEquals(c1.Foo.bam, 30)
152 self.assertEquals(c1.Foo.bar, 20)
153 self.assertEquals(c1.Foo.wow, 40)
154 c2.Foo.Bam.bam = 10
155 c1._merge(c2)
156 self.assertEquals(c1.Foo.Bam.bam, 10)
157
158 def test_deepcopy(self):
159 c1 = Config()
160 c1.Foo.bar = 10
161 c1.Foo.bam = 30
162 c1.a = 'asdf'
163 c1.b = range(10)
164 import copy
165 c2 = copy.deepcopy(c1)
166 self.assertEquals(c1, c2)
167 self.assert_(c1 is not c2)
168 self.assert_(c1.Foo is not c2.Foo)
169
170 def test_builtin(self):
171 c1 = Config()
172 exec 'foo = True' in c1
173 self.assertEquals(c1.foo, True)
174 self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10)
@@ -0,0 +1,262 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 re
26 import sys
27
28 from IPython.core.component import Component
29 from IPython.core.splitinput import split_user_input
30
31 from IPython.utils.traitlets import List
32 from IPython.utils.autoattr import auto_attr
33 from IPython.utils.warn import warn, error
34
35 #-----------------------------------------------------------------------------
36 # Utilities
37 #-----------------------------------------------------------------------------
38
39 # This is used as the pattern for calls to split_user_input.
40 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
41
42 def default_aliases():
43 # Make some aliases automatically
44 # Prepare list of shell aliases to auto-define
45 if os.name == 'posix':
46 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
47 'mv mv -i','rm rm -i','cp cp -i',
48 'cat cat','less less','clear clear',
49 # a better ls
50 'ls ls -F',
51 # long ls
52 'll ls -lF')
53 # Extra ls aliases with color, which need special treatment on BSD
54 # variants
55 ls_extra = ( # color ls
56 'lc ls -F -o --color',
57 # ls normal files only
58 'lf ls -F -o --color %l | grep ^-',
59 # ls symbolic links
60 'lk ls -F -o --color %l | grep ^l',
61 # directories or links to directories,
62 'ldir ls -F -o --color %l | grep /$',
63 # things which are executable
64 'lx ls -F -o --color %l | grep ^-..x',
65 )
66 # The BSDs don't ship GNU ls, so they don't understand the
67 # --color switch out of the box
68 if 'bsd' in sys.platform:
69 ls_extra = ( # ls normal files only
70 'lf ls -lF | grep ^-',
71 # ls symbolic links
72 'lk ls -lF | grep ^l',
73 # directories or links to directories,
74 'ldir ls -lF | grep /$',
75 # things which are executable
76 'lx ls -lF | grep ^-..x',
77 )
78 default_aliases = default_aliases + ls_extra
79 elif os.name in ['nt','dos']:
80 default_aliases = ('ls dir /on',
81 'ddir dir /ad /on', 'ldir dir /ad /on',
82 'mkdir mkdir','rmdir rmdir','echo echo',
83 'ren ren','cls cls','copy copy')
84 else:
85 default_aliases = ()
86 return [s.split(None,1) for s in default_aliases]
87
88
89 class AliasError(Exception):
90 pass
91
92
93 class InvalidAliasError(AliasError):
94 pass
95
96
97 #-----------------------------------------------------------------------------
98 # Main AliasManager class
99 #-----------------------------------------------------------------------------
100
101
102 class AliasManager(Component):
103
104 default_aliases = List(default_aliases(), config=True)
105 user_aliases = List(default_value=[], config=True)
106
107 def __init__(self, parent, config=None):
108 super(AliasManager, self).__init__(parent, config=config)
109 self.alias_table = {}
110 self.exclude_aliases()
111 self.init_aliases()
112
113 @auto_attr
114 def shell(self):
115 return Component.get_instances(
116 root=self.root,
117 klass='IPython.core.iplib.InteractiveShell')[0]
118
119 def __contains__(self, name):
120 if name in self.alias_table:
121 return True
122 else:
123 return False
124
125 @property
126 def aliases(self):
127 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
128
129 def exclude_aliases(self):
130 # set of things NOT to alias (keywords, builtins and some magics)
131 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
132 no_alias.update(set(keyword.kwlist))
133 no_alias.update(set(__builtin__.__dict__.keys()))
134 self.no_alias = no_alias
135
136 def init_aliases(self):
137 # Load default aliases
138 for name, cmd in self.default_aliases:
139 self.soft_define_alias(name, cmd)
140
141 # Load user aliases
142 for name, cmd in self.user_aliases:
143 self.soft_define_alias(name, cmd)
144
145 def clear_aliases(self):
146 self.alias_table.clear()
147
148 def soft_define_alias(self, name, cmd):
149 """Define an alias, but don't raise on an AliasError."""
150 try:
151 self.define_alias(name, cmd)
152 except AliasError, e:
153 error("Invalid alias: %s" % e)
154
155 def define_alias(self, name, cmd):
156 """Define a new alias after validating it.
157
158 This will raise an :exc:`AliasError` if there are validation
159 problems.
160 """
161 nargs = self.validate_alias(name, cmd)
162 self.alias_table[name] = (nargs, cmd)
163
164 def undefine_alias(self, name):
165 if self.alias_table.has_key(name):
166 del self.alias_table[name]
167
168 def validate_alias(self, name, cmd):
169 """Validate an alias and return the its number of arguments."""
170 if name in self.no_alias:
171 raise InvalidAliasError("The name %s can't be aliased "
172 "because it is a keyword or builtin." % name)
173 if not (isinstance(cmd, basestring)):
174 raise InvalidAliasError("An alias command must be a string, "
175 "got: %r" % name)
176 nargs = cmd.count('%s')
177 if nargs>0 and cmd.find('%l')>=0:
178 raise InvalidAliasError('The %s and %l specifiers are mutually '
179 'exclusive in alias definitions.')
180 return nargs
181
182 def call_alias(self, alias, rest=''):
183 """Call an alias given its name and the rest of the line."""
184 cmd = self.transform_alias(alias, rest)
185 try:
186 self.shell.system(cmd)
187 except:
188 self.shell.showtraceback()
189
190 def transform_alias(self, alias,rest=''):
191 """Transform alias to system command string."""
192 nargs, cmd = self.alias_table[alias]
193
194 if ' ' in cmd and os.path.isfile(cmd):
195 cmd = '"%s"' % cmd
196
197 # Expand the %l special to be the user's input line
198 if cmd.find('%l') >= 0:
199 cmd = cmd.replace('%l', rest)
200 rest = ''
201 if nargs==0:
202 # Simple, argument-less aliases
203 cmd = '%s %s' % (cmd, rest)
204 else:
205 # Handle aliases with positional arguments
206 args = rest.split(None, nargs)
207 if len(args) < nargs:
208 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
209 (alias, nargs, len(args)))
210 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
211 return cmd
212
213 def expand_alias(self, line):
214 """ Expand an alias in the command line
215
216 Returns the provided command line, possibly with the first word
217 (command) translated according to alias expansion rules.
218
219 [ipython]|16> _ip.expand_aliases("np myfile.txt")
220 <16> 'q:/opt/np/notepad++.exe myfile.txt'
221 """
222
223 pre,fn,rest = split_user_input(line)
224 res = pre + self.expand_aliases(fn, rest)
225 return res
226
227 def expand_aliases(self, fn, rest):
228 """Expand multiple levels of aliases:
229
230 if:
231
232 alias foo bar /tmp
233 alias baz foo
234
235 then:
236
237 baz huhhahhei -> bar /tmp huhhahhei
238
239 """
240 line = fn + " " + rest
241
242 done = set()
243 while 1:
244 pre,fn,rest = split_user_input(line, shell_line_split)
245 if fn in self.alias_table:
246 if fn in done:
247 warn("Cyclic alias definition, repeated '%s'" % fn)
248 return ""
249 done.add(fn)
250
251 l2 = self.transform_alias(fn, rest)
252 if l2 == line:
253 break
254 # ls -> ls -F should not recurse forever
255 if l2.split(None,1)[0] == line.split(None,1)[0]:
256 line = l2
257 break
258 line=l2
259 else:
260 break
261
262 return line
@@ -0,0 +1,453 b''
1 # encoding: utf-8
2 """
3 An application for IPython.
4
5 All top-level applications should use the classes in this module for
6 handling configuration and creating componenets.
7
8 The job of an :class:`Application` is to create the master configuration
9 object and then create the components, passing the config to them.
10
11 Authors:
12
13 * Brian Granger
14 * Fernando Perez
15
16 Notes
17 -----
18 """
19
20 #-----------------------------------------------------------------------------
21 # Copyright (C) 2008-2009 The IPython Development Team
22 #
23 # Distributed under the terms of the BSD License. The full license is in
24 # the file COPYING, distributed as part of this software.
25 #-----------------------------------------------------------------------------
26
27 #-----------------------------------------------------------------------------
28 # Imports
29 #-----------------------------------------------------------------------------
30
31 import logging
32 import os
33 import sys
34
35 from IPython.core import release, crashhandler
36 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
37 from IPython.config.loader import (
38 PyFileConfigLoader,
39 ArgParseConfigLoader,
40 Config,
41 )
42
43 #-----------------------------------------------------------------------------
44 # Classes and functions
45 #-----------------------------------------------------------------------------
46
47 class ApplicationError(Exception):
48 pass
49
50
51 class BaseAppConfigLoader(ArgParseConfigLoader):
52 """Default command line options for IPython based applications."""
53
54 def _add_ipython_dir(self, parser):
55 """Add the --ipython-dir option to the parser."""
56 paa = parser.add_argument
57 paa('--ipython-dir',
58 dest='Global.ipython_dir',type=unicode,
59 help=
60 """Set to override default location of the IPython directory
61 IPYTHON_DIR, stored as Global.ipython_dir. This can also be
62 specified through the environment variable IPYTHON_DIR.""",
63 metavar='Global.ipython_dir')
64
65 def _add_log_level(self, parser):
66 """Add the --log-level option to the parser."""
67 paa = parser.add_argument
68 paa('--log-level',
69 dest="Global.log_level",type=int,
70 help='Set the log level (0,10,20,30,40,50). Default is 30.',
71 metavar='Global.log_level')
72
73 def _add_arguments(self):
74 self._add_ipython_dir(self.parser)
75 self._add_log_level(self.parser)
76
77
78 class Application(object):
79 """Load a config, construct components and set them running.
80
81 The configuration of an application can be done via three different Config
82 objects, which are loaded and ultimately merged into a single one used
83 from that point on by the app. These are:
84
85 1. default_config: internal defaults, implemented in code.
86 2. file_config: read from the filesystem.
87 3. command_line_config: read from the system's command line flags.
88
89 During initialization, 3 is actually read before 2, since at the
90 command-line one may override the location of the file to be read. But the
91 above is the order in which the merge is made.
92 """
93
94 name = u'ipython'
95 description = 'IPython: an enhanced interactive Python shell.'
96 #: Usage message printed by argparse. If None, auto-generate
97 usage = None
98 #: The command line config loader. Subclass of ArgParseConfigLoader.
99 command_line_loader = BaseAppConfigLoader
100 #: The name of the config file to load, determined at runtime
101 config_file_name = None
102 #: The name of the default config file. Track separately from the actual
103 #: name because some logic happens only if we aren't using the default.
104 default_config_file_name = u'ipython_config.py'
105 default_log_level = logging.WARN
106 #: Set by --profile option
107 profile_name = None
108 #: User's ipython directory, typically ~/.ipython/
109 ipython_dir = None
110 #: Internal defaults, implemented in code.
111 default_config = None
112 #: Read from the filesystem.
113 file_config = None
114 #: Read from the system's command line flags.
115 command_line_config = None
116 #: The final config that will be passed to the component.
117 master_config = None
118 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
119 argv = None
120 #: extra arguments computed by the command-line loader
121 extra_args = None
122 #: The class to use as the crash handler.
123 crash_handler_class = crashhandler.CrashHandler
124
125 # Private attributes
126 _exiting = False
127 _initialized = False
128
129 def __init__(self, argv=None):
130 self.argv = sys.argv[1:] if argv is None else argv
131 self.init_logger()
132
133 def init_logger(self):
134 self.log = logging.getLogger(self.__class__.__name__)
135 # This is used as the default until the command line arguments are read.
136 self.log.setLevel(self.default_log_level)
137 self._log_handler = logging.StreamHandler()
138 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
139 self._log_handler.setFormatter(self._log_formatter)
140 self.log.addHandler(self._log_handler)
141
142 def _set_log_level(self, level):
143 self.log.setLevel(level)
144
145 def _get_log_level(self):
146 return self.log.level
147
148 log_level = property(_get_log_level, _set_log_level)
149
150 def initialize(self):
151 """Initialize the application.
152
153 Loads all configuration information and sets all application state, but
154 does not start any relevant processing (typically some kind of event
155 loop).
156
157 Once this method has been called, the application is flagged as
158 initialized and the method becomes a no-op."""
159
160 if self._initialized:
161 return
162
163 # The first part is protected with an 'attempt' wrapper, that will log
164 # failures with the basic system traceback machinery. Once our crash
165 # handler is in place, we can let any subsequent exception propagate,
166 # as our handler will log it with much better detail than the default.
167 self.attempt(self.create_crash_handler)
168
169 # Configuration phase
170 # Default config (internally hardwired in application code)
171 self.create_default_config()
172 self.log_default_config()
173 self.set_default_config_log_level()
174
175 # Command-line config
176 self.pre_load_command_line_config()
177 self.load_command_line_config()
178 self.set_command_line_config_log_level()
179 self.post_load_command_line_config()
180 self.log_command_line_config()
181
182 # Find resources needed for filesystem access, using information from
183 # the above two
184 self.find_ipython_dir()
185 self.find_resources()
186 self.find_config_file_name()
187 self.find_config_file_paths()
188
189 # File-based config
190 self.pre_load_file_config()
191 self.load_file_config()
192 self.set_file_config_log_level()
193 self.post_load_file_config()
194 self.log_file_config()
195
196 # Merge all config objects into a single one the app can then use
197 self.merge_configs()
198 self.log_master_config()
199
200 # Construction phase
201 self.pre_construct()
202 self.construct()
203 self.post_construct()
204
205 # Done, flag as such and
206 self._initialized = True
207
208 def start(self):
209 """Start the application."""
210 self.initialize()
211 self.start_app()
212
213 #-------------------------------------------------------------------------
214 # Various stages of Application creation
215 #-------------------------------------------------------------------------
216
217 def create_crash_handler(self):
218 """Create a crash handler, typically setting sys.excepthook to it."""
219 self.crash_handler = self.crash_handler_class(self)
220 sys.excepthook = self.crash_handler
221
222 def create_default_config(self):
223 """Create defaults that can't be set elsewhere.
224
225 For the most part, we try to set default in the class attributes
226 of Components. But, defaults the top-level Application (which is
227 not a HasTraitlets or Component) are not set in this way. Instead
228 we set them here. The Global section is for variables like this that
229 don't belong to a particular component.
230 """
231 c = Config()
232 c.Global.ipython_dir = get_ipython_dir()
233 c.Global.log_level = self.log_level
234 self.default_config = c
235
236 def log_default_config(self):
237 self.log.debug('Default config loaded:')
238 self.log.debug(repr(self.default_config))
239
240 def set_default_config_log_level(self):
241 try:
242 self.log_level = self.default_config.Global.log_level
243 except AttributeError:
244 # Fallback to the default_log_level class attribute
245 pass
246
247 def create_command_line_config(self):
248 """Create and return a command line config loader."""
249 return self.command_line_loader(
250 self.argv,
251 description=self.description,
252 version=release.version,
253 usage=self.usage
254 )
255
256 def pre_load_command_line_config(self):
257 """Do actions just before loading the command line config."""
258 pass
259
260 def load_command_line_config(self):
261 """Load the command line config."""
262 loader = self.create_command_line_config()
263 self.command_line_config = loader.load_config()
264 self.extra_args = loader.get_extra_args()
265
266 def set_command_line_config_log_level(self):
267 try:
268 self.log_level = self.command_line_config.Global.log_level
269 except AttributeError:
270 pass
271
272 def post_load_command_line_config(self):
273 """Do actions just after loading the command line config."""
274 pass
275
276 def log_command_line_config(self):
277 self.log.debug("Command line config loaded:")
278 self.log.debug(repr(self.command_line_config))
279
280 def find_ipython_dir(self):
281 """Set the IPython directory.
282
283 This sets ``self.ipython_dir``, but the actual value that is passed to
284 the application is kept in either ``self.default_config`` or
285 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
286 ``sys.path`` so config files there can be referenced by other config
287 files.
288 """
289
290 try:
291 self.ipython_dir = self.command_line_config.Global.ipython_dir
292 except AttributeError:
293 self.ipython_dir = self.default_config.Global.ipython_dir
294 sys.path.append(os.path.abspath(self.ipython_dir))
295 if not os.path.isdir(self.ipython_dir):
296 os.makedirs(self.ipython_dir, mode=0777)
297 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
298
299 def find_resources(self):
300 """Find other resources that need to be in place.
301
302 Things like cluster directories need to be in place to find the
303 config file. These happen right after the IPython directory has
304 been set.
305 """
306 pass
307
308 def find_config_file_name(self):
309 """Find the config file name for this application.
310
311 This must set ``self.config_file_name`` to the filename of the
312 config file to use (just the filename). The search paths for the
313 config file are set in :meth:`find_config_file_paths` and then passed
314 to the config file loader where they are resolved to an absolute path.
315
316 If a profile has been set at the command line, this will resolve it.
317 """
318 try:
319 self.config_file_name = self.command_line_config.Global.config_file
320 except AttributeError:
321 pass
322 else:
323 return
324
325 try:
326 self.profile_name = self.command_line_config.Global.profile
327 except AttributeError:
328 # Just use the default as there is no profile
329 self.config_file_name = self.default_config_file_name
330 else:
331 # Use the default config file name and profile name if set
332 # to determine the used config file name.
333 name_parts = self.default_config_file_name.split('.')
334 name_parts.insert(1, u'_' + self.profile_name + u'.')
335 self.config_file_name = ''.join(name_parts)
336
337 def find_config_file_paths(self):
338 """Set the search paths for resolving the config file.
339
340 This must set ``self.config_file_paths`` to a sequence of search
341 paths to pass to the config file loader.
342 """
343 # Include our own profiles directory last, so that users can still find
344 # our shipped copies of builtin profiles even if they don't have them
345 # in their local ipython directory.
346 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
347 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
348
349 def pre_load_file_config(self):
350 """Do actions before the config file is loaded."""
351 pass
352
353 def load_file_config(self):
354 """Load the config file.
355
356 This tries to load the config file from disk. If successful, the
357 ``CONFIG_FILE`` config variable is set to the resolved config file
358 location. If not successful, an empty config is used.
359 """
360 self.log.debug("Attempting to load config file: %s" %
361 self.config_file_name)
362 loader = PyFileConfigLoader(self.config_file_name,
363 path=self.config_file_paths)
364 try:
365 self.file_config = loader.load_config()
366 self.file_config.Global.config_file = loader.full_filename
367 except IOError:
368 # Only warn if the default config file was NOT being used.
369 if not self.config_file_name==self.default_config_file_name:
370 self.log.warn("Config file not found, skipping: %s" %
371 self.config_file_name, exc_info=True)
372 self.file_config = Config()
373 except:
374 self.log.warn("Error loading config file: %s" %
375 self.config_file_name, exc_info=True)
376 self.file_config = Config()
377
378 def set_file_config_log_level(self):
379 # We need to keeep self.log_level updated. But we only use the value
380 # of the file_config if a value was not specified at the command
381 # line, because the command line overrides everything.
382 if not hasattr(self.command_line_config.Global, 'log_level'):
383 try:
384 self.log_level = self.file_config.Global.log_level
385 except AttributeError:
386 pass # Use existing value
387
388 def post_load_file_config(self):
389 """Do actions after the config file is loaded."""
390 pass
391
392 def log_file_config(self):
393 if hasattr(self.file_config.Global, 'config_file'):
394 self.log.debug("Config file loaded: %s" %
395 self.file_config.Global.config_file)
396 self.log.debug(repr(self.file_config))
397
398 def merge_configs(self):
399 """Merge the default, command line and file config objects."""
400 config = Config()
401 config._merge(self.default_config)
402 config._merge(self.file_config)
403 config._merge(self.command_line_config)
404
405 # XXX fperez - propose to Brian we rename master_config to simply
406 # config, I think this is going to be heavily used in examples and
407 # application code and the name is shorter/easier to find/remember.
408 # For now, just alias it...
409 self.master_config = config
410 self.config = config
411
412 def log_master_config(self):
413 self.log.debug("Master config created:")
414 self.log.debug(repr(self.master_config))
415
416 def pre_construct(self):
417 """Do actions after the config has been built, but before construct."""
418 pass
419
420 def construct(self):
421 """Construct the main components that make up this app."""
422 self.log.debug("Constructing components for application")
423
424 def post_construct(self):
425 """Do actions after construct, but before starting the app."""
426 pass
427
428 def start_app(self):
429 """Actually start the app."""
430 self.log.debug("Starting application")
431
432 #-------------------------------------------------------------------------
433 # Utility methods
434 #-------------------------------------------------------------------------
435
436 def exit(self, exit_status=0):
437 if self._exiting:
438 pass
439 else:
440 self.log.debug("Exiting application: %s" % self.name)
441 self._exiting = True
442 sys.exit(exit_status)
443
444 def attempt(self, func):
445 try:
446 func()
447 except SystemExit:
448 raise
449 except:
450 self.log.critical("Aborting application: %s" % self.name,
451 exc_info=True)
452 self.exit(0)
453
@@ -0,0 +1,45 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Autocall capabilities for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26
27 #-----------------------------------------------------------------------------
28 # Code
29 #-----------------------------------------------------------------------------
30
31 class IPyAutocall(object):
32 """ Instances of this class are always autocalled
33
34 This happens regardless of 'autocall' variable state. Use this to
35 develop macro-like mechanisms.
36 """
37
38 def set_ip(self,ip):
39 """ Will be used to set _ip point to current ipython instance b/f call
40
41 Override this method if you don't want this to happen.
42
43 """
44 self._ip = ip
45
@@ -0,0 +1,118 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A context manager for managing things injected into :mod:`__builtin__`.
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
24 from IPython.core.component import Component
25 from IPython.core.quitter import Quitter
26
27 from IPython.utils.autoattr import auto_attr
28
29 #-----------------------------------------------------------------------------
30 # Classes and functions
31 #-----------------------------------------------------------------------------
32
33
34 class __BuiltinUndefined(object): pass
35 BuiltinUndefined = __BuiltinUndefined()
36
37
38 class BuiltinTrap(Component):
39
40 def __init__(self, parent):
41 super(BuiltinTrap, self).__init__(parent, None, None)
42 self._orig_builtins = {}
43 # We define this to track if a single BuiltinTrap is nested.
44 # Only turn off the trap when the outermost call to __exit__ is made.
45 self._nested_level = 0
46
47 @auto_attr
48 def shell(self):
49 return Component.get_instances(
50 root=self.root,
51 klass='IPython.core.iplib.InteractiveShell')[0]
52
53 def __enter__(self):
54 if self._nested_level == 0:
55 self.set()
56 self._nested_level += 1
57 # I return self, so callers can use add_builtin in a with clause.
58 return self
59
60 def __exit__(self, type, value, traceback):
61 if self._nested_level == 1:
62 self.unset()
63 self._nested_level -= 1
64 # Returning False will cause exceptions to propagate
65 return False
66
67 def add_builtin(self, key, value):
68 """Add a builtin and save the original."""
69 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
70 self._orig_builtins[key] = orig
71 __builtin__.__dict__[key] = value
72
73 def remove_builtin(self, key):
74 """Remove an added builtin and re-set the original."""
75 try:
76 orig = self._orig_builtins.pop(key)
77 except KeyError:
78 pass
79 else:
80 if orig is BuiltinUndefined:
81 del __builtin__.__dict__[key]
82 else:
83 __builtin__.__dict__[key] = orig
84
85 def set(self):
86 """Store ipython references in the __builtin__ namespace."""
87 self.add_builtin('exit', Quitter(self.shell, 'exit'))
88 self.add_builtin('quit', Quitter(self.shell, 'quit'))
89 self.add_builtin('get_ipython', self.shell.get_ipython)
90
91 # Recursive reload function
92 try:
93 from IPython.lib import deepreload
94 if self.shell.deep_reload:
95 self.add_builtin('reload', deepreload.reload)
96 else:
97 self.add_builtin('dreload', deepreload.reload)
98 del deepreload
99 except ImportError:
100 pass
101
102 # Keep in the builtins a flag for when IPython is active. We set it
103 # with setdefault so that multiple nested IPythons don't clobber one
104 # another. Each will increase its value by one upon being activated,
105 # which also gives us a way to determine the nesting level.
106 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
107
108 def unset(self):
109 """Remove any builtins which might have been added by add_builtins, or
110 restore overwritten ones to their previous values."""
111 for key in self._orig_builtins.keys():
112 self.remove_builtin(key)
113 self._orig_builtins.clear()
114 self._builtins_added = False
115 try:
116 del __builtin__.__dict__['__IPYTHON__active']
117 except KeyError:
118 pass
@@ -0,0 +1,346 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A lightweight component system for IPython.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10 """
11
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
18
19 #-----------------------------------------------------------------------------
20 # Imports
21 #-----------------------------------------------------------------------------
22
23 from copy import deepcopy
24 import datetime
25 from weakref import WeakValueDictionary
26
27 from IPython.utils.importstring import import_item
28 from IPython.config.loader import Config
29 from IPython.utils.traitlets import (
30 HasTraitlets, MetaHasTraitlets, Instance, This
31 )
32
33
34 #-----------------------------------------------------------------------------
35 # Helper classes for Components
36 #-----------------------------------------------------------------------------
37
38
39 class ComponentError(Exception):
40 pass
41
42 class MetaComponentTracker(type):
43 """A metaclass that tracks instances of Components and its subclasses."""
44
45 def __init__(cls, name, bases, d):
46 super(MetaComponentTracker, cls).__init__(name, bases, d)
47 cls.__instance_refs = WeakValueDictionary()
48 cls.__numcreated = 0
49
50 def __call__(cls, *args, **kw):
51 """Called when a class is called (instantiated)!!!
52
53 When a Component or subclass is instantiated, this is called and
54 the instance is saved in a WeakValueDictionary for tracking.
55 """
56 instance = cls.__new__(cls, *args, **kw)
57
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 = []
79 for c in cls.__mro__:
80 if issubclass(cls, c) and issubclass(c, Component):
81 c.__numcreated += 1
82 indices.append(c.__numcreated)
83 c.__instance_refs[c.__numcreated] = instance
84 else:
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
95
96 def clear_instances(cls):
97 """Clear all instances tracked by cls."""
98 cls.__instance_refs.clear()
99 cls.__numcreated = 0
100
101 def get_instances(cls, name=None, root=None, klass=None):
102 """Get all instances of cls and its subclasses.
103
104 Parameters
105 ----------
106 name : str
107 Limit to components with this name.
108 root : Component or subclass
109 Limit to components having this root.
110 klass : class or str
111 Limits to instances of the class or its subclasses. If a str
112 is given ut must be in the form 'foo.bar.MyClass'. The str
113 form of this argument is useful for forward declarations.
114 """
115 if klass is not None:
116 if isinstance(klass, basestring):
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)
121 instances = cls.__instance_refs.values()
122 if name is not None:
123 instances = [i for i in instances if i.name == name]
124 if klass is not None:
125 instances = [i for i in instances if isinstance(i, klass)]
126 if root is not None:
127 instances = [i for i in instances if i.root == root]
128 return instances
129
130 def get_instances_by_condition(cls, call, name=None, root=None,
131 klass=None):
132 """Get all instances of cls, i such that call(i)==True.
133
134 This also takes the ``name`` and ``root`` and ``classname``
135 arguments of :meth:`get_instance`
136 """
137 return [i for i in cls.get_instances(name, root, klass) if call(i)]
138
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
160 class __ComponentNameGenerator(object):
161 """A Singleton to generate unique component names."""
162
163 def __init__(self, prefix):
164 self.prefix = prefix
165 self.i = 0
166
167 def __call__(self):
168 count = self.i
169 self.i += 1
170 return "%s%s" % (self.prefix, count)
171
172
173 ComponentNameGenerator = __ComponentNameGenerator('ipython.component')
174
175
176 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
177 pass
178
179
180 #-----------------------------------------------------------------------------
181 # Component implementation
182 #-----------------------------------------------------------------------------
183
184
185 class Component(HasTraitlets):
186
187 __metaclass__ = MetaComponent
188
189 # Traitlets are fun!
190 config = Instance(Config,(),{})
191 parent = This()
192 root = This()
193 created = None
194
195 def __init__(self, parent, name=None, config=None):
196 """Create a component given a parent and possibly and name and config.
197
198 Parameters
199 ----------
200 parent : Component subclass
201 The parent in the component graph. The parent is used
202 to get the root of the component graph.
203 name : str
204 The unique name of the component. If empty, then a unique
205 one will be autogenerated.
206 config : Config
207 If this is empty, self.config = parent.config, otherwise
208 self.config = config and root.config is ignored. This argument
209 should only be used to *override* the automatic inheritance of
210 parent.config. If a caller wants to modify parent.config
211 (not override), the caller should make a copy and change
212 attributes and then pass the copy to this argument.
213
214 Notes
215 -----
216 Subclasses of Component must call the :meth:`__init__` method of
217 :class:`Component` *before* doing anything else and using
218 :func:`super`::
219
220 class MyComponent(Component):
221 def __init__(self, parent, name=None, config=None):
222 super(MyComponent, self).__init__(parent, name, config)
223 # Then any other code you need to finish initialization.
224
225 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
226 attributes are handled properly.
227 """
228 super(Component, self).__init__()
229 self._children = []
230 if name is None:
231 self.name = ComponentNameGenerator()
232 else:
233 self.name = name
234 self.root = self # This is the default, it is set when parent is set
235 self.parent = parent
236 if config is not None:
237 self.config = config
238 # We used to deepcopy, but for now we are trying to just save
239 # by reference. This *could* have side effects as all components
240 # will share config. In fact, I did find such a side effect in
241 # _config_changed below. If a config attribute value was a mutable type
242 # all instances of a component were getting the same copy, effectively
243 # making that a class attribute.
244 # self.config = deepcopy(config)
245 else:
246 if self.parent is not None:
247 self.config = self.parent.config
248 # We used to deepcopy, but for now we are trying to just save
249 # by reference. This *could* have side effects as all components
250 # will share config. In fact, I did find such a side effect in
251 # _config_changed below. If a config attribute value was a mutable type
252 # all instances of a component were getting the same copy, effectively
253 # making that a class attribute.
254 # self.config = deepcopy(self.parent.config)
255
256 self.created = datetime.datetime.now()
257
258 #-------------------------------------------------------------------------
259 # Static traitlet notifiations
260 #-------------------------------------------------------------------------
261
262 def _parent_changed(self, name, old, new):
263 if old is not None:
264 old._remove_child(self)
265 if new is not None:
266 new._add_child(self)
267
268 if new is None:
269 self.root = self
270 else:
271 self.root = new.root
272
273 def _root_changed(self, name, old, new):
274 if self.parent is None:
275 if not (new is self):
276 raise ComponentError("Root not self, but parent is None.")
277 else:
278 if not self.parent.root is new:
279 raise ComponentError("Error in setting the root attribute: "
280 "root != parent.root")
281
282 def _config_changed(self, name, old, new):
283 """Update all the class traits having ``config=True`` as metadata.
284
285 For any class traitlet with a ``config`` metadata attribute that is
286 ``True``, we update the traitlet with the value of the corresponding
287 config entry.
288 """
289 # Get all traitlets with a config metadata entry that is True
290 traitlets = self.traitlets(config=True)
291
292 # We auto-load config section for this class as well as any parent
293 # classes that are Component subclasses. This starts with Component
294 # and works down the mro loading the config for each section.
295 section_names = [cls.__name__ for cls in \
296 reversed(self.__class__.__mro__) if
297 issubclass(cls, Component) and issubclass(self.__class__, cls)]
298
299 for sname in section_names:
300 # Don't do a blind getattr as that would cause the config to
301 # dynamically create the section with name self.__class__.__name__.
302 if new._has_section(sname):
303 my_config = new[sname]
304 for k, v in traitlets.items():
305 # Don't allow traitlets with config=True to start with
306 # uppercase. Otherwise, they are confused with Config
307 # subsections. But, developers shouldn't have uppercase
308 # attributes anyways! (PEP 6)
309 if k[0].upper()==k[0] and not k.startswith('_'):
310 raise ComponentError('Component traitlets with '
311 'config=True must start with a lowercase so they are '
312 'not confused with Config subsections: %s.%s' % \
313 (self.__class__.__name__, k))
314 try:
315 # Here we grab the value from the config
316 # If k has the naming convention of a config
317 # section, it will be auto created.
318 config_value = my_config[k]
319 except KeyError:
320 pass
321 else:
322 # print "Setting %s.%s from %s.%s=%r" % \
323 # (self.__class__.__name__,k,sname,k,config_value)
324 # We have to do a deepcopy here if we don't deepcopy the entire
325 # config object. If we don't, a mutable config_value will be
326 # shared by all instances, effectively making it a class attribute.
327 setattr(self, k, deepcopy(config_value))
328
329 @property
330 def children(self):
331 """A list of all my child components."""
332 return self._children
333
334 def _remove_child(self, child):
335 """A private method for removing children components."""
336 if child in self._children:
337 index = self._children.index(child)
338 del self._children[index]
339
340 def _add_child(self, child):
341 """A private method for adding children components."""
342 if child not in self._children:
343 self._children.append(child)
344
345 def __repr__(self):
346 return "<%s('%s')>" % (self.__class__.__name__, self.name)
@@ -0,0 +1,180 b''
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
4 Authors:
5
6 * Fernando Perez
7 * Brian E. Granger
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2010 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 os
23 import sys
24 from pprint import pformat
25
26 from IPython.core import ultratb
27 from IPython.external.Itpl import itpl
28 from IPython.utils.sysinfo import sys_info
29
30 #-----------------------------------------------------------------------------
31 # Code
32 #-----------------------------------------------------------------------------
33
34 # Template for the user message.
35 _default_message_template = """\
36 Oops, $self.app_name crashed. We do our best to make it stable, but...
37
38 A crash report was automatically generated with the following information:
39 - A verbatim copy of the crash traceback.
40 - A copy of your input history during this session.
41 - Data on your current $self.app_name configuration.
42
43 It was left in the file named:
44 \t'$self.crash_report_fname'
45 If you can email this file to the developers, the information in it will help
46 them in understanding and correcting the problem.
47
48 You can mail it to: $self.contact_name at $self.contact_email
49 with the subject '$self.app_name Crash Report'.
50
51 If you want to do it now, the following command will work (under Unix):
52 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
53
54 To ensure accurate tracking of this issue, please file a report about it at:
55 $self.bug_tracker
56 """
57
58
59 class CrashHandler(object):
60 """Customizable crash handlers for IPython applications.
61
62 Instances of this class provide a :meth:`__call__` method which can be
63 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
64
65 def __call__(self, etype, evalue, etb)
66 """
67
68 message_template = _default_message_template
69
70 def __init__(self, app, contact_name=None, contact_email=None,
71 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
72 """Create a new crash handler
73
74 Parameters
75 ----------
76 app : Application
77 A running :class:`Application` instance, which will be queried at
78 crash time for internal information.
79
80 contact_name : str
81 A string with the name of the person to contact.
82
83 contact_email : str
84 A string with the email address of the contact.
85
86 bug_tracker : str
87 A string with the URL for your project's bug tracker.
88
89 show_crash_traceback : bool
90 If false, don't print the crash traceback on stderr, only generate
91 the on-disk report
92
93 Non-argument instance attributes:
94
95 These instances contain some non-argument attributes which allow for
96 further customization of the crash handler's behavior. Please see the
97 source for further details.
98 """
99 self.app = app
100 self.app_name = self.app.name
101 self.contact_name = contact_name
102 self.contact_email = contact_email
103 self.bug_tracker = bug_tracker
104 self.crash_report_fname = "Crash_report_%s.txt" % self.app_name
105 self.show_crash_traceback = show_crash_traceback
106 self.section_sep = '\n\n'+'*'*75+'\n\n'
107 self.call_pdb = call_pdb
108 #self.call_pdb = True # dbg
109
110 def __call__(self, etype, evalue, etb):
111 """Handle an exception, call for compatible with sys.excepthook"""
112
113 # Report tracebacks shouldn't use color in general (safer for users)
114 color_scheme = 'NoColor'
115
116 # Use this ONLY for developer debugging (keep commented out for release)
117 #color_scheme = 'Linux' # dbg
118
119 try:
120 rptdir = self.app.ipython_dir
121 except:
122 rptdir = os.getcwd()
123 if not os.path.isdir(rptdir):
124 rptdir = os.getcwd()
125 report_name = os.path.join(rptdir,self.crash_report_fname)
126 # write the report filename into the instance dict so it can get
127 # properly expanded out in the user message template
128 self.crash_report_fname = report_name
129 TBhandler = ultratb.VerboseTB(
130 color_scheme=color_scheme,
131 long_header=1,
132 call_pdb=self.call_pdb,
133 )
134 if self.call_pdb:
135 TBhandler(etype,evalue,etb)
136 return
137 else:
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
140 # print traceback to screen
141 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
143
144 # and generate a complete report on disk
145 try:
146 report = open(report_name,'w')
147 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
150
151 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.message_template)
153 print >> sys.stderr, msg
154
155 # Construct report on disk
156 report.write(self.make_report(traceback))
157 report.close()
158 raw_input("Hit <Enter> to quit this message (your terminal may close):")
159
160 def make_report(self,traceback):
161 """Return a string containing a crash report."""
162
163 sec_sep = self.section_sep
164
165 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
166 rpt_add = report.append
167 rpt_add(sys_info())
168
169 try:
170 config = pformat(self.app.config)
171 rpt_add(sec_sep)
172 rpt_add('Application name: %s\n\n' % self.app_name)
173 rpt_add('Current user configuration structure:\n\n')
174 rpt_add(config)
175 except:
176 pass
177 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
178
179 return ''.join(report)
180
@@ -0,0 +1,75 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 A context manager for handling sys.displayhook.
5
6 Authors:
7
8 * Robert Kern
9 * Brian Granger
10 """
11
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
18
19 #-----------------------------------------------------------------------------
20 # Imports
21 #-----------------------------------------------------------------------------
22
23 import sys
24
25 from IPython.core.component import Component
26
27 #-----------------------------------------------------------------------------
28 # Classes and functions
29 #-----------------------------------------------------------------------------
30
31
32 class DisplayTrap(Component):
33 """Object to manage sys.displayhook.
34
35 This came from IPython.core.kernel.display_hook, but is simplified
36 (no callbacks or formatters) until more of the core is refactored.
37 """
38
39 def __init__(self, parent, hook):
40 super(DisplayTrap, self).__init__(parent, None, None)
41 self.hook = hook
42 self.old_hook = None
43 # We define this to track if a single BuiltinTrap is nested.
44 # Only turn off the trap when the outermost call to __exit__ is made.
45 self._nested_level = 0
46
47 # @auto_attr
48 # def shell(self):
49 # return Component.get_instances(
50 # root=self.root,
51 # klass='IPython.core.iplib.InteractiveShell')[0]
52
53 def __enter__(self):
54 if self._nested_level == 0:
55 self.set()
56 self._nested_level += 1
57 return self
58
59 def __exit__(self, type, value, traceback):
60 if self._nested_level == 1:
61 self.unset()
62 self._nested_level -= 1
63 # Returning False will cause exceptions to propagate
64 return False
65
66 def set(self):
67 """Set the hook."""
68 if sys.displayhook is not self.hook:
69 self.old_hook = sys.displayhook
70 sys.displayhook = self.hook
71
72 def unset(self):
73 """Unset the hook."""
74 sys.displayhook = self.old_hook
75
@@ -0,0 +1,273 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 An embedded IPython shell.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 from __future__ import with_statement
27 import __main__
28
29 import sys
30 from contextlib import nested
31
32 from IPython.core import ultratb
33 from IPython.core.iplib import InteractiveShell
34 from IPython.core.ipapp import load_default_config
35
36 from IPython.utils.traitlets import Bool, Str, CBool
37 from IPython.utils.io import ask_yes_no
38
39
40 #-----------------------------------------------------------------------------
41 # Classes and functions
42 #-----------------------------------------------------------------------------
43
44 # This is an additional magic that is exposed in embedded shells.
45 def kill_embedded(self,parameter_s=''):
46 """%kill_embedded : deactivate for good the current embedded IPython.
47
48 This function (after asking for confirmation) sets an internal flag so that
49 an embedded IPython will never activate again. This is useful to
50 permanently disable a shell that is being called inside a loop: once you've
51 figured out what you needed from it, you may then kill it and the program
52 will then continue to run without the interactive shell interfering again.
53 """
54
55 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
56 "(y/n)? [y/N] ",'n')
57 if kill:
58 self.embedded_active = False
59 print "This embedded IPython will not reactivate anymore once you exit."
60
61
62 class InteractiveShellEmbed(InteractiveShell):
63
64 dummy_mode = Bool(False)
65 exit_msg = Str('')
66 embedded = CBool(True)
67 embedded_active = CBool(True)
68 # Like the base class display_banner is not configurable, but here it
69 # is True by default.
70 display_banner = CBool(True)
71
72 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
73 user_ns=None, user_global_ns=None,
74 banner1=None, banner2=None, display_banner=None,
75 custom_exceptions=((),None), exit_msg=''):
76
77 self.save_sys_ipcompleter()
78
79 super(InteractiveShellEmbed,self).__init__(
80 parent=parent, config=config, ipython_dir=ipython_dir, usage=usage,
81 user_ns=user_ns, user_global_ns=user_global_ns,
82 banner1=banner1, banner2=banner2, display_banner=display_banner,
83 custom_exceptions=custom_exceptions)
84
85 self.exit_msg = exit_msg
86 self.define_magic("kill_embedded", kill_embedded)
87
88 # don't use the ipython crash handler so that user exceptions aren't
89 # trapped
90 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
91 mode=self.xmode,
92 call_pdb=self.pdb)
93
94 self.restore_sys_ipcompleter()
95
96 def init_sys_modules(self):
97 pass
98
99 def save_sys_ipcompleter(self):
100 """Save readline completer status."""
101 try:
102 #print 'Save completer',sys.ipcompleter # dbg
103 self.sys_ipcompleter_orig = sys.ipcompleter
104 except:
105 pass # not nested with IPython
106
107 def restore_sys_ipcompleter(self):
108 """Restores the readline completer which was in place.
109
110 This allows embedded IPython within IPython not to disrupt the
111 parent's completion.
112 """
113 try:
114 self.readline.set_completer(self.sys_ipcompleter_orig)
115 sys.ipcompleter = self.sys_ipcompleter_orig
116 except:
117 pass
118
119 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
120 stack_depth=1):
121 """Activate the interactive interpreter.
122
123 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
124 the interpreter shell with the given local and global namespaces, and
125 optionally print a header string at startup.
126
127 The shell can be globally activated/deactivated using the
128 set/get_dummy_mode methods. This allows you to turn off a shell used
129 for debugging globally.
130
131 However, *each* time you call the shell you can override the current
132 state of dummy_mode with the optional keyword parameter 'dummy'. For
133 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
134 can still have a specific call work by making it as IPShell(dummy=0).
135
136 The optional keyword parameter dummy controls whether the call
137 actually does anything.
138 """
139
140 # If the user has turned it off, go away
141 if not self.embedded_active:
142 return
143
144 # Normal exits from interactive mode set this flag, so the shell can't
145 # re-enter (it checks this variable at the start of interactive mode).
146 self.exit_now = False
147
148 # Allow the dummy parameter to override the global __dummy_mode
149 if dummy or (dummy != 0 and self.dummy_mode):
150 return
151
152 if self.has_readline:
153 self.set_completer()
154
155 # self.banner is auto computed
156 if header:
157 self.old_banner2 = self.banner2
158 self.banner2 = self.banner2 + '\n' + header + '\n'
159
160 # Call the embedding code with a stack depth of 1 so it can skip over
161 # our call and get the original caller's namespaces.
162 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
163
164 self.banner2 = self.old_banner2
165
166 if self.exit_msg is not None:
167 print self.exit_msg
168
169 self.restore_sys_ipcompleter()
170
171 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
172 display_banner=None):
173 """Embeds IPython into a running python program.
174
175 Input:
176
177 - header: An optional header message can be specified.
178
179 - local_ns, global_ns: working namespaces. If given as None, the
180 IPython-initialized one is updated with __main__.__dict__, so that
181 program variables become visible but user-specific configuration
182 remains possible.
183
184 - stack_depth: specifies how many levels in the stack to go to
185 looking for namespaces (when local_ns and global_ns are None). This
186 allows an intermediate caller to make sure that this function gets
187 the namespace from the intended level in the stack. By default (0)
188 it will get its locals and globals from the immediate caller.
189
190 Warning: it's possible to use this in a program which is being run by
191 IPython itself (via %run), but some funny things will happen (a few
192 globals get overwritten). In the future this will be cleaned up, as
193 there is no fundamental reason why it can't work perfectly."""
194
195 # Get locals and globals from caller
196 if local_ns is None or global_ns is None:
197 call_frame = sys._getframe(stack_depth).f_back
198
199 if local_ns is None:
200 local_ns = call_frame.f_locals
201 if global_ns is None:
202 global_ns = call_frame.f_globals
203
204 # Update namespaces and fire up interpreter
205
206 # The global one is easy, we can just throw it in
207 self.user_global_ns = global_ns
208
209 # but the user/local one is tricky: ipython needs it to store internal
210 # data, but we also need the locals. We'll copy locals in the user
211 # one, but will track what got copied so we can delete them at exit.
212 # This is so that a later embedded call doesn't see locals from a
213 # previous call (which most likely existed in a separate scope).
214 local_varnames = local_ns.keys()
215 self.user_ns.update(local_ns)
216 #self.user_ns['local_ns'] = local_ns # dbg
217
218 # Patch for global embedding to make sure that things don't overwrite
219 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
220 # FIXME. Test this a bit more carefully (the if.. is new)
221 if local_ns is None and global_ns is None:
222 self.user_global_ns.update(__main__.__dict__)
223
224 # make sure the tab-completer has the correct frame information, so it
225 # actually completes using the frame's locals/globals
226 self.set_completer_frame()
227
228 with nested(self.builtin_trap, self.display_trap):
229 self.interact(display_banner=display_banner)
230
231 # now, purge out the user namespace from anything we might have added
232 # from the caller's local namespace
233 delvar = self.user_ns.pop
234 for var in local_varnames:
235 delvar(var,None)
236
237
238 _embedded_shell = None
239
240
241 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
242 display_banner=True, exit_msg=''):
243 """Call this to embed IPython at the current point in your program.
244
245 The first invocation of this will create an :class:`InteractiveShellEmbed`
246 instance and then call it. Consecutive calls just call the already
247 created instance.
248
249 Here is a simple example::
250
251 from IPython import embed
252 a = 10
253 b = 20
254 embed('First time')
255 c = 30
256 d = 40
257 embed
258
259 Full customization can be done by passing a :class:`Struct` in as the
260 config argument.
261 """
262 if config is None:
263 config = load_default_config()
264 config.InteractiveShellEmbed = config.InteractiveShell
265 global _embedded_shell
266 if _embedded_shell is None:
267 _embedded_shell = InteractiveShellEmbed(
268 config=config, usage=usage,
269 banner1=banner1, banner2=banner2,
270 display_banner=display_banner, exit_msg=exit_msg
271 )
272 _embedded_shell(header=header, stack_depth=2)
273
@@ -0,0 +1,52 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Global exception classes for IPython.core.
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13 """
14
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
21
22 #-----------------------------------------------------------------------------
23 # Imports
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Exception classes
28 #-----------------------------------------------------------------------------
29
30 class IPythonCoreError(Exception):
31 pass
32
33
34 class TryNext(IPythonCoreError):
35 """Try next hook exception.
36
37 Raise this in your hook function to indicate that the next hook handler
38 should be used to handle the operation. If you pass arguments to the
39 constructor those arguments will be used by the next hook instead of the
40 original ones.
41 """
42
43 def __init__(self, *args, **kwargs):
44 self.args = args
45 self.kwargs = kwargs
46
47 class UsageError(IPythonCoreError):
48 """Error in magic function arguments, etc.
49
50 Something that probably won't warrant a full traceback, but should
51 nevertheless interrupt a macro / batch file.
52 """ No newline at end of file
@@ -0,0 +1,36 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 This module is *completely* deprecated and should no longer be used for
5 any purpose. Currently, we have a few parts of the core that have
6 not been componentized and thus, still rely on this module. When everything
7 has been made into a component, this module will be sent to deathrow.
8 """
9
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2008-2009 The IPython Development Team
12 #
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
15 #-----------------------------------------------------------------------------
16
17 #-----------------------------------------------------------------------------
18 # Imports
19 #-----------------------------------------------------------------------------
20
21 #-----------------------------------------------------------------------------
22 # Classes and functions
23 #-----------------------------------------------------------------------------
24
25
26 def get():
27 """Get the most recently created InteractiveShell instance."""
28 from IPython.core.iplib import InteractiveShell
29 insts = InteractiveShell.get_instances()
30 if len(insts)==0:
31 return None
32 most_recent = insts[0]
33 for inst in insts[1:]:
34 if inst.created > most_recent.created:
35 most_recent = inst
36 return most_recent
This diff has been collapsed as it changes many lines, (653 lines changed) Show them Hide them
@@ -0,0 +1,653 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 The :class:`~IPython.core.application.Application` object for the command
5 line :command:`ipython` program.
6
7 Authors
8 -------
9
10 * Brian Granger
11 * Fernando Perez
12 """
13
14 #-----------------------------------------------------------------------------
15 # Copyright (C) 2008-2010 The IPython Development Team
16 #
17 # Distributed under the terms of the BSD License. The full license is in
18 # the file COPYING, distributed as part of this software.
19 #-----------------------------------------------------------------------------
20
21 #-----------------------------------------------------------------------------
22 # Imports
23 #-----------------------------------------------------------------------------
24
25 from __future__ import absolute_import
26
27 import logging
28 import os
29 import sys
30
31 from IPython.core import release
32 from IPython.core.crashhandler import CrashHandler
33 from IPython.core.application import Application, BaseAppConfigLoader
34 from IPython.core.iplib import InteractiveShell
35 from IPython.config.loader import (
36 Config,
37 PyFileConfigLoader
38 )
39 from IPython.lib import inputhook
40 from IPython.utils.path import filefind, get_ipython_dir
41 from . import usage
42
43 #-----------------------------------------------------------------------------
44 # Globals, utilities and helpers
45 #-----------------------------------------------------------------------------
46
47 #: The default config file name for this application.
48 default_config_file_name = u'ipython_config.py'
49
50
51 class IPAppConfigLoader(BaseAppConfigLoader):
52
53 def _add_arguments(self):
54 super(IPAppConfigLoader, self)._add_arguments()
55 paa = self.parser.add_argument
56 paa('-p',
57 '--profile', dest='Global.profile', type=unicode,
58 help=
59 """The string name of the ipython profile to be used. Assume that your
60 config file is ipython_config-<name>.py (looks in current dir first,
61 then in IPYTHON_DIR). This is a quick way to keep and load multiple
62 config files for different tasks, especially if include your basic one
63 in your more specialized ones. You can keep a basic
64 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
65 include this one and load extra things for particular tasks.""",
66 metavar='Global.profile')
67 paa('--config-file',
68 dest='Global.config_file', type=unicode,
69 help=
70 """Set the config file name to override default. Normally IPython
71 loads ipython_config.py (from current directory) or
72 IPYTHON_DIR/ipython_config.py. If the loading of your config file
73 fails, IPython starts with a bare bones configuration (no modules
74 loaded at all).""",
75 metavar='Global.config_file')
76 paa('--autocall',
77 dest='InteractiveShell.autocall', type=int,
78 help=
79 """Make IPython automatically call any callable object even if you
80 didn't type explicit parentheses. For example, 'str 43' becomes
81 'str(43)' automatically. The value can be '0' to disable the feature,
82 '1' for 'smart' autocall, where it is not applied if there are no more
83 arguments on the line, and '2' for 'full' autocall, where all callable
84 objects are automatically called (even if no arguments are present).
85 The default is '1'.""",
86 metavar='InteractiveShell.autocall')
87 paa('--autoindent',
88 action='store_true', dest='InteractiveShell.autoindent',
89 help='Turn on autoindenting.')
90 paa('--no-autoindent',
91 action='store_false', dest='InteractiveShell.autoindent',
92 help='Turn off autoindenting.')
93 paa('--automagic',
94 action='store_true', dest='InteractiveShell.automagic',
95 help=
96 """Turn on the auto calling of magic commands. Type %%magic at the
97 IPython prompt for more information.""")
98 paa('--no-automagic',
99 action='store_false', dest='InteractiveShell.automagic',
100 help='Turn off the auto calling of magic commands.')
101 paa('--autoedit-syntax',
102 action='store_true', dest='InteractiveShell.autoedit_syntax',
103 help='Turn on auto editing of files with syntax errors.')
104 paa('--no-autoedit-syntax',
105 action='store_false', dest='InteractiveShell.autoedit_syntax',
106 help='Turn off auto editing of files with syntax errors.')
107 paa('--banner',
108 action='store_true', dest='Global.display_banner',
109 help='Display a banner upon starting IPython.')
110 paa('--no-banner',
111 action='store_false', dest='Global.display_banner',
112 help="Don't display a banner upon starting IPython.")
113 paa('--cache-size',
114 type=int, dest='InteractiveShell.cache_size',
115 help=
116 """Set the size of the output cache. The default is 1000, you can
117 change it permanently in your config file. Setting it to 0 completely
118 disables the caching system, and the minimum value accepted is 20 (if
119 you provide a value less than 20, it is reset to 0 and a warning is
120 issued). This limit is defined because otherwise you'll spend more
121 time re-flushing a too small cache than working""",
122 metavar='InteractiveShell.cache_size')
123 paa('--classic',
124 action='store_true', dest='Global.classic',
125 help="Gives IPython a similar feel to the classic Python prompt.")
126 paa('--colors',
127 type=str, dest='InteractiveShell.colors',
128 help="Set the color scheme (NoColor, Linux, and LightBG).",
129 metavar='InteractiveShell.colors')
130 paa('--color-info',
131 action='store_true', dest='InteractiveShell.color_info',
132 help=
133 """IPython can display information about objects via a set of func-
134 tions, and optionally can use colors for this, syntax highlighting
135 source code and various other elements. However, because this
136 information is passed through a pager (like 'less') and many pagers get
137 confused with color codes, this option is off by default. You can test
138 it and turn it on permanently in your ipython_config.py file if it
139 works for you. Test it and turn it on permanently if it works with
140 your system. The magic function %%color_info allows you to toggle this
141 inter- actively for testing.""")
142 paa('--no-color-info',
143 action='store_false', dest='InteractiveShell.color_info',
144 help="Disable using colors for info related things.")
145 paa('--confirm-exit',
146 action='store_true', dest='InteractiveShell.confirm_exit',
147 help=
148 """Set to confirm when you try to exit IPython with an EOF (Control-D
149 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
150 '%%Exit', you can force a direct exit without any confirmation.""")
151 paa('--no-confirm-exit',
152 action='store_false', dest='InteractiveShell.confirm_exit',
153 help="Don't prompt the user when exiting.")
154 paa('--deep-reload',
155 action='store_true', dest='InteractiveShell.deep_reload',
156 help=
157 """Enable deep (recursive) reloading by default. IPython can use the
158 deep_reload module which reloads changes in modules recursively (it
159 replaces the reload() function, so you don't need to change anything to
160 use it). deep_reload() forces a full reload of modules whose code may
161 have changed, which the default reload() function does not. When
162 deep_reload is off, IPython will use the normal reload(), but
163 deep_reload will still be available as dreload(). This fea- ture is off
164 by default [which means that you have both normal reload() and
165 dreload()].""")
166 paa('--no-deep-reload',
167 action='store_false', dest='InteractiveShell.deep_reload',
168 help="Disable deep (recursive) reloading by default.")
169 paa('--editor',
170 type=str, dest='InteractiveShell.editor',
171 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
172 metavar='InteractiveShell.editor')
173 paa('--log','-l',
174 action='store_true', dest='InteractiveShell.logstart',
175 help="Start logging to the default log file (./ipython_log.py).")
176 paa('--logfile','-lf',
177 type=unicode, dest='InteractiveShell.logfile',
178 help="Start logging to logfile with this name.",
179 metavar='InteractiveShell.logfile')
180 paa('--log-append','-la',
181 type=unicode, dest='InteractiveShell.logappend',
182 help="Start logging to the given file in append mode.",
183 metavar='InteractiveShell.logfile')
184 paa('--pdb',
185 action='store_true', dest='InteractiveShell.pdb',
186 help="Enable auto calling the pdb debugger after every exception.")
187 paa('--no-pdb',
188 action='store_false', dest='InteractiveShell.pdb',
189 help="Disable auto calling the pdb debugger after every exception.")
190 paa('--pprint',
191 action='store_true', dest='InteractiveShell.pprint',
192 help="Enable auto pretty printing of results.")
193 paa('--no-pprint',
194 action='store_false', dest='InteractiveShell.pprint',
195 help="Disable auto auto pretty printing of results.")
196 paa('--prompt-in1','-pi1',
197 type=str, dest='InteractiveShell.prompt_in1',
198 help=
199 """Set the main input prompt ('In [\#]: '). Note that if you are using
200 numbered prompts, the number is represented with a '\#' in the string.
201 Don't forget to quote strings with spaces embedded in them. Most
202 bash-like escapes can be used to customize IPython's prompts, as well
203 as a few additional ones which are IPython-spe- cific. All valid
204 prompt escapes are described in detail in the Customization section of
205 the IPython manual.""",
206 metavar='InteractiveShell.prompt_in1')
207 paa('--prompt-in2','-pi2',
208 type=str, dest='InteractiveShell.prompt_in2',
209 help=
210 """Set the secondary input prompt (' .\D.: '). Similar to the previous
211 option, but used for the continuation prompts. The special sequence
212 '\D' is similar to '\#', but with all digits replaced by dots (so you
213 can have your continuation prompt aligned with your input prompt).
214 Default: ' .\D.: ' (note three spaces at the start for alignment with
215 'In [\#]')""",
216 metavar='InteractiveShell.prompt_in2')
217 paa('--prompt-out','-po',
218 type=str, dest='InteractiveShell.prompt_out',
219 help="Set the output prompt ('Out[\#]:')",
220 metavar='InteractiveShell.prompt_out')
221 paa('--quick',
222 action='store_true', dest='Global.quick',
223 help="Enable quick startup with no config files.")
224 paa('--readline',
225 action='store_true', dest='InteractiveShell.readline_use',
226 help="Enable readline for command line usage.")
227 paa('--no-readline',
228 action='store_false', dest='InteractiveShell.readline_use',
229 help="Disable readline for command line usage.")
230 paa('--screen-length','-sl',
231 type=int, dest='InteractiveShell.screen_length',
232 help=
233 """Number of lines of your screen, used to control printing of very
234 long strings. Strings longer than this number of lines will be sent
235 through a pager instead of directly printed. The default value for
236 this is 0, which means IPython will auto-detect your screen size every
237 time it needs to print certain potentially long strings (this doesn't
238 change the behavior of the 'print' keyword, it's only triggered
239 internally). If for some reason this isn't working well (it needs
240 curses support), specify it yourself. Otherwise don't change the
241 default.""",
242 metavar='InteractiveShell.screen_length')
243 paa('--separate-in','-si',
244 type=str, dest='InteractiveShell.separate_in',
245 help="Separator before input prompts. Default '\\n'.",
246 metavar='InteractiveShell.separate_in')
247 paa('--separate-out','-so',
248 type=str, dest='InteractiveShell.separate_out',
249 help="Separator before output prompts. Default 0 (nothing).",
250 metavar='InteractiveShell.separate_out')
251 paa('--separate-out2','-so2',
252 type=str, dest='InteractiveShell.separate_out2',
253 help="Separator after output prompts. Default 0 (nonight).",
254 metavar='InteractiveShell.separate_out2')
255 paa('--no-sep',
256 action='store_true', dest='Global.nosep',
257 help="Eliminate all spacing between prompts.")
258 paa('--term-title',
259 action='store_true', dest='InteractiveShell.term_title',
260 help="Enable auto setting the terminal title.")
261 paa('--no-term-title',
262 action='store_false', dest='InteractiveShell.term_title',
263 help="Disable auto setting the terminal title.")
264 paa('--xmode',
265 type=str, dest='InteractiveShell.xmode',
266 help=
267 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
268 similar to python's normal traceback printing. Context: prints 5 lines
269 of context source code around each line in the traceback. Verbose:
270 similar to Context, but additionally prints the variables currently
271 visible where the exception happened (shortening their strings if too
272 long). This can potentially be very slow, if you happen to have a huge
273 data structure whose string representation is complex to compute.
274 Your computer may appear to freeze for a while with cpu usage at 100%%.
275 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
276 it more than once).
277 """,
278 metavar='InteractiveShell.xmode')
279 paa('--ext',
280 type=str, dest='Global.extra_extension',
281 help="The dotted module name of an IPython extension to load.",
282 metavar='Global.extra_extension')
283 paa('-c',
284 type=str, dest='Global.code_to_run',
285 help="Execute the given command string.",
286 metavar='Global.code_to_run')
287 paa('-i',
288 action='store_true', dest='Global.force_interact',
289 help=
290 "If running code from the command line, become interactive afterwards.")
291
292 # Options to start with GUI control enabled from the beginning
293 paa('--gui',
294 type=str, dest='Global.gui',
295 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
296 metavar='gui-mode')
297 paa('--pylab','-pylab',
298 type=str, dest='Global.pylab',
299 nargs='?', const='auto', metavar='gui-mode',
300 help="Pre-load matplotlib and numpy for interactive use. "+
301 "If no value is given, the gui backend is matplotlib's, else use "+
302 "one of: ['tk', 'qt', 'wx', 'gtk'].")
303
304 # Legacy GUI options. Leave them in for backwards compatibility, but the
305 # 'thread' names are really a misnomer now.
306 paa('--wthread', '-wthread',
307 action='store_true', dest='Global.wthread',
308 help=
309 """Enable wxPython event loop integration. (DEPRECATED, use --gui wx)""")
310 paa('--q4thread', '--qthread', '-q4thread', '-qthread',
311 action='store_true', dest='Global.q4thread',
312 help=
313 """Enable Qt4 event loop integration. Qt3 is no longer supported.
314 (DEPRECATED, use --gui qt)""")
315 paa('--gthread', '-gthread',
316 action='store_true', dest='Global.gthread',
317 help=
318 """Enable GTK event loop integration. (DEPRECATED, use --gui gtk)""")
319
320
321 #-----------------------------------------------------------------------------
322 # Crash handler for this application
323 #-----------------------------------------------------------------------------
324
325
326 _message_template = """\
327 Oops, $self.app_name crashed. We do our best to make it stable, but...
328
329 A crash report was automatically generated with the following information:
330 - A verbatim copy of the crash traceback.
331 - A copy of your input history during this session.
332 - Data on your current $self.app_name configuration.
333
334 It was left in the file named:
335 \t'$self.crash_report_fname'
336 If you can email this file to the developers, the information in it will help
337 them in understanding and correcting the problem.
338
339 You can mail it to: $self.contact_name at $self.contact_email
340 with the subject '$self.app_name Crash Report'.
341
342 If you want to do it now, the following command will work (under Unix):
343 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
344
345 To ensure accurate tracking of this issue, please file a report about it at:
346 $self.bug_tracker
347 """
348
349 class IPAppCrashHandler(CrashHandler):
350 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
351
352 message_template = _message_template
353
354 def __init__(self, app):
355 contact_name = release.authors['Fernando'][0]
356 contact_email = release.authors['Fernando'][1]
357 bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug'
358 super(IPAppCrashHandler,self).__init__(
359 app, contact_name, contact_email, bug_tracker
360 )
361
362 def make_report(self,traceback):
363 """Return a string containing a crash report."""
364
365 sec_sep = self.section_sep
366 # Start with parent report
367 report = [super(IPAppCrashHandler, self).make_report(traceback)]
368 # Add interactive-specific info we may have
369 rpt_add = report.append
370 try:
371 rpt_add(sec_sep+"History of session input:")
372 for line in self.app.shell.user_ns['_ih']:
373 rpt_add(line)
374 rpt_add('\n*** Last line of input (may not be in above history):\n')
375 rpt_add(self.app.shell._last_input_line+'\n')
376 except:
377 pass
378
379 return ''.join(report)
380
381
382 #-----------------------------------------------------------------------------
383 # Main classes and functions
384 #-----------------------------------------------------------------------------
385
386 class IPythonApp(Application):
387 name = u'ipython'
388 #: argparse formats better the 'usage' than the 'description' field
389 description = None
390 usage = usage.cl_usage
391 command_line_loader = IPAppConfigLoader
392 default_config_file_name = default_config_file_name
393 crash_handler_class = IPAppCrashHandler
394
395 def create_default_config(self):
396 super(IPythonApp, self).create_default_config()
397 # Eliminate multiple lookups
398 Global = self.default_config.Global
399
400 # Set all default values
401 Global.display_banner = True
402
403 # If the -c flag is given or a file is given to run at the cmd line
404 # like "ipython foo.py", normally we exit without starting the main
405 # loop. The force_interact config variable allows a user to override
406 # this and interact. It is also set by the -i cmd line flag, just
407 # like Python.
408 Global.force_interact = False
409
410 # By default always interact by starting the IPython mainloop.
411 Global.interact = True
412
413 # No GUI integration by default
414 Global.gui = False
415 # Pylab off by default
416 Global.pylab = False
417
418 # Deprecated versions of gui support that used threading, we support
419 # them just for bacwards compatibility as an alternate spelling for
420 # '--gui X'
421 Global.qthread = False
422 Global.q4thread = False
423 Global.wthread = False
424 Global.gthread = False
425
426 def load_file_config(self):
427 if hasattr(self.command_line_config.Global, 'quick'):
428 if self.command_line_config.Global.quick:
429 self.file_config = Config()
430 return
431 super(IPythonApp, self).load_file_config()
432
433 def post_load_file_config(self):
434 if hasattr(self.command_line_config.Global, 'extra_extension'):
435 if not hasattr(self.file_config.Global, 'extensions'):
436 self.file_config.Global.extensions = []
437 self.file_config.Global.extensions.append(
438 self.command_line_config.Global.extra_extension)
439 del self.command_line_config.Global.extra_extension
440
441 def pre_construct(self):
442 config = self.master_config
443
444 if hasattr(config.Global, 'classic'):
445 if config.Global.classic:
446 config.InteractiveShell.cache_size = 0
447 config.InteractiveShell.pprint = 0
448 config.InteractiveShell.prompt_in1 = '>>> '
449 config.InteractiveShell.prompt_in2 = '... '
450 config.InteractiveShell.prompt_out = ''
451 config.InteractiveShell.separate_in = \
452 config.InteractiveShell.separate_out = \
453 config.InteractiveShell.separate_out2 = ''
454 config.InteractiveShell.colors = 'NoColor'
455 config.InteractiveShell.xmode = 'Plain'
456
457 if hasattr(config.Global, 'nosep'):
458 if config.Global.nosep:
459 config.InteractiveShell.separate_in = \
460 config.InteractiveShell.separate_out = \
461 config.InteractiveShell.separate_out2 = ''
462
463 # if there is code of files to run from the cmd line, don't interact
464 # unless the -i flag (Global.force_interact) is true.
465 code_to_run = config.Global.get('code_to_run','')
466 file_to_run = False
467 if self.extra_args and self.extra_args[0]:
468 file_to_run = True
469 if file_to_run or code_to_run:
470 if not config.Global.force_interact:
471 config.Global.interact = False
472
473 def construct(self):
474 # I am a little hesitant to put these into InteractiveShell itself.
475 # But that might be the place for them
476 sys.path.insert(0, '')
477
478 # Create an InteractiveShell instance
479 self.shell = InteractiveShell(None, self.master_config)
480
481 def post_construct(self):
482 """Do actions after construct, but before starting the app."""
483 config = self.master_config
484
485 # shell.display_banner should always be False for the terminal
486 # based app, because we call shell.show_banner() by hand below
487 # so the banner shows *before* all extension loading stuff.
488 self.shell.display_banner = False
489 if config.Global.display_banner and \
490 config.Global.interact:
491 self.shell.show_banner()
492
493 # Make sure there is a space below the banner.
494 if self.log_level <= logging.INFO: print
495
496 # Now a variety of things that happen after the banner is printed.
497 self._enable_gui_pylab()
498 self._load_extensions()
499 self._run_exec_lines()
500 self._run_exec_files()
501 self._run_cmd_line_code()
502
503 def _enable_gui_pylab(self):
504 """Enable GUI event loop integration, taking pylab into account."""
505 Global = self.master_config.Global
506
507 # Select which gui to use
508 if Global.gui:
509 gui = Global.gui
510 # The following are deprecated, but there's likely to be a lot of use
511 # of this form out there, so we might as well support it for now. But
512 # the --gui option above takes precedence.
513 elif Global.wthread:
514 gui = inputhook.GUI_WX
515 elif Global.qthread:
516 gui = inputhook.GUI_QT
517 elif Global.gthread:
518 gui = inputhook.GUI_GTK
519 else:
520 gui = None
521
522 # Using --pylab will also require gui activation, though which toolkit
523 # to use may be chosen automatically based on mpl configuration.
524 if Global.pylab:
525 activate = self.shell.enable_pylab
526 if Global.pylab == 'auto':
527 gui = None
528 else:
529 gui = Global.pylab
530 else:
531 # Enable only GUI integration, no pylab
532 activate = inputhook.enable_gui
533
534 if gui or Global.pylab:
535 try:
536 self.log.info("Enabling GUI event loop integration, "
537 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
538 activate(gui)
539 except:
540 self.log.warn("Error in enabling GUI event loop integration:")
541 self.shell.showtraceback()
542
543 def _load_extensions(self):
544 """Load all IPython extensions in Global.extensions.
545
546 This uses the :meth:`InteractiveShell.load_extensions` to load all
547 the extensions listed in ``self.master_config.Global.extensions``.
548 """
549 try:
550 if hasattr(self.master_config.Global, 'extensions'):
551 self.log.debug("Loading IPython extensions...")
552 extensions = self.master_config.Global.extensions
553 for ext in extensions:
554 try:
555 self.log.info("Loading IPython extension: %s" % ext)
556 self.shell.load_extension(ext)
557 except:
558 self.log.warn("Error in loading extension: %s" % ext)
559 self.shell.showtraceback()
560 except:
561 self.log.warn("Unknown error in loading extensions:")
562 self.shell.showtraceback()
563
564 def _run_exec_lines(self):
565 """Run lines of code in Global.exec_lines in the user's namespace."""
566 try:
567 if hasattr(self.master_config.Global, 'exec_lines'):
568 self.log.debug("Running code from Global.exec_lines...")
569 exec_lines = self.master_config.Global.exec_lines
570 for line in exec_lines:
571 try:
572 self.log.info("Running code in user namespace: %s" % line)
573 self.shell.runlines(line)
574 except:
575 self.log.warn("Error in executing line in user namespace: %s" % line)
576 self.shell.showtraceback()
577 except:
578 self.log.warn("Unknown error in handling Global.exec_lines:")
579 self.shell.showtraceback()
580
581 def _exec_file(self, fname):
582 full_filename = filefind(fname, [u'.', self.ipython_dir])
583 if os.path.isfile(full_filename):
584 if full_filename.endswith(u'.py'):
585 self.log.info("Running file in user namespace: %s" % full_filename)
586 self.shell.safe_execfile(full_filename, self.shell.user_ns)
587 elif full_filename.endswith('.ipy'):
588 self.log.info("Running file in user namespace: %s" % full_filename)
589 self.shell.safe_execfile_ipy(full_filename)
590 else:
591 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
592
593 def _run_exec_files(self):
594 try:
595 if hasattr(self.master_config.Global, 'exec_files'):
596 self.log.debug("Running files in Global.exec_files...")
597 exec_files = self.master_config.Global.exec_files
598 for fname in exec_files:
599 self._exec_file(fname)
600 except:
601 self.log.warn("Unknown error in handling Global.exec_files:")
602 self.shell.showtraceback()
603
604 def _run_cmd_line_code(self):
605 if hasattr(self.master_config.Global, 'code_to_run'):
606 line = self.master_config.Global.code_to_run
607 try:
608 self.log.info("Running code given at command line (-c): %s" % line)
609 self.shell.runlines(line)
610 except:
611 self.log.warn("Error in executing line in user namespace: %s" % line)
612 self.shell.showtraceback()
613 return
614 # Like Python itself, ignore the second if the first of these is present
615 try:
616 fname = self.extra_args[0]
617 except:
618 pass
619 else:
620 try:
621 self._exec_file(fname)
622 except:
623 self.log.warn("Error in executing file in user namespace: %s" % fname)
624 self.shell.showtraceback()
625
626 def start_app(self):
627 if self.master_config.Global.interact:
628 self.log.debug("Starting IPython's mainloop...")
629 self.shell.mainloop()
630 else:
631 self.log.debug("IPython not interactive, start_app is no-op...")
632
633
634 def load_default_config(ipython_dir=None):
635 """Load the default config file from the default ipython_dir.
636
637 This is useful for embedded shells.
638 """
639 if ipython_dir is None:
640 ipython_dir = get_ipython_dir()
641 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
642 config = cl.load_config()
643 return config
644
645
646 def launch_new_instance():
647 """Create and run a full blown IPython instance"""
648 app = IPythonApp()
649 app.start()
650
651
652 if __name__ == '__main__':
653 launch_new_instance()
This diff has been collapsed as it changes many lines, (2561 lines changed) Show them Hide them
@@ -0,0 +1,2561 b''
1 # -*- coding: utf-8 -*-
2 """
3 Main IPython Component
4 """
5
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18
19 from __future__ import with_statement
20 from __future__ import absolute_import
21
22 import __builtin__
23 import bdb
24 import codeop
25 import exceptions
26 import new
27 import os
28 import re
29 import string
30 import sys
31 import tempfile
32 from contextlib import nested
33
34 from IPython.core import debugger, oinspect
35 from IPython.core import history as ipcorehist
36 from IPython.core import prefilter
37 from IPython.core import shadowns
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.component import Component
42 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.error import TryNext, UsageError
44 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
45 from IPython.core.logger import Logger
46 from IPython.core.magic import Magic
47 from IPython.core.prefilter import PrefilterManager
48 from IPython.core.prompts import CachedOutput
49 from IPython.core.usage import interactive_usage, default_banner
50 import IPython.core.hooks
51 from IPython.external.Itpl import ItplNS
52 from IPython.lib.inputhook import enable_gui
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.lib.pylabtools import pylab_activate
55 from IPython.utils import PyColorize
56 from IPython.utils import pickleshare
57 from IPython.utils.doctestreload import doctest_reload
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.io import Term, ask_yes_no
60 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
61 from IPython.utils.process import (
62 abbrev_cwd,
63 getoutput,
64 getoutputerror
65 )
66 # import IPython.utils.rlineimpl as readline
67 from IPython.utils.strdispatch import StrDispatch
68 from IPython.utils.syspathcontext import prepended_to_syspath
69 from IPython.utils.terminal import toggle_set_term_title, set_term_title
70 from IPython.utils.warn import warn, error, fatal
71 from IPython.utils.traitlets import (
72 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
73 )
74
75 # from IPython.utils import growl
76 # growl.start("IPython")
77
78 #-----------------------------------------------------------------------------
79 # Globals
80 #-----------------------------------------------------------------------------
81
82 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
85
86 # compiled regexps for autoindent management
87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88
89 #-----------------------------------------------------------------------------
90 # Utilities
91 #-----------------------------------------------------------------------------
92
93 ini_spaces_re = re.compile(r'^(\s+)')
94
95
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
98
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
101 return ini_spaces.end()
102 else:
103 return 0
104
105
106 def softspace(file, newvalue):
107 """Copied from code.py, to remove the dependency"""
108
109 oldvalue = 0
110 try:
111 oldvalue = file.softspace
112 except AttributeError:
113 pass
114 try:
115 file.softspace = newvalue
116 except (AttributeError, TypeError):
117 # "attribute-less object" or "read-only attributes"
118 pass
119 return oldvalue
120
121
122 def no_op(*a, **kw): pass
123
124 class SpaceInInput(exceptions.Exception): pass
125
126 class Bunch: pass
127
128 class InputList(list):
129 """Class to store user input.
130
131 It's basically a list, but slices return a string instead of a list, thus
132 allowing things like (assuming 'In' is an instance):
133
134 exec In[4:7]
135
136 or
137
138 exec In[5:9] + In[14] + In[21:25]"""
139
140 def __getslice__(self,i,j):
141 return ''.join(list.__getslice__(self,i,j))
142
143
144 class SyntaxTB(ultratb.ListTB):
145 """Extension which holds some state: the last exception value"""
146
147 def __init__(self,color_scheme = 'NoColor'):
148 ultratb.ListTB.__init__(self,color_scheme)
149 self.last_syntax_error = None
150
151 def __call__(self, etype, value, elist):
152 self.last_syntax_error = value
153 ultratb.ListTB.__call__(self,etype,value,elist)
154
155 def clear_err_state(self):
156 """Return the current error state and clear it"""
157 e = self.last_syntax_error
158 self.last_syntax_error = None
159 return e
160
161
162 def get_default_editor():
163 try:
164 ed = os.environ['EDITOR']
165 except KeyError:
166 if os.name == 'posix':
167 ed = 'vi' # the only one guaranteed to be there!
168 else:
169 ed = 'notepad' # same in Windows!
170 return ed
171
172
173 def get_default_colors():
174 if sys.platform=='darwin':
175 return "LightBG"
176 elif os.name=='nt':
177 return 'Linux'
178 else:
179 return 'Linux'
180
181
182 class SeparateStr(Str):
183 """A Str subclass to validate separate_in, separate_out, etc.
184
185 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
186 """
187
188 def validate(self, obj, value):
189 if value == '0': value = ''
190 value = value.replace('\\n','\n')
191 return super(SeparateStr, self).validate(obj, value)
192
193
194 #-----------------------------------------------------------------------------
195 # Main IPython class
196 #-----------------------------------------------------------------------------
197
198
199 class InteractiveShell(Component, Magic):
200 """An enhanced, interactive shell for Python."""
201
202 autocall = Enum((0,1,2), default_value=1, config=True)
203 autoedit_syntax = CBool(False, config=True)
204 autoindent = CBool(True, config=True)
205 automagic = CBool(True, config=True)
206 banner = Str('')
207 banner1 = Str(default_banner, config=True)
208 banner2 = Str('', config=True)
209 cache_size = Int(1000, config=True)
210 color_info = CBool(True, config=True)
211 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
212 default_value=get_default_colors(), config=True)
213 confirm_exit = CBool(True, config=True)
214 debug = CBool(False, config=True)
215 deep_reload = CBool(False, config=True)
216 # This display_banner only controls whether or not self.show_banner()
217 # is called when mainloop/interact are called. The default is False
218 # because for the terminal based application, the banner behavior
219 # is controlled by Global.display_banner, which IPythonApp looks at
220 # to determine if *it* should call show_banner() by hand or not.
221 display_banner = CBool(False) # This isn't configurable!
222 embedded = CBool(False)
223 embedded_active = CBool(False)
224 editor = Str(get_default_editor(), config=True)
225 filename = Str("<ipython console>")
226 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
227 logstart = CBool(False, config=True)
228 logfile = Str('', config=True)
229 logappend = Str('', config=True)
230 object_info_string_level = Enum((0,1,2), default_value=0,
231 config=True)
232 pager = Str('less', config=True)
233 pdb = CBool(False, config=True)
234 pprint = CBool(True, config=True)
235 profile = Str('', config=True)
236 prompt_in1 = Str('In [\\#]: ', config=True)
237 prompt_in2 = Str(' .\\D.: ', config=True)
238 prompt_out = Str('Out[\\#]: ', config=True)
239 prompts_pad_left = CBool(True, config=True)
240 quiet = CBool(False, config=True)
241
242 readline_use = CBool(True, config=True)
243 readline_merge_completions = CBool(True, config=True)
244 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
245 readline_remove_delims = Str('-/~', config=True)
246 readline_parse_and_bind = List([
247 'tab: complete',
248 '"\C-l": possible-completions',
249 'set show-all-if-ambiguous on',
250 '"\C-o": tab-insert',
251 '"\M-i": " "',
252 '"\M-o": "\d\d\d\d"',
253 '"\M-I": "\d\d\d\d"',
254 '"\C-r": reverse-search-history',
255 '"\C-s": forward-search-history',
256 '"\C-p": history-search-backward',
257 '"\C-n": history-search-forward',
258 '"\e[A": history-search-backward',
259 '"\e[B": history-search-forward',
260 '"\C-k": kill-line',
261 '"\C-u": unix-line-discard',
262 ], allow_none=False, config=True)
263
264 screen_length = Int(0, config=True)
265
266 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
267 separate_in = SeparateStr('\n', config=True)
268 separate_out = SeparateStr('', config=True)
269 separate_out2 = SeparateStr('', config=True)
270
271 system_header = Str('IPython system call: ', config=True)
272 system_verbose = CBool(False, config=True)
273 term_title = CBool(False, config=True)
274 wildcards_case_sensitive = CBool(True, config=True)
275 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
276 default_value='Context', config=True)
277
278 autoexec = List(allow_none=False)
279
280 # class attribute to indicate whether the class supports threads or not.
281 # Subclasses with thread support should override this as needed.
282 isthreaded = False
283
284 def __init__(self, parent=None, config=None, ipython_dir=None, usage=None,
285 user_ns=None, user_global_ns=None,
286 banner1=None, banner2=None, display_banner=None,
287 custom_exceptions=((),None)):
288
289 # This is where traitlets with a config_key argument are updated
290 # from the values on config.
291 super(InteractiveShell, self).__init__(parent, config=config)
292
293 # These are relatively independent and stateless
294 self.init_ipython_dir(ipython_dir)
295 self.init_instance_attrs()
296 self.init_term_title()
297 self.init_usage(usage)
298 self.init_banner(banner1, banner2, display_banner)
299
300 # Create namespaces (user_ns, user_global_ns, etc.)
301 self.init_create_namespaces(user_ns, user_global_ns)
302 # This has to be done after init_create_namespaces because it uses
303 # something in self.user_ns, but before init_sys_modules, which
304 # is the first thing to modify sys.
305 self.save_sys_module_state()
306 self.init_sys_modules()
307
308 self.init_history()
309 self.init_encoding()
310 self.init_prefilter()
311
312 Magic.__init__(self, self)
313
314 self.init_syntax_highlighting()
315 self.init_hooks()
316 self.init_pushd_popd_magic()
317 self.init_traceback_handlers(custom_exceptions)
318 self.init_user_ns()
319 self.init_logger()
320 self.init_alias()
321 self.init_builtins()
322
323 # pre_config_initialization
324 self.init_shadow_hist()
325
326 # The next section should contain averything that was in ipmaker.
327 self.init_logstart()
328
329 # The following was in post_config_initialization
330 self.init_inspector()
331 self.init_readline()
332 self.init_prompts()
333 self.init_displayhook()
334 self.init_reload_doctest()
335 self.init_magics()
336 self.init_pdb()
337 self.hooks.late_startup_hook()
338
339 def get_ipython(self):
340 """Return the currently running IPython instance."""
341 return self
342
343 #-------------------------------------------------------------------------
344 # Traitlet changed handlers
345 #-------------------------------------------------------------------------
346
347 def _banner1_changed(self):
348 self.compute_banner()
349
350 def _banner2_changed(self):
351 self.compute_banner()
352
353 def _ipython_dir_changed(self, name, new):
354 if not os.path.isdir(new):
355 os.makedirs(new, mode = 0777)
356 if not os.path.isdir(self.ipython_extension_dir):
357 os.makedirs(self.ipython_extension_dir, mode = 0777)
358
359 @property
360 def ipython_extension_dir(self):
361 return os.path.join(self.ipython_dir, 'extensions')
362
363 @property
364 def usable_screen_length(self):
365 if self.screen_length == 0:
366 return 0
367 else:
368 num_lines_bot = self.separate_in.count('\n')+1
369 return self.screen_length - num_lines_bot
370
371 def _term_title_changed(self, name, new_value):
372 self.init_term_title()
373
374 def set_autoindent(self,value=None):
375 """Set the autoindent flag, checking for readline support.
376
377 If called with no arguments, it acts as a toggle."""
378
379 if not self.has_readline:
380 if os.name == 'posix':
381 warn("The auto-indent feature requires the readline library")
382 self.autoindent = 0
383 return
384 if value is None:
385 self.autoindent = not self.autoindent
386 else:
387 self.autoindent = value
388
389 #-------------------------------------------------------------------------
390 # init_* methods called by __init__
391 #-------------------------------------------------------------------------
392
393 def init_ipython_dir(self, ipython_dir):
394 if ipython_dir is not None:
395 self.ipython_dir = ipython_dir
396 self.config.Global.ipython_dir = self.ipython_dir
397 return
398
399 if hasattr(self.config.Global, 'ipython_dir'):
400 self.ipython_dir = self.config.Global.ipython_dir
401 else:
402 self.ipython_dir = get_ipython_dir()
403
404 # All children can just read this
405 self.config.Global.ipython_dir = self.ipython_dir
406
407 def init_instance_attrs(self):
408 self.jobs = BackgroundJobManager()
409 self.more = False
410
411 # command compiler
412 self.compile = codeop.CommandCompiler()
413
414 # User input buffer
415 self.buffer = []
416
417 # Make an empty namespace, which extension writers can rely on both
418 # existing and NEVER being used by ipython itself. This gives them a
419 # convenient location for storing additional information and state
420 # their extensions may require, without fear of collisions with other
421 # ipython names that may develop later.
422 self.meta = Struct()
423
424 # Object variable to store code object waiting execution. This is
425 # used mainly by the multithreaded shells, but it can come in handy in
426 # other situations. No need to use a Queue here, since it's a single
427 # item which gets cleared once run.
428 self.code_to_run = None
429
430 # Flag to mark unconditional exit
431 self.exit_now = False
432
433 # Temporary files used for various purposes. Deleted at exit.
434 self.tempfiles = []
435
436 # Keep track of readline usage (later set by init_readline)
437 self.has_readline = False
438
439 # keep track of where we started running (mainly for crash post-mortem)
440 # This is not being used anywhere currently.
441 self.starting_dir = os.getcwd()
442
443 # Indentation management
444 self.indent_current_nsp = 0
445
446 def init_term_title(self):
447 # Enable or disable the terminal title.
448 if self.term_title:
449 toggle_set_term_title(True)
450 set_term_title('IPython: ' + abbrev_cwd())
451 else:
452 toggle_set_term_title(False)
453
454 def init_usage(self, usage=None):
455 if usage is None:
456 self.usage = interactive_usage
457 else:
458 self.usage = usage
459
460 def init_encoding(self):
461 # Get system encoding at startup time. Certain terminals (like Emacs
462 # under Win32 have it set to None, and we need to have a known valid
463 # encoding to use in the raw_input() method
464 try:
465 self.stdin_encoding = sys.stdin.encoding or 'ascii'
466 except AttributeError:
467 self.stdin_encoding = 'ascii'
468
469 def init_syntax_highlighting(self):
470 # Python source parser/formatter for syntax highlighting
471 pyformat = PyColorize.Parser().format
472 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
473
474 def init_pushd_popd_magic(self):
475 # for pushd/popd management
476 try:
477 self.home_dir = get_home_dir()
478 except HomeDirError, msg:
479 fatal(msg)
480
481 self.dir_stack = []
482
483 def init_logger(self):
484 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
485 # local shortcut, this is used a LOT
486 self.log = self.logger.log
487
488 def init_logstart(self):
489 if self.logappend:
490 self.magic_logstart(self.logappend + ' append')
491 elif self.logfile:
492 self.magic_logstart(self.logfile)
493 elif self.logstart:
494 self.magic_logstart()
495
496 def init_builtins(self):
497 self.builtin_trap = BuiltinTrap(self)
498
499 def init_inspector(self):
500 # Object inspector
501 self.inspector = oinspect.Inspector(oinspect.InspectColors,
502 PyColorize.ANSICodeColors,
503 'NoColor',
504 self.object_info_string_level)
505
506 def init_prompts(self):
507 # Initialize cache, set in/out prompts and printing system
508 self.outputcache = CachedOutput(self,
509 self.cache_size,
510 self.pprint,
511 input_sep = self.separate_in,
512 output_sep = self.separate_out,
513 output_sep2 = self.separate_out2,
514 ps1 = self.prompt_in1,
515 ps2 = self.prompt_in2,
516 ps_out = self.prompt_out,
517 pad_left = self.prompts_pad_left)
518
519 # user may have over-ridden the default print hook:
520 try:
521 self.outputcache.__class__.display = self.hooks.display
522 except AttributeError:
523 pass
524
525 def init_displayhook(self):
526 self.display_trap = DisplayTrap(self, self.outputcache)
527
528 def init_reload_doctest(self):
529 # Do a proper resetting of doctest, including the necessary displayhook
530 # monkeypatching
531 try:
532 doctest_reload()
533 except ImportError:
534 warn("doctest module does not exist.")
535
536 #-------------------------------------------------------------------------
537 # Things related to the banner
538 #-------------------------------------------------------------------------
539
540 def init_banner(self, banner1, banner2, display_banner):
541 if banner1 is not None:
542 self.banner1 = banner1
543 if banner2 is not None:
544 self.banner2 = banner2
545 if display_banner is not None:
546 self.display_banner = display_banner
547 self.compute_banner()
548
549 def show_banner(self, banner=None):
550 if banner is None:
551 banner = self.banner
552 self.write(banner)
553
554 def compute_banner(self):
555 self.banner = self.banner1 + '\n'
556 if self.profile:
557 self.banner += '\nIPython profile: %s\n' % self.profile
558 if self.banner2:
559 self.banner += '\n' + self.banner2 + '\n'
560
561 #-------------------------------------------------------------------------
562 # Things related to injections into the sys module
563 #-------------------------------------------------------------------------
564
565 def save_sys_module_state(self):
566 """Save the state of hooks in the sys module.
567
568 This has to be called after self.user_ns is created.
569 """
570 self._orig_sys_module_state = {}
571 self._orig_sys_module_state['stdin'] = sys.stdin
572 self._orig_sys_module_state['stdout'] = sys.stdout
573 self._orig_sys_module_state['stderr'] = sys.stderr
574 self._orig_sys_module_state['excepthook'] = sys.excepthook
575 try:
576 self._orig_sys_modules_main_name = self.user_ns['__name__']
577 except KeyError:
578 pass
579
580 def restore_sys_module_state(self):
581 """Restore the state of the sys module."""
582 try:
583 for k, v in self._orig_sys_module_state.items():
584 setattr(sys, k, v)
585 except AttributeError:
586 pass
587 try:
588 delattr(sys, 'ipcompleter')
589 except AttributeError:
590 pass
591 # Reset what what done in self.init_sys_modules
592 try:
593 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
594 except (AttributeError, KeyError):
595 pass
596
597 #-------------------------------------------------------------------------
598 # Things related to hooks
599 #-------------------------------------------------------------------------
600
601 def init_hooks(self):
602 # hooks holds pointers used for user-side customizations
603 self.hooks = Struct()
604
605 self.strdispatchers = {}
606
607 # Set all default hooks, defined in the IPython.hooks module.
608 hooks = IPython.core.hooks
609 for hook_name in hooks.__all__:
610 # default hooks have priority 100, i.e. low; user hooks should have
611 # 0-100 priority
612 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
613
614 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
615 """set_hook(name,hook) -> sets an internal IPython hook.
616
617 IPython exposes some of its internal API as user-modifiable hooks. By
618 adding your function to one of these hooks, you can modify IPython's
619 behavior to call at runtime your own routines."""
620
621 # At some point in the future, this should validate the hook before it
622 # accepts it. Probably at least check that the hook takes the number
623 # of args it's supposed to.
624
625 f = new.instancemethod(hook,self,self.__class__)
626
627 # check if the hook is for strdispatcher first
628 if str_key is not None:
629 sdp = self.strdispatchers.get(name, StrDispatch())
630 sdp.add_s(str_key, f, priority )
631 self.strdispatchers[name] = sdp
632 return
633 if re_key is not None:
634 sdp = self.strdispatchers.get(name, StrDispatch())
635 sdp.add_re(re.compile(re_key), f, priority )
636 self.strdispatchers[name] = sdp
637 return
638
639 dp = getattr(self.hooks, name, None)
640 if name not in IPython.core.hooks.__all__:
641 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
642 if not dp:
643 dp = IPython.core.hooks.CommandChainDispatcher()
644
645 try:
646 dp.add(f,priority)
647 except AttributeError:
648 # it was not commandchain, plain old func - replace
649 dp = f
650
651 setattr(self.hooks,name, dp)
652
653 #-------------------------------------------------------------------------
654 # Things related to the "main" module
655 #-------------------------------------------------------------------------
656
657 def new_main_mod(self,ns=None):
658 """Return a new 'main' module object for user code execution.
659 """
660 main_mod = self._user_main_module
661 init_fakemod_dict(main_mod,ns)
662 return main_mod
663
664 def cache_main_mod(self,ns,fname):
665 """Cache a main module's namespace.
666
667 When scripts are executed via %run, we must keep a reference to the
668 namespace of their __main__ module (a FakeModule instance) around so
669 that Python doesn't clear it, rendering objects defined therein
670 useless.
671
672 This method keeps said reference in a private dict, keyed by the
673 absolute path of the module object (which corresponds to the script
674 path). This way, for multiple executions of the same script we only
675 keep one copy of the namespace (the last one), thus preventing memory
676 leaks from old references while allowing the objects from the last
677 execution to be accessible.
678
679 Note: we can not allow the actual FakeModule instances to be deleted,
680 because of how Python tears down modules (it hard-sets all their
681 references to None without regard for reference counts). This method
682 must therefore make a *copy* of the given namespace, to allow the
683 original module's __dict__ to be cleared and reused.
684
685
686 Parameters
687 ----------
688 ns : a namespace (a dict, typically)
689
690 fname : str
691 Filename associated with the namespace.
692
693 Examples
694 --------
695
696 In [10]: import IPython
697
698 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
699
700 In [12]: IPython.__file__ in _ip._main_ns_cache
701 Out[12]: True
702 """
703 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
704
705 def clear_main_mod_cache(self):
706 """Clear the cache of main modules.
707
708 Mainly for use by utilities like %reset.
709
710 Examples
711 --------
712
713 In [15]: import IPython
714
715 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
716
717 In [17]: len(_ip._main_ns_cache) > 0
718 Out[17]: True
719
720 In [18]: _ip.clear_main_mod_cache()
721
722 In [19]: len(_ip._main_ns_cache) == 0
723 Out[19]: True
724 """
725 self._main_ns_cache.clear()
726
727 #-------------------------------------------------------------------------
728 # Things related to debugging
729 #-------------------------------------------------------------------------
730
731 def init_pdb(self):
732 # Set calling of pdb on exceptions
733 # self.call_pdb is a property
734 self.call_pdb = self.pdb
735
736 def _get_call_pdb(self):
737 return self._call_pdb
738
739 def _set_call_pdb(self,val):
740
741 if val not in (0,1,False,True):
742 raise ValueError,'new call_pdb value must be boolean'
743
744 # store value in instance
745 self._call_pdb = val
746
747 # notify the actual exception handlers
748 self.InteractiveTB.call_pdb = val
749 if self.isthreaded:
750 try:
751 self.sys_excepthook.call_pdb = val
752 except:
753 warn('Failed to activate pdb for threaded exception handler')
754
755 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
756 'Control auto-activation of pdb at exceptions')
757
758 def debugger(self,force=False):
759 """Call the pydb/pdb debugger.
760
761 Keywords:
762
763 - force(False): by default, this routine checks the instance call_pdb
764 flag and does not actually invoke the debugger if the flag is false.
765 The 'force' option forces the debugger to activate even if the flag
766 is false.
767 """
768
769 if not (force or self.call_pdb):
770 return
771
772 if not hasattr(sys,'last_traceback'):
773 error('No traceback has been produced, nothing to debug.')
774 return
775
776 # use pydb if available
777 if debugger.has_pydb:
778 from pydb import pm
779 else:
780 # fallback to our internal debugger
781 pm = lambda : self.InteractiveTB.debugger(force=True)
782 self.history_saving_wrapper(pm)()
783
784 #-------------------------------------------------------------------------
785 # Things related to IPython's various namespaces
786 #-------------------------------------------------------------------------
787
788 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
789 # Create the namespace where the user will operate. user_ns is
790 # normally the only one used, and it is passed to the exec calls as
791 # the locals argument. But we do carry a user_global_ns namespace
792 # given as the exec 'globals' argument, This is useful in embedding
793 # situations where the ipython shell opens in a context where the
794 # distinction between locals and globals is meaningful. For
795 # non-embedded contexts, it is just the same object as the user_ns dict.
796
797 # FIXME. For some strange reason, __builtins__ is showing up at user
798 # level as a dict instead of a module. This is a manual fix, but I
799 # should really track down where the problem is coming from. Alex
800 # Schmolck reported this problem first.
801
802 # A useful post by Alex Martelli on this topic:
803 # Re: inconsistent value from __builtins__
804 # Von: Alex Martelli <aleaxit@yahoo.com>
805 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
806 # Gruppen: comp.lang.python
807
808 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
809 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
810 # > <type 'dict'>
811 # > >>> print type(__builtins__)
812 # > <type 'module'>
813 # > Is this difference in return value intentional?
814
815 # Well, it's documented that '__builtins__' can be either a dictionary
816 # or a module, and it's been that way for a long time. Whether it's
817 # intentional (or sensible), I don't know. In any case, the idea is
818 # that if you need to access the built-in namespace directly, you
819 # should start with "import __builtin__" (note, no 's') which will
820 # definitely give you a module. Yeah, it's somewhat confusing:-(.
821
822 # These routines return properly built dicts as needed by the rest of
823 # the code, and can also be used by extension writers to generate
824 # properly initialized namespaces.
825 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
826
827 # Assign namespaces
828 # This is the namespace where all normal user variables live
829 self.user_ns = user_ns
830 self.user_global_ns = user_global_ns
831
832 # An auxiliary namespace that checks what parts of the user_ns were
833 # loaded at startup, so we can list later only variables defined in
834 # actual interactive use. Since it is always a subset of user_ns, it
835 # doesn't need to be separately tracked in the ns_table.
836 self.user_ns_hidden = {}
837
838 # A namespace to keep track of internal data structures to prevent
839 # them from cluttering user-visible stuff. Will be updated later
840 self.internal_ns = {}
841
842 # Now that FakeModule produces a real module, we've run into a nasty
843 # problem: after script execution (via %run), the module where the user
844 # code ran is deleted. Now that this object is a true module (needed
845 # so docetst and other tools work correctly), the Python module
846 # teardown mechanism runs over it, and sets to None every variable
847 # present in that module. Top-level references to objects from the
848 # script survive, because the user_ns is updated with them. However,
849 # calling functions defined in the script that use other things from
850 # the script will fail, because the function's closure had references
851 # to the original objects, which are now all None. So we must protect
852 # these modules from deletion by keeping a cache.
853 #
854 # To avoid keeping stale modules around (we only need the one from the
855 # last run), we use a dict keyed with the full path to the script, so
856 # only the last version of the module is held in the cache. Note,
857 # however, that we must cache the module *namespace contents* (their
858 # __dict__). Because if we try to cache the actual modules, old ones
859 # (uncached) could be destroyed while still holding references (such as
860 # those held by GUI objects that tend to be long-lived)>
861 #
862 # The %reset command will flush this cache. See the cache_main_mod()
863 # and clear_main_mod_cache() methods for details on use.
864
865 # This is the cache used for 'main' namespaces
866 self._main_ns_cache = {}
867 # And this is the single instance of FakeModule whose __dict__ we keep
868 # copying and clearing for reuse on each %run
869 self._user_main_module = FakeModule()
870
871 # A table holding all the namespaces IPython deals with, so that
872 # introspection facilities can search easily.
873 self.ns_table = {'user':user_ns,
874 'user_global':user_global_ns,
875 'internal':self.internal_ns,
876 'builtin':__builtin__.__dict__
877 }
878
879 # Similarly, track all namespaces where references can be held and that
880 # we can safely clear (so it can NOT include builtin). This one can be
881 # a simple list.
882 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
883 self.internal_ns, self._main_ns_cache ]
884
885 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
886 """Return a valid local and global user interactive namespaces.
887
888 This builds a dict with the minimal information needed to operate as a
889 valid IPython user namespace, which you can pass to the various
890 embedding classes in ipython. The default implementation returns the
891 same dict for both the locals and the globals to allow functions to
892 refer to variables in the namespace. Customized implementations can
893 return different dicts. The locals dictionary can actually be anything
894 following the basic mapping protocol of a dict, but the globals dict
895 must be a true dict, not even a subclass. It is recommended that any
896 custom object for the locals namespace synchronize with the globals
897 dict somehow.
898
899 Raises TypeError if the provided globals namespace is not a true dict.
900
901 Parameters
902 ----------
903 user_ns : dict-like, optional
904 The current user namespace. The items in this namespace should
905 be included in the output. If None, an appropriate blank
906 namespace should be created.
907 user_global_ns : dict, optional
908 The current user global namespace. The items in this namespace
909 should be included in the output. If None, an appropriate
910 blank namespace should be created.
911
912 Returns
913 -------
914 A pair of dictionary-like object to be used as the local namespace
915 of the interpreter and a dict to be used as the global namespace.
916 """
917
918
919 # We must ensure that __builtin__ (without the final 's') is always
920 # available and pointing to the __builtin__ *module*. For more details:
921 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
922
923 if user_ns is None:
924 # Set __name__ to __main__ to better match the behavior of the
925 # normal interpreter.
926 user_ns = {'__name__' :'__main__',
927 '__builtin__' : __builtin__,
928 '__builtins__' : __builtin__,
929 }
930 else:
931 user_ns.setdefault('__name__','__main__')
932 user_ns.setdefault('__builtin__',__builtin__)
933 user_ns.setdefault('__builtins__',__builtin__)
934
935 if user_global_ns is None:
936 user_global_ns = user_ns
937 if type(user_global_ns) is not dict:
938 raise TypeError("user_global_ns must be a true dict; got %r"
939 % type(user_global_ns))
940
941 return user_ns, user_global_ns
942
943 def init_sys_modules(self):
944 # We need to insert into sys.modules something that looks like a
945 # module but which accesses the IPython namespace, for shelve and
946 # pickle to work interactively. Normally they rely on getting
947 # everything out of __main__, but for embedding purposes each IPython
948 # instance has its own private namespace, so we can't go shoving
949 # everything into __main__.
950
951 # note, however, that we should only do this for non-embedded
952 # ipythons, which really mimic the __main__.__dict__ with their own
953 # namespace. Embedded instances, on the other hand, should not do
954 # this because they need to manage the user local/global namespaces
955 # only, but they live within a 'normal' __main__ (meaning, they
956 # shouldn't overtake the execution environment of the script they're
957 # embedded in).
958
959 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
960
961 try:
962 main_name = self.user_ns['__name__']
963 except KeyError:
964 raise KeyError('user_ns dictionary MUST have a "__name__" key')
965 else:
966 sys.modules[main_name] = FakeModule(self.user_ns)
967
968 def init_user_ns(self):
969 """Initialize all user-visible namespaces to their minimum defaults.
970
971 Certain history lists are also initialized here, as they effectively
972 act as user namespaces.
973
974 Notes
975 -----
976 All data structures here are only filled in, they are NOT reset by this
977 method. If they were not empty before, data will simply be added to
978 therm.
979 """
980 # This function works in two parts: first we put a few things in
981 # user_ns, and we sync that contents into user_ns_hidden so that these
982 # initial variables aren't shown by %who. After the sync, we add the
983 # rest of what we *do* want the user to see with %who even on a new
984 # session (probably nothing, so theye really only see their own stuff)
985
986 # The user dict must *always* have a __builtin__ reference to the
987 # Python standard __builtin__ namespace, which must be imported.
988 # This is so that certain operations in prompt evaluation can be
989 # reliably executed with builtins. Note that we can NOT use
990 # __builtins__ (note the 's'), because that can either be a dict or a
991 # module, and can even mutate at runtime, depending on the context
992 # (Python makes no guarantees on it). In contrast, __builtin__ is
993 # always a module object, though it must be explicitly imported.
994
995 # For more details:
996 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
997 ns = dict(__builtin__ = __builtin__)
998
999 # Put 'help' in the user namespace
1000 try:
1001 from site import _Helper
1002 ns['help'] = _Helper()
1003 except ImportError:
1004 warn('help() not available - check site.py')
1005
1006 # make global variables for user access to the histories
1007 ns['_ih'] = self.input_hist
1008 ns['_oh'] = self.output_hist
1009 ns['_dh'] = self.dir_hist
1010
1011 ns['_sh'] = shadowns
1012
1013 # user aliases to input and output histories. These shouldn't show up
1014 # in %who, as they can have very large reprs.
1015 ns['In'] = self.input_hist
1016 ns['Out'] = self.output_hist
1017
1018 # Store myself as the public api!!!
1019 ns['get_ipython'] = self.get_ipython
1020
1021 # Sync what we've added so far to user_ns_hidden so these aren't seen
1022 # by %who
1023 self.user_ns_hidden.update(ns)
1024
1025 # Anything put into ns now would show up in %who. Think twice before
1026 # putting anything here, as we really want %who to show the user their
1027 # stuff, not our variables.
1028
1029 # Finally, update the real user's namespace
1030 self.user_ns.update(ns)
1031
1032
1033 def reset(self):
1034 """Clear all internal namespaces.
1035
1036 Note that this is much more aggressive than %reset, since it clears
1037 fully all namespaces, as well as all input/output lists.
1038 """
1039 for ns in self.ns_refs_table:
1040 ns.clear()
1041
1042 self.alias_manager.clear_aliases()
1043
1044 # Clear input and output histories
1045 self.input_hist[:] = []
1046 self.input_hist_raw[:] = []
1047 self.output_hist.clear()
1048
1049 # Restore the user namespaces to minimal usability
1050 self.init_user_ns()
1051
1052 # Restore the default and user aliases
1053 self.alias_manager.init_aliases()
1054
1055 def push(self, variables, interactive=True):
1056 """Inject a group of variables into the IPython user namespace.
1057
1058 Parameters
1059 ----------
1060 variables : dict, str or list/tuple of str
1061 The variables to inject into the user's namespace. If a dict,
1062 a simple update is done. If a str, the string is assumed to
1063 have variable names separated by spaces. A list/tuple of str
1064 can also be used to give the variable names. If just the variable
1065 names are give (list/tuple/str) then the variable values looked
1066 up in the callers frame.
1067 interactive : bool
1068 If True (default), the variables will be listed with the ``who``
1069 magic.
1070 """
1071 vdict = None
1072
1073 # We need a dict of name/value pairs to do namespace updates.
1074 if isinstance(variables, dict):
1075 vdict = variables
1076 elif isinstance(variables, (basestring, list, tuple)):
1077 if isinstance(variables, basestring):
1078 vlist = variables.split()
1079 else:
1080 vlist = variables
1081 vdict = {}
1082 cf = sys._getframe(1)
1083 for name in vlist:
1084 try:
1085 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1086 except:
1087 print ('Could not get variable %s from %s' %
1088 (name,cf.f_code.co_name))
1089 else:
1090 raise ValueError('variables must be a dict/str/list/tuple')
1091
1092 # Propagate variables to user namespace
1093 self.user_ns.update(vdict)
1094
1095 # And configure interactive visibility
1096 config_ns = self.user_ns_hidden
1097 if interactive:
1098 for name, val in vdict.iteritems():
1099 config_ns.pop(name, None)
1100 else:
1101 for name,val in vdict.iteritems():
1102 config_ns[name] = val
1103
1104 #-------------------------------------------------------------------------
1105 # Things related to history management
1106 #-------------------------------------------------------------------------
1107
1108 def init_history(self):
1109 # List of input with multi-line handling.
1110 self.input_hist = InputList()
1111 # This one will hold the 'raw' input history, without any
1112 # pre-processing. This will allow users to retrieve the input just as
1113 # it was exactly typed in by the user, with %hist -r.
1114 self.input_hist_raw = InputList()
1115
1116 # list of visited directories
1117 try:
1118 self.dir_hist = [os.getcwd()]
1119 except OSError:
1120 self.dir_hist = []
1121
1122 # dict of output history
1123 self.output_hist = {}
1124
1125 # Now the history file
1126 if self.profile:
1127 histfname = 'history-%s' % self.profile
1128 else:
1129 histfname = 'history'
1130 self.histfile = os.path.join(self.ipython_dir, histfname)
1131
1132 # Fill the history zero entry, user counter starts at 1
1133 self.input_hist.append('\n')
1134 self.input_hist_raw.append('\n')
1135
1136 def init_shadow_hist(self):
1137 try:
1138 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1139 except exceptions.UnicodeDecodeError:
1140 print "Your ipython_dir can't be decoded to unicode!"
1141 print "Please set HOME environment variable to something that"
1142 print r"only has ASCII characters, e.g. c:\home"
1143 print "Now it is", self.ipython_dir
1144 sys.exit()
1145 self.shadowhist = ipcorehist.ShadowHist(self.db)
1146
1147 def savehist(self):
1148 """Save input history to a file (via readline library)."""
1149
1150 try:
1151 self.readline.write_history_file(self.histfile)
1152 except:
1153 print 'Unable to save IPython command history to file: ' + \
1154 `self.histfile`
1155
1156 def reloadhist(self):
1157 """Reload the input history from disk file."""
1158
1159 try:
1160 self.readline.clear_history()
1161 self.readline.read_history_file(self.shell.histfile)
1162 except AttributeError:
1163 pass
1164
1165 def history_saving_wrapper(self, func):
1166 """ Wrap func for readline history saving
1167
1168 Convert func into callable that saves & restores
1169 history around the call """
1170
1171 if self.has_readline:
1172 from IPython.utils import rlineimpl as readline
1173 else:
1174 return func
1175
1176 def wrapper():
1177 self.savehist()
1178 try:
1179 func()
1180 finally:
1181 readline.read_history_file(self.histfile)
1182 return wrapper
1183
1184 #-------------------------------------------------------------------------
1185 # Things related to exception handling and tracebacks (not debugging)
1186 #-------------------------------------------------------------------------
1187
1188 def init_traceback_handlers(self, custom_exceptions):
1189 # Syntax error handler.
1190 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1191
1192 # The interactive one is initialized with an offset, meaning we always
1193 # want to remove the topmost item in the traceback, which is our own
1194 # internal code. Valid modes: ['Plain','Context','Verbose']
1195 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1196 color_scheme='NoColor',
1197 tb_offset = 1)
1198
1199 # The instance will store a pointer to the system-wide exception hook,
1200 # so that runtime code (such as magics) can access it. This is because
1201 # during the read-eval loop, it may get temporarily overwritten.
1202 self.sys_excepthook = sys.excepthook
1203
1204 # and add any custom exception handlers the user may have specified
1205 self.set_custom_exc(*custom_exceptions)
1206
1207 # Set the exception mode
1208 self.InteractiveTB.set_mode(mode=self.xmode)
1209
1210 def set_custom_exc(self,exc_tuple,handler):
1211 """set_custom_exc(exc_tuple,handler)
1212
1213 Set a custom exception handler, which will be called if any of the
1214 exceptions in exc_tuple occur in the mainloop (specifically, in the
1215 runcode() method.
1216
1217 Inputs:
1218
1219 - exc_tuple: a *tuple* of valid exceptions to call the defined
1220 handler for. It is very important that you use a tuple, and NOT A
1221 LIST here, because of the way Python's except statement works. If
1222 you only want to trap a single exception, use a singleton tuple:
1223
1224 exc_tuple == (MyCustomException,)
1225
1226 - handler: this must be defined as a function with the following
1227 basic interface: def my_handler(self,etype,value,tb).
1228
1229 This will be made into an instance method (via new.instancemethod)
1230 of IPython itself, and it will be called if any of the exceptions
1231 listed in the exc_tuple are caught. If the handler is None, an
1232 internal basic one is used, which just prints basic info.
1233
1234 WARNING: by putting in your own exception handler into IPython's main
1235 execution loop, you run a very good chance of nasty crashes. This
1236 facility should only be used if you really know what you are doing."""
1237
1238 assert type(exc_tuple)==type(()) , \
1239 "The custom exceptions must be given AS A TUPLE."
1240
1241 def dummy_handler(self,etype,value,tb):
1242 print '*** Simple custom exception handler ***'
1243 print 'Exception type :',etype
1244 print 'Exception value:',value
1245 print 'Traceback :',tb
1246 print 'Source code :','\n'.join(self.buffer)
1247
1248 if handler is None: handler = dummy_handler
1249
1250 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1251 self.custom_exceptions = exc_tuple
1252
1253 def excepthook(self, etype, value, tb):
1254 """One more defense for GUI apps that call sys.excepthook.
1255
1256 GUI frameworks like wxPython trap exceptions and call
1257 sys.excepthook themselves. I guess this is a feature that
1258 enables them to keep running after exceptions that would
1259 otherwise kill their mainloop. This is a bother for IPython
1260 which excepts to catch all of the program exceptions with a try:
1261 except: statement.
1262
1263 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1264 any app directly invokes sys.excepthook, it will look to the user like
1265 IPython crashed. In order to work around this, we can disable the
1266 CrashHandler and replace it with this excepthook instead, which prints a
1267 regular traceback using our InteractiveTB. In this fashion, apps which
1268 call sys.excepthook will generate a regular-looking exception from
1269 IPython, and the CrashHandler will only be triggered by real IPython
1270 crashes.
1271
1272 This hook should be used sparingly, only in places which are not likely
1273 to be true IPython errors.
1274 """
1275 self.showtraceback((etype,value,tb),tb_offset=0)
1276
1277 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1278 exception_only=False):
1279 """Display the exception that just occurred.
1280
1281 If nothing is known about the exception, this is the method which
1282 should be used throughout the code for presenting user tracebacks,
1283 rather than directly invoking the InteractiveTB object.
1284
1285 A specific showsyntaxerror() also exists, but this method can take
1286 care of calling it if needed, so unless you are explicitly catching a
1287 SyntaxError exception, don't try to analyze the stack manually and
1288 simply call this method."""
1289
1290 try:
1291 if exc_tuple is None:
1292 etype, value, tb = sys.exc_info()
1293 else:
1294 etype, value, tb = exc_tuple
1295
1296 if etype is None:
1297 if hasattr(sys, 'last_type'):
1298 etype, value, tb = sys.last_type, sys.last_value, \
1299 sys.last_traceback
1300 else:
1301 self.write('No traceback available to show.\n')
1302 return
1303
1304 if etype is SyntaxError:
1305 # Though this won't be called by syntax errors in the input
1306 # line, there may be SyntaxError cases whith imported code.
1307 self.showsyntaxerror(filename)
1308 elif etype is UsageError:
1309 print "UsageError:", value
1310 else:
1311 # WARNING: these variables are somewhat deprecated and not
1312 # necessarily safe to use in a threaded environment, but tools
1313 # like pdb depend on their existence, so let's set them. If we
1314 # find problems in the field, we'll need to revisit their use.
1315 sys.last_type = etype
1316 sys.last_value = value
1317 sys.last_traceback = tb
1318
1319 if etype in self.custom_exceptions:
1320 self.CustomTB(etype,value,tb)
1321 else:
1322 if exception_only:
1323 m = ('An exception has occurred, use %tb to see the '
1324 'full traceback.')
1325 print m
1326 self.InteractiveTB.show_exception_only(etype, value)
1327 else:
1328 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1329 if self.InteractiveTB.call_pdb:
1330 # pdb mucks up readline, fix it back
1331 self.set_completer()
1332
1333 except KeyboardInterrupt:
1334 self.write("\nKeyboardInterrupt\n")
1335
1336
1337 def showsyntaxerror(self, filename=None):
1338 """Display the syntax error that just occurred.
1339
1340 This doesn't display a stack trace because there isn't one.
1341
1342 If a filename is given, it is stuffed in the exception instead
1343 of what was there before (because Python's parser always uses
1344 "<string>" when reading from a string).
1345 """
1346 etype, value, last_traceback = sys.exc_info()
1347
1348 # See note about these variables in showtraceback() above
1349 sys.last_type = etype
1350 sys.last_value = value
1351 sys.last_traceback = last_traceback
1352
1353 if filename and etype is SyntaxError:
1354 # Work hard to stuff the correct filename in the exception
1355 try:
1356 msg, (dummy_filename, lineno, offset, line) = value
1357 except:
1358 # Not the format we expect; leave it alone
1359 pass
1360 else:
1361 # Stuff in the right filename
1362 try:
1363 # Assume SyntaxError is a class exception
1364 value = SyntaxError(msg, (filename, lineno, offset, line))
1365 except:
1366 # If that failed, assume SyntaxError is a string
1367 value = msg, (filename, lineno, offset, line)
1368 self.SyntaxTB(etype,value,[])
1369
1370 def edit_syntax_error(self):
1371 """The bottom half of the syntax error handler called in the main loop.
1372
1373 Loop until syntax error is fixed or user cancels.
1374 """
1375
1376 while self.SyntaxTB.last_syntax_error:
1377 # copy and clear last_syntax_error
1378 err = self.SyntaxTB.clear_err_state()
1379 if not self._should_recompile(err):
1380 return
1381 try:
1382 # may set last_syntax_error again if a SyntaxError is raised
1383 self.safe_execfile(err.filename,self.user_ns)
1384 except:
1385 self.showtraceback()
1386 else:
1387 try:
1388 f = file(err.filename)
1389 try:
1390 # This should be inside a display_trap block and I
1391 # think it is.
1392 sys.displayhook(f.read())
1393 finally:
1394 f.close()
1395 except:
1396 self.showtraceback()
1397
1398 def _should_recompile(self,e):
1399 """Utility routine for edit_syntax_error"""
1400
1401 if e.filename in ('<ipython console>','<input>','<string>',
1402 '<console>','<BackgroundJob compilation>',
1403 None):
1404
1405 return False
1406 try:
1407 if (self.autoedit_syntax and
1408 not self.ask_yes_no('Return to editor to correct syntax error? '
1409 '[Y/n] ','y')):
1410 return False
1411 except EOFError:
1412 return False
1413
1414 def int0(x):
1415 try:
1416 return int(x)
1417 except TypeError:
1418 return 0
1419 # always pass integer line and offset values to editor hook
1420 try:
1421 self.hooks.fix_error_editor(e.filename,
1422 int0(e.lineno),int0(e.offset),e.msg)
1423 except TryNext:
1424 warn('Could not open editor')
1425 return False
1426 return True
1427
1428 #-------------------------------------------------------------------------
1429 # Things related to tab completion
1430 #-------------------------------------------------------------------------
1431
1432 def complete(self, text):
1433 """Return a sorted list of all possible completions on text.
1434
1435 Inputs:
1436
1437 - text: a string of text to be completed on.
1438
1439 This is a wrapper around the completion mechanism, similar to what
1440 readline does at the command line when the TAB key is hit. By
1441 exposing it as a method, it can be used by other non-readline
1442 environments (such as GUIs) for text completion.
1443
1444 Simple usage example:
1445
1446 In [7]: x = 'hello'
1447
1448 In [8]: x
1449 Out[8]: 'hello'
1450
1451 In [9]: print x
1452 hello
1453
1454 In [10]: _ip.complete('x.l')
1455 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1456 """
1457
1458 # Inject names into __builtin__ so we can complete on the added names.
1459 with self.builtin_trap:
1460 complete = self.Completer.complete
1461 state = 0
1462 # use a dict so we get unique keys, since ipyhton's multiple
1463 # completers can return duplicates. When we make 2.4 a requirement,
1464 # start using sets instead, which are faster.
1465 comps = {}
1466 while True:
1467 newcomp = complete(text,state,line_buffer=text)
1468 if newcomp is None:
1469 break
1470 comps[newcomp] = 1
1471 state += 1
1472 outcomps = comps.keys()
1473 outcomps.sort()
1474 #print "T:",text,"OC:",outcomps # dbg
1475 #print "vars:",self.user_ns.keys()
1476 return outcomps
1477
1478 def set_custom_completer(self,completer,pos=0):
1479 """Adds a new custom completer function.
1480
1481 The position argument (defaults to 0) is the index in the completers
1482 list where you want the completer to be inserted."""
1483
1484 newcomp = new.instancemethod(completer,self.Completer,
1485 self.Completer.__class__)
1486 self.Completer.matchers.insert(pos,newcomp)
1487
1488 def set_completer(self):
1489 """Reset readline's completer to be our own."""
1490 self.readline.set_completer(self.Completer.complete)
1491
1492 def set_completer_frame(self, frame=None):
1493 """Set the frame of the completer."""
1494 if frame:
1495 self.Completer.namespace = frame.f_locals
1496 self.Completer.global_namespace = frame.f_globals
1497 else:
1498 self.Completer.namespace = self.user_ns
1499 self.Completer.global_namespace = self.user_global_ns
1500
1501 #-------------------------------------------------------------------------
1502 # Things related to readline
1503 #-------------------------------------------------------------------------
1504
1505 def init_readline(self):
1506 """Command history completion/saving/reloading."""
1507
1508 if self.readline_use:
1509 import IPython.utils.rlineimpl as readline
1510
1511 self.rl_next_input = None
1512 self.rl_do_indent = False
1513
1514 if not self.readline_use or not readline.have_readline:
1515 self.has_readline = False
1516 self.readline = None
1517 # Set a number of methods that depend on readline to be no-op
1518 self.savehist = no_op
1519 self.reloadhist = no_op
1520 self.set_completer = no_op
1521 self.set_custom_completer = no_op
1522 self.set_completer_frame = no_op
1523 warn('Readline services not available or not loaded.')
1524 else:
1525 self.has_readline = True
1526 self.readline = readline
1527 sys.modules['readline'] = readline
1528 import atexit
1529 from IPython.core.completer import IPCompleter
1530 self.Completer = IPCompleter(self,
1531 self.user_ns,
1532 self.user_global_ns,
1533 self.readline_omit__names,
1534 self.alias_manager.alias_table)
1535 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1536 self.strdispatchers['complete_command'] = sdisp
1537 self.Completer.custom_completers = sdisp
1538 # Platform-specific configuration
1539 if os.name == 'nt':
1540 self.readline_startup_hook = readline.set_pre_input_hook
1541 else:
1542 self.readline_startup_hook = readline.set_startup_hook
1543
1544 # Load user's initrc file (readline config)
1545 # Or if libedit is used, load editrc.
1546 inputrc_name = os.environ.get('INPUTRC')
1547 if inputrc_name is None:
1548 home_dir = get_home_dir()
1549 if home_dir is not None:
1550 inputrc_name = '.inputrc'
1551 if readline.uses_libedit:
1552 inputrc_name = '.editrc'
1553 inputrc_name = os.path.join(home_dir, inputrc_name)
1554 if os.path.isfile(inputrc_name):
1555 try:
1556 readline.read_init_file(inputrc_name)
1557 except:
1558 warn('Problems reading readline initialization file <%s>'
1559 % inputrc_name)
1560
1561 # save this in sys so embedded copies can restore it properly
1562 sys.ipcompleter = self.Completer.complete
1563 self.set_completer()
1564
1565 # Configure readline according to user's prefs
1566 # This is only done if GNU readline is being used. If libedit
1567 # is being used (as on Leopard) the readline config is
1568 # not run as the syntax for libedit is different.
1569 if not readline.uses_libedit:
1570 for rlcommand in self.readline_parse_and_bind:
1571 #print "loading rl:",rlcommand # dbg
1572 readline.parse_and_bind(rlcommand)
1573
1574 # Remove some chars from the delimiters list. If we encounter
1575 # unicode chars, discard them.
1576 delims = readline.get_completer_delims().encode("ascii", "ignore")
1577 delims = delims.translate(string._idmap,
1578 self.readline_remove_delims)
1579 readline.set_completer_delims(delims)
1580 # otherwise we end up with a monster history after a while:
1581 readline.set_history_length(1000)
1582 try:
1583 #print '*** Reading readline history' # dbg
1584 readline.read_history_file(self.histfile)
1585 except IOError:
1586 pass # It doesn't exist yet.
1587
1588 atexit.register(self.atexit_operations)
1589 del atexit
1590
1591 # Configure auto-indent for all platforms
1592 self.set_autoindent(self.autoindent)
1593
1594 def set_next_input(self, s):
1595 """ Sets the 'default' input string for the next command line.
1596
1597 Requires readline.
1598
1599 Example:
1600
1601 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1602 [D:\ipython]|2> Hello Word_ # cursor is here
1603 """
1604
1605 self.rl_next_input = s
1606
1607 def pre_readline(self):
1608 """readline hook to be used at the start of each line.
1609
1610 Currently it handles auto-indent only."""
1611
1612 #debugx('self.indent_current_nsp','pre_readline:')
1613
1614 if self.rl_do_indent:
1615 self.readline.insert_text(self._indent_current_str())
1616 if self.rl_next_input is not None:
1617 self.readline.insert_text(self.rl_next_input)
1618 self.rl_next_input = None
1619
1620 def _indent_current_str(self):
1621 """return the current level of indentation as a string"""
1622 return self.indent_current_nsp * ' '
1623
1624 #-------------------------------------------------------------------------
1625 # Things related to magics
1626 #-------------------------------------------------------------------------
1627
1628 def init_magics(self):
1629 # Set user colors (don't do it in the constructor above so that it
1630 # doesn't crash if colors option is invalid)
1631 self.magic_colors(self.colors)
1632 # History was moved to a separate module
1633 from . import history
1634 history.init_ipython(self)
1635
1636 def magic(self,arg_s):
1637 """Call a magic function by name.
1638
1639 Input: a string containing the name of the magic function to call and any
1640 additional arguments to be passed to the magic.
1641
1642 magic('name -opt foo bar') is equivalent to typing at the ipython
1643 prompt:
1644
1645 In[1]: %name -opt foo bar
1646
1647 To call a magic without arguments, simply use magic('name').
1648
1649 This provides a proper Python function to call IPython's magics in any
1650 valid Python code you can type at the interpreter, including loops and
1651 compound statements.
1652 """
1653 args = arg_s.split(' ',1)
1654 magic_name = args[0]
1655 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1656
1657 try:
1658 magic_args = args[1]
1659 except IndexError:
1660 magic_args = ''
1661 fn = getattr(self,'magic_'+magic_name,None)
1662 if fn is None:
1663 error("Magic function `%s` not found." % magic_name)
1664 else:
1665 magic_args = self.var_expand(magic_args,1)
1666 with nested(self.builtin_trap,):
1667 result = fn(magic_args)
1668 return result
1669
1670 def define_magic(self, magicname, func):
1671 """Expose own function as magic function for ipython
1672
1673 def foo_impl(self,parameter_s=''):
1674 'My very own magic!. (Use docstrings, IPython reads them).'
1675 print 'Magic function. Passed parameter is between < >:'
1676 print '<%s>' % parameter_s
1677 print 'The self object is:',self
1678
1679 self.define_magic('foo',foo_impl)
1680 """
1681
1682 import new
1683 im = new.instancemethod(func,self, self.__class__)
1684 old = getattr(self, "magic_" + magicname, None)
1685 setattr(self, "magic_" + magicname, im)
1686 return old
1687
1688 #-------------------------------------------------------------------------
1689 # Things related to macros
1690 #-------------------------------------------------------------------------
1691
1692 def define_macro(self, name, themacro):
1693 """Define a new macro
1694
1695 Parameters
1696 ----------
1697 name : str
1698 The name of the macro.
1699 themacro : str or Macro
1700 The action to do upon invoking the macro. If a string, a new
1701 Macro object is created by passing the string to it.
1702 """
1703
1704 from IPython.core import macro
1705
1706 if isinstance(themacro, basestring):
1707 themacro = macro.Macro(themacro)
1708 if not isinstance(themacro, macro.Macro):
1709 raise ValueError('A macro must be a string or a Macro instance.')
1710 self.user_ns[name] = themacro
1711
1712 #-------------------------------------------------------------------------
1713 # Things related to the running of system commands
1714 #-------------------------------------------------------------------------
1715
1716 def system(self, cmd):
1717 """Make a system call, using IPython."""
1718 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1719
1720 #-------------------------------------------------------------------------
1721 # Things related to aliases
1722 #-------------------------------------------------------------------------
1723
1724 def init_alias(self):
1725 self.alias_manager = AliasManager(self, config=self.config)
1726 self.ns_table['alias'] = self.alias_manager.alias_table,
1727
1728 #-------------------------------------------------------------------------
1729 # Things related to the running of code
1730 #-------------------------------------------------------------------------
1731
1732 def ex(self, cmd):
1733 """Execute a normal python statement in user namespace."""
1734 with nested(self.builtin_trap,):
1735 exec cmd in self.user_global_ns, self.user_ns
1736
1737 def ev(self, expr):
1738 """Evaluate python expression expr in user namespace.
1739
1740 Returns the result of evaluation
1741 """
1742 with nested(self.builtin_trap,):
1743 return eval(expr, self.user_global_ns, self.user_ns)
1744
1745 def mainloop(self, display_banner=None):
1746 """Start the mainloop.
1747
1748 If an optional banner argument is given, it will override the
1749 internally created default banner.
1750 """
1751
1752 with nested(self.builtin_trap, self.display_trap):
1753
1754 # if you run stuff with -c <cmd>, raw hist is not updated
1755 # ensure that it's in sync
1756 if len(self.input_hist) != len (self.input_hist_raw):
1757 self.input_hist_raw = InputList(self.input_hist)
1758
1759 while 1:
1760 try:
1761 self.interact(display_banner=display_banner)
1762 #self.interact_with_readline()
1763 # XXX for testing of a readline-decoupled repl loop, call
1764 # interact_with_readline above
1765 break
1766 except KeyboardInterrupt:
1767 # this should not be necessary, but KeyboardInterrupt
1768 # handling seems rather unpredictable...
1769 self.write("\nKeyboardInterrupt in interact()\n")
1770
1771 def interact_prompt(self):
1772 """ Print the prompt (in read-eval-print loop)
1773
1774 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1775 used in standard IPython flow.
1776 """
1777 if self.more:
1778 try:
1779 prompt = self.hooks.generate_prompt(True)
1780 except:
1781 self.showtraceback()
1782 if self.autoindent:
1783 self.rl_do_indent = True
1784
1785 else:
1786 try:
1787 prompt = self.hooks.generate_prompt(False)
1788 except:
1789 self.showtraceback()
1790 self.write(prompt)
1791
1792 def interact_handle_input(self,line):
1793 """ Handle the input line (in read-eval-print loop)
1794
1795 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1796 used in standard IPython flow.
1797 """
1798 if line.lstrip() == line:
1799 self.shadowhist.add(line.strip())
1800 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1801
1802 if line.strip():
1803 if self.more:
1804 self.input_hist_raw[-1] += '%s\n' % line
1805 else:
1806 self.input_hist_raw.append('%s\n' % line)
1807
1808
1809 self.more = self.push_line(lineout)
1810 if (self.SyntaxTB.last_syntax_error and
1811 self.autoedit_syntax):
1812 self.edit_syntax_error()
1813
1814 def interact_with_readline(self):
1815 """ Demo of using interact_handle_input, interact_prompt
1816
1817 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1818 it should work like this.
1819 """
1820 self.readline_startup_hook(self.pre_readline)
1821 while not self.exit_now:
1822 self.interact_prompt()
1823 if self.more:
1824 self.rl_do_indent = True
1825 else:
1826 self.rl_do_indent = False
1827 line = raw_input_original().decode(self.stdin_encoding)
1828 self.interact_handle_input(line)
1829
1830 def interact(self, display_banner=None):
1831 """Closely emulate the interactive Python console."""
1832
1833 # batch run -> do not interact
1834 if self.exit_now:
1835 return
1836
1837 if display_banner is None:
1838 display_banner = self.display_banner
1839 if display_banner:
1840 self.show_banner()
1841
1842 more = 0
1843
1844 # Mark activity in the builtins
1845 __builtin__.__dict__['__IPYTHON__active'] += 1
1846
1847 if self.has_readline:
1848 self.readline_startup_hook(self.pre_readline)
1849 # exit_now is set by a call to %Exit or %Quit, through the
1850 # ask_exit callback.
1851
1852 while not self.exit_now:
1853 self.hooks.pre_prompt_hook()
1854 if more:
1855 try:
1856 prompt = self.hooks.generate_prompt(True)
1857 except:
1858 self.showtraceback()
1859 if self.autoindent:
1860 self.rl_do_indent = True
1861
1862 else:
1863 try:
1864 prompt = self.hooks.generate_prompt(False)
1865 except:
1866 self.showtraceback()
1867 try:
1868 line = self.raw_input(prompt, more)
1869 if self.exit_now:
1870 # quick exit on sys.std[in|out] close
1871 break
1872 if self.autoindent:
1873 self.rl_do_indent = False
1874
1875 except KeyboardInterrupt:
1876 #double-guard against keyboardinterrupts during kbdint handling
1877 try:
1878 self.write('\nKeyboardInterrupt\n')
1879 self.resetbuffer()
1880 # keep cache in sync with the prompt counter:
1881 self.outputcache.prompt_count -= 1
1882
1883 if self.autoindent:
1884 self.indent_current_nsp = 0
1885 more = 0
1886 except KeyboardInterrupt:
1887 pass
1888 except EOFError:
1889 if self.autoindent:
1890 self.rl_do_indent = False
1891 if self.has_readline:
1892 self.readline_startup_hook(None)
1893 self.write('\n')
1894 self.exit()
1895 except bdb.BdbQuit:
1896 warn('The Python debugger has exited with a BdbQuit exception.\n'
1897 'Because of how pdb handles the stack, it is impossible\n'
1898 'for IPython to properly format this particular exception.\n'
1899 'IPython will resume normal operation.')
1900 except:
1901 # exceptions here are VERY RARE, but they can be triggered
1902 # asynchronously by signal handlers, for example.
1903 self.showtraceback()
1904 else:
1905 more = self.push_line(line)
1906 if (self.SyntaxTB.last_syntax_error and
1907 self.autoedit_syntax):
1908 self.edit_syntax_error()
1909
1910 # We are off again...
1911 __builtin__.__dict__['__IPYTHON__active'] -= 1
1912
1913 # Turn off the exit flag, so the mainloop can be restarted if desired
1914 self.exit_now = False
1915
1916 def safe_execfile(self, fname, *where, **kw):
1917 """A safe version of the builtin execfile().
1918
1919 This version will never throw an exception, but instead print
1920 helpful error messages to the screen. This only works on pure
1921 Python files with the .py extension.
1922
1923 Parameters
1924 ----------
1925 fname : string
1926 The name of the file to be executed.
1927 where : tuple
1928 One or two namespaces, passed to execfile() as (globals,locals).
1929 If only one is given, it is passed as both.
1930 exit_ignore : bool (False)
1931 If True, then silence SystemExit for non-zero status (it is always
1932 silenced for zero status, as it is so common).
1933 """
1934 kw.setdefault('exit_ignore', False)
1935
1936 fname = os.path.abspath(os.path.expanduser(fname))
1937
1938 # Make sure we have a .py file
1939 if not fname.endswith('.py'):
1940 warn('File must end with .py to be run using execfile: <%s>' % fname)
1941
1942 # Make sure we can open the file
1943 try:
1944 with open(fname) as thefile:
1945 pass
1946 except:
1947 warn('Could not open file <%s> for safe execution.' % fname)
1948 return
1949
1950 # Find things also in current directory. This is needed to mimic the
1951 # behavior of running a script from the system command line, where
1952 # Python inserts the script's directory into sys.path
1953 dname = os.path.dirname(fname)
1954
1955 with prepended_to_syspath(dname):
1956 try:
1957 execfile(fname,*where)
1958 except SystemExit, status:
1959 # If the call was made with 0 or None exit status (sys.exit(0)
1960 # or sys.exit() ), don't bother showing a traceback, as both of
1961 # these are considered normal by the OS:
1962 # > python -c'import sys;sys.exit(0)'; echo $?
1963 # 0
1964 # > python -c'import sys;sys.exit()'; echo $?
1965 # 0
1966 # For other exit status, we show the exception unless
1967 # explicitly silenced, but only in short form.
1968 if status.code not in (0, None) and not kw['exit_ignore']:
1969 self.showtraceback(exception_only=True)
1970 except:
1971 self.showtraceback()
1972
1973 def safe_execfile_ipy(self, fname):
1974 """Like safe_execfile, but for .ipy files with IPython syntax.
1975
1976 Parameters
1977 ----------
1978 fname : str
1979 The name of the file to execute. The filename must have a
1980 .ipy extension.
1981 """
1982 fname = os.path.abspath(os.path.expanduser(fname))
1983
1984 # Make sure we have a .py file
1985 if not fname.endswith('.ipy'):
1986 warn('File must end with .py to be run using execfile: <%s>' % fname)
1987
1988 # Make sure we can open the file
1989 try:
1990 with open(fname) as thefile:
1991 pass
1992 except:
1993 warn('Could not open file <%s> for safe execution.' % fname)
1994 return
1995
1996 # Find things also in current directory. This is needed to mimic the
1997 # behavior of running a script from the system command line, where
1998 # Python inserts the script's directory into sys.path
1999 dname = os.path.dirname(fname)
2000
2001 with prepended_to_syspath(dname):
2002 try:
2003 with open(fname) as thefile:
2004 script = thefile.read()
2005 # self.runlines currently captures all exceptions
2006 # raise in user code. It would be nice if there were
2007 # versions of runlines, execfile that did raise, so
2008 # we could catch the errors.
2009 self.runlines(script, clean=True)
2010 except:
2011 self.showtraceback()
2012 warn('Unknown failure executing file: <%s>' % fname)
2013
2014 def _is_secondary_block_start(self, s):
2015 if not s.endswith(':'):
2016 return False
2017 if (s.startswith('elif') or
2018 s.startswith('else') or
2019 s.startswith('except') or
2020 s.startswith('finally')):
2021 return True
2022
2023 def cleanup_ipy_script(self, script):
2024 """Make a script safe for self.runlines()
2025
2026 Currently, IPython is lines based, with blocks being detected by
2027 empty lines. This is a problem for block based scripts that may
2028 not have empty lines after blocks. This script adds those empty
2029 lines to make scripts safe for running in the current line based
2030 IPython.
2031 """
2032 res = []
2033 lines = script.splitlines()
2034 level = 0
2035
2036 for l in lines:
2037 lstripped = l.lstrip()
2038 stripped = l.strip()
2039 if not stripped:
2040 continue
2041 newlevel = len(l) - len(lstripped)
2042 if level > 0 and newlevel == 0 and \
2043 not self._is_secondary_block_start(stripped):
2044 # add empty line
2045 res.append('')
2046 res.append(l)
2047 level = newlevel
2048
2049 return '\n'.join(res) + '\n'
2050
2051 def runlines(self, lines, clean=False):
2052 """Run a string of one or more lines of source.
2053
2054 This method is capable of running a string containing multiple source
2055 lines, as if they had been entered at the IPython prompt. Since it
2056 exposes IPython's processing machinery, the given strings can contain
2057 magic calls (%magic), special shell access (!cmd), etc.
2058 """
2059
2060 if isinstance(lines, (list, tuple)):
2061 lines = '\n'.join(lines)
2062
2063 if clean:
2064 lines = self.cleanup_ipy_script(lines)
2065
2066 # We must start with a clean buffer, in case this is run from an
2067 # interactive IPython session (via a magic, for example).
2068 self.resetbuffer()
2069 lines = lines.splitlines()
2070 more = 0
2071
2072 with nested(self.builtin_trap, self.display_trap):
2073 for line in lines:
2074 # skip blank lines so we don't mess up the prompt counter, but do
2075 # NOT skip even a blank line if we are in a code block (more is
2076 # true)
2077
2078 if line or more:
2079 # push to raw history, so hist line numbers stay in sync
2080 self.input_hist_raw.append("# " + line + "\n")
2081 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2082 more = self.push_line(prefiltered)
2083 # IPython's runsource returns None if there was an error
2084 # compiling the code. This allows us to stop processing right
2085 # away, so the user gets the error message at the right place.
2086 if more is None:
2087 break
2088 else:
2089 self.input_hist_raw.append("\n")
2090 # final newline in case the input didn't have it, so that the code
2091 # actually does get executed
2092 if more:
2093 self.push_line('\n')
2094
2095 def runsource(self, source, filename='<input>', symbol='single'):
2096 """Compile and run some source in the interpreter.
2097
2098 Arguments are as for compile_command().
2099
2100 One several things can happen:
2101
2102 1) The input is incorrect; compile_command() raised an
2103 exception (SyntaxError or OverflowError). A syntax traceback
2104 will be printed by calling the showsyntaxerror() method.
2105
2106 2) The input is incomplete, and more input is required;
2107 compile_command() returned None. Nothing happens.
2108
2109 3) The input is complete; compile_command() returned a code
2110 object. The code is executed by calling self.runcode() (which
2111 also handles run-time exceptions, except for SystemExit).
2112
2113 The return value is:
2114
2115 - True in case 2
2116
2117 - False in the other cases, unless an exception is raised, where
2118 None is returned instead. This can be used by external callers to
2119 know whether to continue feeding input or not.
2120
2121 The return value can be used to decide whether to use sys.ps1 or
2122 sys.ps2 to prompt the next line."""
2123
2124 # if the source code has leading blanks, add 'if 1:\n' to it
2125 # this allows execution of indented pasted code. It is tempting
2126 # to add '\n' at the end of source to run commands like ' a=1'
2127 # directly, but this fails for more complicated scenarios
2128 source=source.encode(self.stdin_encoding)
2129 if source[:1] in [' ', '\t']:
2130 source = 'if 1:\n%s' % source
2131
2132 try:
2133 code = self.compile(source,filename,symbol)
2134 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2135 # Case 1
2136 self.showsyntaxerror(filename)
2137 return None
2138
2139 if code is None:
2140 # Case 2
2141 return True
2142
2143 # Case 3
2144 # We store the code object so that threaded shells and
2145 # custom exception handlers can access all this info if needed.
2146 # The source corresponding to this can be obtained from the
2147 # buffer attribute as '\n'.join(self.buffer).
2148 self.code_to_run = code
2149 # now actually execute the code object
2150 if self.runcode(code) == 0:
2151 return False
2152 else:
2153 return None
2154
2155 def runcode(self,code_obj):
2156 """Execute a code object.
2157
2158 When an exception occurs, self.showtraceback() is called to display a
2159 traceback.
2160
2161 Return value: a flag indicating whether the code to be run completed
2162 successfully:
2163
2164 - 0: successful execution.
2165 - 1: an error occurred.
2166 """
2167
2168 # Set our own excepthook in case the user code tries to call it
2169 # directly, so that the IPython crash handler doesn't get triggered
2170 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2171
2172 # we save the original sys.excepthook in the instance, in case config
2173 # code (such as magics) needs access to it.
2174 self.sys_excepthook = old_excepthook
2175 outflag = 1 # happens in more places, so it's easier as default
2176 try:
2177 try:
2178 self.hooks.pre_runcode_hook()
2179 exec code_obj in self.user_global_ns, self.user_ns
2180 finally:
2181 # Reset our crash handler in place
2182 sys.excepthook = old_excepthook
2183 except SystemExit:
2184 self.resetbuffer()
2185 self.showtraceback(exception_only=True)
2186 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2187 except self.custom_exceptions:
2188 etype,value,tb = sys.exc_info()
2189 self.CustomTB(etype,value,tb)
2190 except:
2191 self.showtraceback()
2192 else:
2193 outflag = 0
2194 if softspace(sys.stdout, 0):
2195 print
2196 # Flush out code object which has been run (and source)
2197 self.code_to_run = None
2198 return outflag
2199
2200 def push_line(self, line):
2201 """Push a line to the interpreter.
2202
2203 The line should not have a trailing newline; it may have
2204 internal newlines. The line is appended to a buffer and the
2205 interpreter's runsource() method is called with the
2206 concatenated contents of the buffer as source. If this
2207 indicates that the command was executed or invalid, the buffer
2208 is reset; otherwise, the command is incomplete, and the buffer
2209 is left as it was after the line was appended. The return
2210 value is 1 if more input is required, 0 if the line was dealt
2211 with in some way (this is the same as runsource()).
2212 """
2213
2214 # autoindent management should be done here, and not in the
2215 # interactive loop, since that one is only seen by keyboard input. We
2216 # need this done correctly even for code run via runlines (which uses
2217 # push).
2218
2219 #print 'push line: <%s>' % line # dbg
2220 for subline in line.splitlines():
2221 self._autoindent_update(subline)
2222 self.buffer.append(line)
2223 more = self.runsource('\n'.join(self.buffer), self.filename)
2224 if not more:
2225 self.resetbuffer()
2226 return more
2227
2228 def _autoindent_update(self,line):
2229 """Keep track of the indent level."""
2230
2231 #debugx('line')
2232 #debugx('self.indent_current_nsp')
2233 if self.autoindent:
2234 if line:
2235 inisp = num_ini_spaces(line)
2236 if inisp < self.indent_current_nsp:
2237 self.indent_current_nsp = inisp
2238
2239 if line[-1] == ':':
2240 self.indent_current_nsp += 4
2241 elif dedent_re.match(line):
2242 self.indent_current_nsp -= 4
2243 else:
2244 self.indent_current_nsp = 0
2245
2246 def resetbuffer(self):
2247 """Reset the input buffer."""
2248 self.buffer[:] = []
2249
2250 def raw_input(self,prompt='',continue_prompt=False):
2251 """Write a prompt and read a line.
2252
2253 The returned line does not include the trailing newline.
2254 When the user enters the EOF key sequence, EOFError is raised.
2255
2256 Optional inputs:
2257
2258 - prompt(''): a string to be printed to prompt the user.
2259
2260 - continue_prompt(False): whether this line is the first one or a
2261 continuation in a sequence of inputs.
2262 """
2263 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2264
2265 # Code run by the user may have modified the readline completer state.
2266 # We must ensure that our completer is back in place.
2267
2268 if self.has_readline:
2269 self.set_completer()
2270
2271 try:
2272 line = raw_input_original(prompt).decode(self.stdin_encoding)
2273 except ValueError:
2274 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2275 " or sys.stdout.close()!\nExiting IPython!")
2276 self.ask_exit()
2277 return ""
2278
2279 # Try to be reasonably smart about not re-indenting pasted input more
2280 # than necessary. We do this by trimming out the auto-indent initial
2281 # spaces, if the user's actual input started itself with whitespace.
2282 #debugx('self.buffer[-1]')
2283
2284 if self.autoindent:
2285 if num_ini_spaces(line) > self.indent_current_nsp:
2286 line = line[self.indent_current_nsp:]
2287 self.indent_current_nsp = 0
2288
2289 # store the unfiltered input before the user has any chance to modify
2290 # it.
2291 if line.strip():
2292 if continue_prompt:
2293 self.input_hist_raw[-1] += '%s\n' % line
2294 if self.has_readline and self.readline_use:
2295 try:
2296 histlen = self.readline.get_current_history_length()
2297 if histlen > 1:
2298 newhist = self.input_hist_raw[-1].rstrip()
2299 self.readline.remove_history_item(histlen-1)
2300 self.readline.replace_history_item(histlen-2,
2301 newhist.encode(self.stdin_encoding))
2302 except AttributeError:
2303 pass # re{move,place}_history_item are new in 2.4.
2304 else:
2305 self.input_hist_raw.append('%s\n' % line)
2306 # only entries starting at first column go to shadow history
2307 if line.lstrip() == line:
2308 self.shadowhist.add(line.strip())
2309 elif not continue_prompt:
2310 self.input_hist_raw.append('\n')
2311 try:
2312 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2313 except:
2314 # blanket except, in case a user-defined prefilter crashes, so it
2315 # can't take all of ipython with it.
2316 self.showtraceback()
2317 return ''
2318 else:
2319 return lineout
2320
2321 #-------------------------------------------------------------------------
2322 # Working with components
2323 #-------------------------------------------------------------------------
2324
2325 def get_component(self, name=None, klass=None):
2326 """Fetch a component by name and klass in my tree."""
2327 c = Component.get_instances(root=self, name=name, klass=klass)
2328 if len(c) == 0:
2329 return None
2330 if len(c) == 1:
2331 return c[0]
2332 else:
2333 return c
2334
2335 #-------------------------------------------------------------------------
2336 # IPython extensions
2337 #-------------------------------------------------------------------------
2338
2339 def load_extension(self, module_str):
2340 """Load an IPython extension by its module name.
2341
2342 An IPython extension is an importable Python module that has
2343 a function with the signature::
2344
2345 def load_ipython_extension(ipython):
2346 # Do things with ipython
2347
2348 This function is called after your extension is imported and the
2349 currently active :class:`InteractiveShell` instance is passed as
2350 the only argument. You can do anything you want with IPython at
2351 that point, including defining new magic and aliases, adding new
2352 components, etc.
2353
2354 The :func:`load_ipython_extension` will be called again is you
2355 load or reload the extension again. It is up to the extension
2356 author to add code to manage that.
2357
2358 You can put your extension modules anywhere you want, as long as
2359 they can be imported by Python's standard import mechanism. However,
2360 to make it easy to write extensions, you can also put your extensions
2361 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
2362 is added to ``sys.path`` automatically.
2363
2364 If :func:`load_ipython_extension` returns anything, this function
2365 will return that object.
2366 """
2367 from IPython.utils.syspathcontext import prepended_to_syspath
2368
2369 if module_str not in sys.modules:
2370 with prepended_to_syspath(self.ipython_extension_dir):
2371 __import__(module_str)
2372 mod = sys.modules[module_str]
2373 return self._call_load_ipython_extension(mod)
2374
2375 def unload_extension(self, module_str):
2376 """Unload an IPython extension by its module name.
2377
2378 This function looks up the extension's name in ``sys.modules`` and
2379 simply calls ``mod.unload_ipython_extension(self)``.
2380 """
2381 if module_str in sys.modules:
2382 mod = sys.modules[module_str]
2383 self._call_unload_ipython_extension(mod)
2384
2385 def reload_extension(self, module_str):
2386 """Reload an IPython extension by calling reload.
2387
2388 If the module has not been loaded before,
2389 :meth:`InteractiveShell.load_extension` is called. Otherwise
2390 :func:`reload` is called and then the :func:`load_ipython_extension`
2391 function of the module, if it exists is called.
2392 """
2393 from IPython.utils.syspathcontext import prepended_to_syspath
2394
2395 with prepended_to_syspath(self.ipython_extension_dir):
2396 if module_str in sys.modules:
2397 mod = sys.modules[module_str]
2398 reload(mod)
2399 self._call_load_ipython_extension(mod)
2400 else:
2401 self.load_extension(module_str)
2402
2403 def _call_load_ipython_extension(self, mod):
2404 if hasattr(mod, 'load_ipython_extension'):
2405 return mod.load_ipython_extension(self)
2406
2407 def _call_unload_ipython_extension(self, mod):
2408 if hasattr(mod, 'unload_ipython_extension'):
2409 return mod.unload_ipython_extension(self)
2410
2411 #-------------------------------------------------------------------------
2412 # Things related to the prefilter
2413 #-------------------------------------------------------------------------
2414
2415 def init_prefilter(self):
2416 self.prefilter_manager = PrefilterManager(self, config=self.config)
2417 # Ultimately this will be refactored in the new interpreter code, but
2418 # for now, we should expose the main prefilter method (there's legacy
2419 # code out there that may rely on this).
2420 self.prefilter = self.prefilter_manager.prefilter_lines
2421
2422 #-------------------------------------------------------------------------
2423 # Utilities
2424 #-------------------------------------------------------------------------
2425
2426 def getoutput(self, cmd):
2427 return getoutput(self.var_expand(cmd,depth=2),
2428 header=self.system_header,
2429 verbose=self.system_verbose)
2430
2431 def getoutputerror(self, cmd):
2432 return getoutputerror(self.var_expand(cmd,depth=2),
2433 header=self.system_header,
2434 verbose=self.system_verbose)
2435
2436 def var_expand(self,cmd,depth=0):
2437 """Expand python variables in a string.
2438
2439 The depth argument indicates how many frames above the caller should
2440 be walked to look for the local namespace where to expand variables.
2441
2442 The global namespace for expansion is always the user's interactive
2443 namespace.
2444 """
2445
2446 return str(ItplNS(cmd,
2447 self.user_ns, # globals
2448 # Skip our own frame in searching for locals:
2449 sys._getframe(depth+1).f_locals # locals
2450 ))
2451
2452 def mktempfile(self,data=None):
2453 """Make a new tempfile and return its filename.
2454
2455 This makes a call to tempfile.mktemp, but it registers the created
2456 filename internally so ipython cleans it up at exit time.
2457
2458 Optional inputs:
2459
2460 - data(None): if data is given, it gets written out to the temp file
2461 immediately, and the file is closed again."""
2462
2463 filename = tempfile.mktemp('.py','ipython_edit_')
2464 self.tempfiles.append(filename)
2465
2466 if data:
2467 tmp_file = open(filename,'w')
2468 tmp_file.write(data)
2469 tmp_file.close()
2470 return filename
2471
2472 def write(self,data):
2473 """Write a string to the default output"""
2474 Term.cout.write(data)
2475
2476 def write_err(self,data):
2477 """Write a string to the default error output"""
2478 Term.cerr.write(data)
2479
2480 def ask_yes_no(self,prompt,default=True):
2481 if self.quiet:
2482 return True
2483 return ask_yes_no(prompt,default)
2484
2485 #-------------------------------------------------------------------------
2486 # Things related to GUI support and pylab
2487 #-------------------------------------------------------------------------
2488
2489 def enable_pylab(self, gui=None):
2490 """Activate pylab support at runtime.
2491
2492 This turns on support for matplotlib, preloads into the interactive
2493 namespace all of numpy and pylab, and configures IPython to correcdtly
2494 interact with the GUI event loop. The GUI backend to be used can be
2495 optionally selected with the optional :param:`gui` argument.
2496
2497 Parameters
2498 ----------
2499 gui : optional, string
2500
2501 If given, dictates the choice of matplotlib GUI backend to use
2502 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
2503 'gtk'), otherwise we use the default chosen by matplotlib (as
2504 dictated by the matplotlib build-time options plus the user's
2505 matplotlibrc configuration file).
2506 """
2507 # We want to prevent the loading of pylab to pollute the user's
2508 # namespace as shown by the %who* magics, so we execute the activation
2509 # code in an empty namespace, and we update *both* user_ns and
2510 # user_ns_hidden with this information.
2511 ns = {}
2512 gui = pylab_activate(ns, gui)
2513 self.user_ns.update(ns)
2514 self.user_ns_hidden.update(ns)
2515 # Now we must activate the gui pylab wants to use, and fix %run to take
2516 # plot updates into account
2517 enable_gui(gui)
2518 self.magic_run = self._pylab_magic_run
2519
2520 #-------------------------------------------------------------------------
2521 # Things related to IPython exiting
2522 #-------------------------------------------------------------------------
2523
2524 def ask_exit(self):
2525 """ Ask the shell to exit. Can be overiden and used as a callback. """
2526 self.exit_now = True
2527
2528 def exit(self):
2529 """Handle interactive exit.
2530
2531 This method calls the ask_exit callback."""
2532 if self.confirm_exit:
2533 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2534 self.ask_exit()
2535 else:
2536 self.ask_exit()
2537
2538 def atexit_operations(self):
2539 """This will be executed at the time of exit.
2540
2541 Saving of persistent data should be performed here.
2542 """
2543 self.savehist()
2544
2545 # Cleanup all tempfiles left around
2546 for tfile in self.tempfiles:
2547 try:
2548 os.unlink(tfile)
2549 except OSError:
2550 pass
2551
2552 # Clear all user namespaces to release all references cleanly.
2553 self.reset()
2554
2555 # Run user hooks
2556 self.hooks.shutdown_hook()
2557
2558 def cleanup(self):
2559 self.restore_sys_module_state()
2560
2561
@@ -0,0 +1,306 b''
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Paging capabilities for IPython.core
5
6 Authors:
7
8 * Brian Granger
9 * Fernando Perez
10
11 Notes
12 -----
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
16 -----
17 """
18
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
25
26 #-----------------------------------------------------------------------------
27 # Imports
28 #-----------------------------------------------------------------------------
29
30 import os
31 import re
32 import sys
33 import tempfile
34
35 from IPython.core import ipapi
36 from IPython.core.error import TryNext
37 from IPython.utils.cursesimport import use_curses
38 from IPython.utils.data import chop
39 from IPython.utils.io import Term
40 from IPython.utils.process import xsys
41 from IPython.utils.terminal import get_terminal_size
42
43
44 #-----------------------------------------------------------------------------
45 # Classes and functions
46 #-----------------------------------------------------------------------------
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
50 def page_dumb(strng, start=0, screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
52
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
55
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
59 print >>Term.cout, os.linesep.join(screens[0])
60 else:
61 last_escape = ""
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
64 print >>Term.cout, last_escape + hunk
65 if not page_more():
66 return
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
71
72
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
74 """Print a string, piping through a pager after a certain length.
75
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
89
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
92 """
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
96 start = max(0, start)
97
98 # first, try the hook
99 ip = ipapi.get()
100 if ip:
101 try:
102 ip.hooks.show_in_pager(strng)
103 return
104 except TryNext:
105 pass
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
111 return
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
122
123 screen_lines_def = get_terminal_size()[1]
124
125 # auto-determine screen size
126 if screen_lines <= 0:
127 if TERM=='xterm' or TERM=='xterm-color':
128 local_use_curses = use_curses
129 else:
130 # curses causes problems on many terminals other than xterm.
131 local_use_curses = False
132 if local_use_curses:
133 import termios
134 import curses
135 # There is a bug in curses, where *sometimes* it fails to properly
136 # initialize, and then after the endwin() call is made, the
137 # terminal is left in an unusable state. Rather than trying to
138 # check everytime for this (by requesting and comparing termios
139 # flags each time), we just save the initial terminal state and
140 # unconditionally reset it every time. It's cheaper than making
141 # the checks.
142 term_flags = termios.tcgetattr(sys.stdout)
143 scr = curses.initscr()
144 screen_lines_real,screen_cols = scr.getmaxyx()
145 curses.endwin()
146 # Restore terminal state in case endwin() didn't.
147 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
148 # Now we have what we needed: the screen size in rows/columns
149 screen_lines += screen_lines_real
150 #print '***Screen size:',screen_lines_real,'lines x',\
151 #screen_cols,'columns.' # dbg
152 else:
153 screen_lines += screen_lines_def
154
155 #print 'numlines',numlines,'screenlines',screen_lines # dbg
156 if numlines <= screen_lines :
157 #print '*** normal print' # dbg
158 print >>Term.cout, str_toprint
159 else:
160 # Try to open pager and default to internal one if that fails.
161 # All failure modes are tagged as 'retval=1', to match the return
162 # value of a failed system command. If any intermediate attempt
163 # sets retval to 1, at the end we resort to our own page_dumb() pager.
164 pager_cmd = get_pager_cmd(pager_cmd)
165 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
166 if os.name == 'nt':
167 if pager_cmd.startswith('type'):
168 # The default WinXP 'type' command is failing on complex strings.
169 retval = 1
170 else:
171 tmpname = tempfile.mktemp('.txt')
172 tmpfile = file(tmpname,'wt')
173 tmpfile.write(strng)
174 tmpfile.close()
175 cmd = "%s < %s" % (pager_cmd,tmpname)
176 if os.system(cmd):
177 retval = 1
178 else:
179 retval = None
180 os.remove(tmpname)
181 else:
182 try:
183 retval = None
184 # if I use popen4, things hang. No idea why.
185 #pager,shell_out = os.popen4(pager_cmd)
186 pager = os.popen(pager_cmd,'w')
187 pager.write(strng)
188 pager.close()
189 retval = pager.close() # success returns None
190 except IOError,msg: # broken pipe when user quits
191 if msg.args == (32,'Broken pipe'):
192 retval = None
193 else:
194 retval = 1
195 except OSError:
196 # Other strange problems, sometimes seen in Win2k/cygwin
197 retval = 1
198 if retval is not None:
199 page_dumb(strng,screen_lines=screen_lines)
200
201
202 def page_file(fname, start=0, pager_cmd=None):
203 """Page a file, using an optional pager command and starting line.
204 """
205
206 pager_cmd = get_pager_cmd(pager_cmd)
207 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
208
209 try:
210 if os.environ['TERM'] in ['emacs','dumb']:
211 raise EnvironmentError
212 xsys(pager_cmd + ' ' + fname)
213 except:
214 try:
215 if start > 0:
216 start -= 1
217 page(open(fname).read(),start)
218 except:
219 print 'Unable to show file',`fname`
220
221
222 def get_pager_cmd(pager_cmd=None):
223 """Return a pager command.
224
225 Makes some attempts at finding an OS-correct one.
226 """
227 if os.name == 'posix':
228 default_pager_cmd = 'less -r' # -r for color control sequences
229 elif os.name in ['nt','dos']:
230 default_pager_cmd = 'type'
231
232 if pager_cmd is None:
233 try:
234 pager_cmd = os.environ['PAGER']
235 except:
236 pager_cmd = default_pager_cmd
237 return pager_cmd
238
239
240 def get_pager_start(pager, start):
241 """Return the string for paging files with an offset.
242
243 This is the '+N' argument which less and more (under Unix) accept.
244 """
245
246 if pager in ['less','more']:
247 if start:
248 start_string = '+' + str(start)
249 else:
250 start_string = ''
251 else:
252 start_string = ''
253 return start_string
254
255
256 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
257 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
258 import msvcrt
259 def page_more():
260 """ Smart pausing between pages
261
262 @return: True if need print more lines, False if quit
263 """
264 Term.cout.write('---Return to continue, q to quit--- ')
265 ans = msvcrt.getch()
266 if ans in ("q", "Q"):
267 result = False
268 else:
269 result = True
270 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
271 return result
272 else:
273 def page_more():
274 ans = raw_input('---Return to continue, q to quit--- ')
275 if ans.lower().startswith('q'):
276 return False
277 else:
278 return True
279
280
281 def snip_print(str,width = 75,print_full = 0,header = ''):
282 """Print a string snipping the midsection to fit in width.
283
284 print_full: mode control:
285 - 0: only snip long strings
286 - 1: send to page() directly.
287 - 2: snip long strings and ask for full length viewing with page()
288 Return 1 if snipping was necessary, 0 otherwise."""
289
290 if print_full == 1:
291 page(header+str)
292 return 0
293
294 print header,
295 if len(str) < width:
296 print str
297 snip = 0
298 else:
299 whalf = int((width -5)/2)
300 print str[:whalf] + ' <...> ' + str[-whalf:]
301 snip = 1
302 if snip and print_full == 2:
303 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
304 page(str)
305 return snip
306
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644, binary diff hidden
NO CONTENT: new file 100644, binary diff hidden
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100755
NO CONTENT: new file 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
The requested commit or file is too big and content was truncated. Show full diff
This diff has been collapsed as it changes many lines, (1252 lines changed) Show them Hide them
@@ -1,1244 +1,42 b''
1 # -*- coding: utf-8 -*-
1 #!/usr/bin/env python
2 """IPython Shell classes.
2 # encoding: utf-8
3 """
4 A backwards compatibility layer for IPython.Shell.
3
5
4 All the matplotlib support code was co-developed with John Hunter,
6 Previously, IPython had an IPython.Shell module. IPython.Shell has been moved
5 matplotlib's author.
7 to IPython.core.shell and is being refactored. This new module is provided
8 for backwards compatability. We strongly encourage everyone to start using
9 the new code in IPython.core.shell.
6 """
10 """
7
11
8 #*****************************************************************************
12 #-----------------------------------------------------------------------------
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
13 # Copyright (C) 2008-2009 The IPython Development Team
10 #
14 #
11 # 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
12 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
14
15 # Code begins
16 # Stdlib imports
17 import __builtin__
18 import __main__
19 import Queue
20 import inspect
21 import os
22 import sys
23 import thread
24 import threading
25 import time
26
27 from signal import signal, SIGINT
28
29 try:
30 import ctypes
31 HAS_CTYPES = True
32 except ImportError:
33 HAS_CTYPES = False
34
35 # IPython imports
36 import IPython
37 from IPython import ultraTB, ipapi
38 from IPython.Magic import Magic
39 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
40 from IPython.iplib import InteractiveShell
41 from IPython.ipmaker import make_IPython
42 from IPython.ipstruct import Struct
43 from IPython.testing import decorators as testdec
44
45 # Globals
46 # global flag to pass around information about Ctrl-C without exceptions
47 KBINT = False
48
49 # global flag to turn on/off Tk support.
50 USE_TK = False
51
52 # ID for the main thread, used for cross-thread exceptions
53 MAIN_THREAD_ID = thread.get_ident()
54
55 # Tag when runcode() is active, for exception handling
56 CODE_RUN = None
57
58 # Default timeout for waiting for multithreaded shells (in seconds)
59 GUI_TIMEOUT = 10
60
61 #-----------------------------------------------------------------------------
62 # This class is trivial now, but I want to have it in to publish a clean
63 # interface. Later when the internals are reorganized, code that uses this
64 # shouldn't have to change.
65
66 class IPShell:
67 """Create an IPython instance."""
68
69 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
70 debug=1,shell_class=InteractiveShell):
71 self.IP = make_IPython(argv,user_ns=user_ns,
72 user_global_ns=user_global_ns,
73 debug=debug,shell_class=shell_class)
74
75 def mainloop(self,sys_exit=0,banner=None):
76 self.IP.mainloop(banner)
77 if sys_exit:
78 sys.exit()
79
80 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
81 def kill_embedded(self,parameter_s=''):
82 """%kill_embedded : deactivate for good the current embedded IPython.
83
84 This function (after asking for confirmation) sets an internal flag so that
85 an embedded IPython will never activate again. This is useful to
86 permanently disable a shell that is being called inside a loop: once you've
87 figured out what you needed from it, you may then kill it and the program
88 will then continue to run without the interactive shell interfering again.
89 """
90
91 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
92 "(y/n)? [y/N] ",'n')
93 if kill:
94 self.shell.embedded_active = False
95 print "This embedded IPython will not reactivate anymore once you exit."
96
97 class IPShellEmbed:
98 """Allow embedding an IPython shell into a running program.
99
100 Instances of this class are callable, with the __call__ method being an
101 alias to the embed() method of an InteractiveShell instance.
102
103 Usage (see also the example-embed.py file for a running example):
104
105 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
106
107 - argv: list containing valid command-line options for IPython, as they
108 would appear in sys.argv[1:].
109
110 For example, the following command-line options:
111
112 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
113
114 would be passed in the argv list as:
115
116 ['-prompt_in1','Input <\\#>','-colors','LightBG']
117
118 - banner: string which gets printed every time the interpreter starts.
119
120 - exit_msg: string which gets printed every time the interpreter exits.
121
122 - rc_override: a dict or Struct of configuration options such as those
123 used by IPython. These options are read from your ~/.ipython/ipythonrc
124 file when the Shell object is created. Passing an explicit rc_override
125 dict with any options you want allows you to override those values at
126 creation time without having to modify the file. This way you can create
127 embeddable instances configured in any way you want without editing any
128 global files (thus keeping your interactive IPython configuration
129 unchanged).
130
131 Then the ipshell instance can be called anywhere inside your code:
132
133 ipshell(header='') -> Opens up an IPython shell.
134
135 - header: string printed by the IPython shell upon startup. This can let
136 you know where in your code you are when dropping into the shell. Note
137 that 'banner' gets prepended to all calls, so header is used for
138 location-specific information.
139
140 For more details, see the __call__ method below.
141
142 When the IPython shell is exited with Ctrl-D, normal program execution
143 resumes.
144
145 This functionality was inspired by a posting on comp.lang.python by cmkl
146 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
147 by the IDL stop/continue commands."""
148
149 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
150 user_ns=None):
151 """Note that argv here is a string, NOT a list."""
152 self.set_banner(banner)
153 self.set_exit_msg(exit_msg)
154 self.set_dummy_mode(0)
155
156 # sys.displayhook is a global, we need to save the user's original
157 # Don't rely on __displayhook__, as the user may have changed that.
158 self.sys_displayhook_ori = sys.displayhook
159
160 # save readline completer status
161 try:
162 #print 'Save completer',sys.ipcompleter # dbg
163 self.sys_ipcompleter_ori = sys.ipcompleter
164 except:
165 pass # not nested with IPython
166
167 self.IP = make_IPython(argv,rc_override=rc_override,
168 embedded=True,
169 user_ns=user_ns)
170
171 ip = ipapi.IPApi(self.IP)
172 ip.expose_magic("kill_embedded",kill_embedded)
173
174 # copy our own displayhook also
175 self.sys_displayhook_embed = sys.displayhook
176 # and leave the system's display hook clean
177 sys.displayhook = self.sys_displayhook_ori
178 # don't use the ipython crash handler so that user exceptions aren't
179 # trapped
180 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
181 mode = self.IP.rc.xmode,
182 call_pdb = self.IP.rc.pdb)
183 self.restore_system_completer()
184
185 def restore_system_completer(self):
186 """Restores the readline completer which was in place.
187
188 This allows embedded IPython within IPython not to disrupt the
189 parent's completion.
190 """
191
192 try:
193 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
194 sys.ipcompleter = self.sys_ipcompleter_ori
195 except:
196 pass
197
198 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
199 """Activate the interactive interpreter.
200
201 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
202 the interpreter shell with the given local and global namespaces, and
203 optionally print a header string at startup.
204
205 The shell can be globally activated/deactivated using the
206 set/get_dummy_mode methods. This allows you to turn off a shell used
207 for debugging globally.
208
209 However, *each* time you call the shell you can override the current
210 state of dummy_mode with the optional keyword parameter 'dummy'. For
211 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
212 can still have a specific call work by making it as IPShell(dummy=0).
213
214 The optional keyword parameter dummy controls whether the call
215 actually does anything. """
216
217 # If the user has turned it off, go away
218 if not self.IP.embedded_active:
219 return
220
221 # Normal exits from interactive mode set this flag, so the shell can't
222 # re-enter (it checks this variable at the start of interactive mode).
223 self.IP.exit_now = False
224
225 # Allow the dummy parameter to override the global __dummy_mode
226 if dummy or (dummy != 0 and self.__dummy_mode):
227 return
228
229 # Set global subsystems (display,completions) to our values
230 sys.displayhook = self.sys_displayhook_embed
231 if self.IP.has_readline:
232 self.IP.set_completer()
233
234 if self.banner and header:
235 format = '%s\n%s\n'
236 else:
237 format = '%s%s\n'
238 banner = format % (self.banner,header)
239
240 # Call the embedding code with a stack depth of 1 so it can skip over
241 # our call and get the original caller's namespaces.
242 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
243
244 if self.exit_msg:
245 print self.exit_msg
246
247 # Restore global systems (display, completion)
248 sys.displayhook = self.sys_displayhook_ori
249 self.restore_system_completer()
250
251 def set_dummy_mode(self,dummy):
252 """Sets the embeddable shell's dummy mode parameter.
253
254 set_dummy_mode(dummy): dummy = 0 or 1.
255
256 This parameter is persistent and makes calls to the embeddable shell
257 silently return without performing any action. This allows you to
258 globally activate or deactivate a shell you're using with a single call.
259
260 If you need to manually"""
261
18
262 if dummy not in [0,1,False,True]:
19 from warnings import warn
263 raise ValueError,'dummy parameter must be boolean'
264 self.__dummy_mode = dummy
265
20
266 def get_dummy_mode(self):
21 msg = """
267 """Return the current value of the dummy mode parameter.
22 This module (IPython.Shell) is deprecated. The classes that were in this
268 """
23 module have been replaced by:
269 return self.__dummy_mode
270
271 def set_banner(self,banner):
272 """Sets the global banner.
273
24
274 This banner gets prepended to every header printed when the shell
25 IPShell->IPython.core.iplib.InteractiveShell
275 instance is called."""
26 IPShellEmbed->IPython.core.embed.InteractiveShellEmbed
276
27
277 self.banner = banner
28 Please migrate your code to use these classes instead.
278
279 def set_exit_msg(self,exit_msg):
280 """Sets the global exit_msg.
281
282 This exit message gets printed upon exiting every time the embedded
283 shell is called. It is None by default. """
284
285 self.exit_msg = exit_msg
286
287 #-----------------------------------------------------------------------------
288 if HAS_CTYPES:
289 # Add async exception support. Trick taken from:
290 # http://sebulba.wikispaces.com/recipe+thread2
291 def _async_raise(tid, exctype):
292 """raises the exception, performs cleanup if needed"""
293 if not inspect.isclass(exctype):
294 raise TypeError("Only types can be raised (not instances)")
295 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
296 ctypes.py_object(exctype))
297 if res == 0:
298 raise ValueError("invalid thread id")
299 elif res != 1:
300 # """if it returns a number greater than one, you're in trouble,
301 # and you should call it again with exc=NULL to revert the effect"""
302 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
303 raise SystemError("PyThreadState_SetAsyncExc failed")
304
305 def sigint_handler (signum,stack_frame):
306 """Sigint handler for threaded apps.
307
308 This is a horrible hack to pass information about SIGINT _without_
309 using exceptions, since I haven't been able to properly manage
310 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
311 done (or at least that's my understanding from a c.l.py thread where
312 this was discussed)."""
313
314 global KBINT
315
316 if CODE_RUN:
317 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
318 else:
319 KBINT = True
320 print '\nKeyboardInterrupt - Press <Enter> to continue.',
321 Term.cout.flush()
322
323 else:
324 def sigint_handler (signum,stack_frame):
325 """Sigint handler for threaded apps.
326
327 This is a horrible hack to pass information about SIGINT _without_
328 using exceptions, since I haven't been able to properly manage
329 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
330 done (or at least that's my understanding from a c.l.py thread where
331 this was discussed)."""
332
333 global KBINT
334
335 print '\nKeyboardInterrupt - Press <Enter> to continue.',
336 Term.cout.flush()
337 # Set global flag so that runsource can know that Ctrl-C was hit
338 KBINT = True
339
340
341 class MTInteractiveShell(InteractiveShell):
342 """Simple multi-threaded shell."""
343
344 # Threading strategy taken from:
345 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
346 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
347 # from the pygtk mailing list, to avoid lockups with system calls.
348
349 # class attribute to indicate whether the class supports threads or not.
350 # Subclasses with thread support should override this as needed.
351 isthreaded = True
352
353 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
354 user_ns=None,user_global_ns=None,banner2='',
355 gui_timeout=GUI_TIMEOUT,**kw):
356 """Similar to the normal InteractiveShell, but with threading control"""
357
358 InteractiveShell.__init__(self,name,usage,rc,user_ns,
359 user_global_ns,banner2)
360
361 # Timeout we wait for GUI thread
362 self.gui_timeout = gui_timeout
363
364 # A queue to hold the code to be executed.
365 self.code_queue = Queue.Queue()
366
367 # Stuff to do at closing time
368 self._kill = None
369 on_kill = kw.get('on_kill', [])
370 # Check that all things to kill are callable:
371 for t in on_kill:
372 if not callable(t):
373 raise TypeError,'on_kill must be a list of callables'
374 self.on_kill = on_kill
375 # thread identity of the "worker thread" (that may execute code directly)
376 self.worker_ident = None
377
378 def runsource(self, source, filename="<input>", symbol="single"):
379 """Compile and run some source in the interpreter.
380
381 Modified version of code.py's runsource(), to handle threading issues.
382 See the original for full docstring details."""
383
384 global KBINT
385
386 # If Ctrl-C was typed, we reset the flag and return right away
387 if KBINT:
388 KBINT = False
389 return False
390
391 if self._kill:
392 # can't queue new code if we are being killed
393 return True
394
395 try:
396 code = self.compile(source, filename, symbol)
397 except (OverflowError, SyntaxError, ValueError):
398 # Case 1
399 self.showsyntaxerror(filename)
400 return False
401
402 if code is None:
403 # Case 2
404 return True
405
406 # shortcut - if we are in worker thread, or the worker thread is not
407 # running, execute directly (to allow recursion and prevent deadlock if
408 # code is run early in IPython construction)
409
410 if (self.worker_ident is None
411 or self.worker_ident == thread.get_ident() ):
412 InteractiveShell.runcode(self,code)
413 return False
414
415 # Case 3
416 # Store code in queue, so the execution thread can handle it.
417
418 completed_ev, received_ev = threading.Event(), threading.Event()
419
420 self.code_queue.put((code,completed_ev, received_ev))
421 # first make sure the message was received, with timeout
422 received_ev.wait(self.gui_timeout)
423 if not received_ev.isSet():
424 # the mainloop is dead, start executing code directly
425 print "Warning: Timeout for mainloop thread exceeded"
426 print "switching to nonthreaded mode (until mainloop wakes up again)"
427 self.worker_ident = None
428 else:
429 completed_ev.wait()
430 return False
431
432 def runcode(self):
433 """Execute a code object.
434
435 Multithreaded wrapper around IPython's runcode()."""
436
437 global CODE_RUN
438
439 # we are in worker thread, stash out the id for runsource()
440 self.worker_ident = thread.get_ident()
441
442 if self._kill:
443 print >>Term.cout, 'Closing threads...',
444 Term.cout.flush()
445 for tokill in self.on_kill:
446 tokill()
447 print >>Term.cout, 'Done.'
448 # allow kill() to return
449 self._kill.set()
450 return True
451
452 # Install sigint handler. We do it every time to ensure that if user
453 # code modifies it, we restore our own handling.
454 try:
455 signal(SIGINT,sigint_handler)
456 except SystemError:
457 # This happens under Windows, which seems to have all sorts
458 # of problems with signal handling. Oh well...
459 pass
460
461 # Flush queue of pending code by calling the run methood of the parent
462 # class with all items which may be in the queue.
463 code_to_run = None
464 while 1:
465 try:
466 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
467 except Queue.Empty:
468 break
469 received_ev.set()
470
471 # Exceptions need to be raised differently depending on which
472 # thread is active. This convoluted try/except is only there to
473 # protect against asynchronous exceptions, to ensure that a KBINT
474 # at the wrong time doesn't deadlock everything. The global
475 # CODE_TO_RUN is set to true/false as close as possible to the
476 # runcode() call, so that the KBINT handler is correctly informed.
477 try:
478 try:
479 CODE_RUN = True
480 InteractiveShell.runcode(self,code_to_run)
481 except KeyboardInterrupt:
482 print "Keyboard interrupted in mainloop"
483 while not self.code_queue.empty():
484 code, ev1,ev2 = self.code_queue.get_nowait()
485 ev1.set()
486 ev2.set()
487 break
488 finally:
489 CODE_RUN = False
490 # allow runsource() return from wait
491 completed_ev.set()
492
493
494 # This MUST return true for gtk threading to work
495 return True
496
497 def kill(self):
498 """Kill the thread, returning when it has been shut down."""
499 self._kill = threading.Event()
500 self._kill.wait()
501
502 class MatplotlibShellBase:
503 """Mixin class to provide the necessary modifications to regular IPython
504 shell classes for matplotlib support.
505
506 Given Python's MRO, this should be used as the FIRST class in the
507 inheritance hierarchy, so that it overrides the relevant methods."""
508
509 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
510 """Return items needed to setup the user's shell with matplotlib"""
511
512 # Initialize matplotlib to interactive mode always
513 import matplotlib
514 from matplotlib import backends
515 matplotlib.interactive(True)
516
517 def use(arg):
518 """IPython wrapper for matplotlib's backend switcher.
519
520 In interactive use, we can not allow switching to a different
521 interactive backend, since thread conflicts will most likely crash
522 the python interpreter. This routine does a safety check first,
523 and refuses to perform a dangerous switch. It still allows
524 switching to non-interactive backends."""
525
526 if arg in backends.interactive_bk and arg != self.mpl_backend:
527 m=('invalid matplotlib backend switch.\n'
528 'This script attempted to switch to the interactive '
529 'backend: `%s`\n'
530 'Your current choice of interactive backend is: `%s`\n\n'
531 'Switching interactive matplotlib backends at runtime\n'
532 'would crash the python interpreter, '
533 'and IPython has blocked it.\n\n'
534 'You need to either change your choice of matplotlib backend\n'
535 'by editing your .matplotlibrc file, or run this script as a \n'
536 'standalone file from the command line, not using IPython.\n' %
537 (arg,self.mpl_backend) )
538 raise RuntimeError, m
539 else:
540 self.mpl_use(arg)
541 self.mpl_use._called = True
542
543 self.matplotlib = matplotlib
544 self.mpl_backend = matplotlib.rcParams['backend']
545
546 # we also need to block switching of interactive backends by use()
547 self.mpl_use = matplotlib.use
548 self.mpl_use._called = False
549 # overwrite the original matplotlib.use with our wrapper
550 matplotlib.use = use
551
552 # This must be imported last in the matplotlib series, after
553 # backend/interactivity choices have been made
554 import matplotlib.pylab as pylab
555 self.pylab = pylab
556
557 self.pylab.show._needmain = False
558 # We need to detect at runtime whether show() is called by the user.
559 # For this, we wrap it into a decorator which adds a 'called' flag.
560 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
561
562 # Build a user namespace initialized with matplotlib/matlab features.
563 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
564 user_global_ns)
565
566 # Import numpy as np/pyplot as plt are conventions we're trying to
567 # somewhat standardize on. Making them available to users by default
568 # will greatly help this.
569 exec ("import numpy\n"
570 "import numpy as np\n"
571 "import matplotlib\n"
572 "import matplotlib.pylab as pylab\n"
573 "try:\n"
574 " import matplotlib.pyplot as plt\n"
575 "except ImportError:\n"
576 " pass\n"
577 ) in user_ns
578
579 # Build matplotlib info banner
580 b="""
581 Welcome to pylab, a matplotlib-based Python environment.
582 For more information, type 'help(pylab)'.
583 """
29 """
584 return user_ns,user_global_ns,b
585
586 def mplot_exec(self,fname,*where,**kw):
587 """Execute a matplotlib script.
588
589 This is a call to execfile(), but wrapped in safeties to properly
590 handle interactive rendering and backend switching."""
591
592 #print '*** Matplotlib runner ***' # dbg
593 # turn off rendering until end of script
594 isInteractive = self.matplotlib.rcParams['interactive']
595 self.matplotlib.interactive(False)
596 self.safe_execfile(fname,*where,**kw)
597 self.matplotlib.interactive(isInteractive)
598 # make rendering call now, if the user tried to do it
599 if self.pylab.draw_if_interactive.called:
600 self.pylab.draw()
601 self.pylab.draw_if_interactive.called = False
602
603 # if a backend switch was performed, reverse it now
604 if self.mpl_use._called:
605 self.matplotlib.rcParams['backend'] = self.mpl_backend
606
607 @testdec.skip_doctest
608 def magic_run(self,parameter_s=''):
609 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
610
611 # Fix the docstring so users see the original as well
612 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
613 "\n *** Modified %run for Matplotlib,"
614 " with proper interactive handling ***")
615
616 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
617 # and multithreaded. Note that these are meant for internal use, the IPShell*
618 # classes below are the ones meant for public consumption.
619
620 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
621 """Single-threaded shell with matplotlib support."""
622
623 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
624 user_ns=None,user_global_ns=None,**kw):
625 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
626 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
627 banner2=b2,**kw)
628
629 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
630 """Multi-threaded shell with matplotlib support."""
631
632 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
633 user_ns=None,user_global_ns=None, **kw):
634 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
635 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
636 banner2=b2,**kw)
637
30
638 #-----------------------------------------------------------------------------
31 warn(msg, category=DeprecationWarning, stacklevel=1)
639 # Utility functions for the different GUI enabled IPShell* classes.
640
641 def get_tk():
642 """Tries to import Tkinter and returns a withdrawn Tkinter root
643 window. If Tkinter is already imported or not available, this
644 returns None. This function calls `hijack_tk` underneath.
645 """
646 if not USE_TK or sys.modules.has_key('Tkinter'):
647 return None
648 else:
649 try:
650 import Tkinter
651 except ImportError:
652 return None
653 else:
654 hijack_tk()
655 r = Tkinter.Tk()
656 r.withdraw()
657 return r
658
659 def hijack_tk():
660 """Modifies Tkinter's mainloop with a dummy so when a module calls
661 mainloop, it does not block.
662
32
663 """
33 from IPython.core.iplib import InteractiveShell as IPShell
664 def misc_mainloop(self, n=0):
34 from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed
665 pass
666 def tkinter_mainloop(n=0):
667 pass
668
669 import Tkinter
670 Tkinter.Misc.mainloop = misc_mainloop
671 Tkinter.mainloop = tkinter_mainloop
672
35
673 def update_tk(tk):
36 def start(user_ns=None, embedded=False):
674 """Updates the Tkinter event loop. This is typically called from
37 """Return an instance of :class:`InteractiveShell`."""
675 the respective WX or GTK mainloops.
38 if embedded:
676 """
39 return InteractiveShellEmbed(user_ns=user_ns)
677 if tk:
678 tk.update()
679
680 def hijack_wx():
681 """Modifies wxPython's MainLoop with a dummy so user code does not
682 block IPython. The hijacked mainloop function is returned.
683 """
684 def dummy_mainloop(*args, **kw):
685 pass
686
687 try:
688 import wx
689 except ImportError:
690 # For very old versions of WX
691 import wxPython as wx
692
693 ver = wx.__version__
694 orig_mainloop = None
695 if ver[:3] >= '2.5':
696 import wx
697 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
698 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
699 else: raise AttributeError('Could not find wx core module')
700 orig_mainloop = core.PyApp_MainLoop
701 core.PyApp_MainLoop = dummy_mainloop
702 elif ver[:3] == '2.4':
703 orig_mainloop = wx.wxc.wxPyApp_MainLoop
704 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
705 else:
40 else:
706 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
41 return InteractiveShell(user_ns=user_ns)
707 return orig_mainloop
708
709 def hijack_gtk():
710 """Modifies pyGTK's mainloop with a dummy so user code does not
711 block IPython. This function returns the original `gtk.mainloop`
712 function that has been hijacked.
713 """
714 def dummy_mainloop(*args, **kw):
715 pass
716 import gtk
717 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
718 else: orig_mainloop = gtk.mainloop
719 gtk.mainloop = dummy_mainloop
720 gtk.main = dummy_mainloop
721 return orig_mainloop
722
723 def hijack_qt():
724 """Modifies PyQt's mainloop with a dummy so user code does not
725 block IPython. This function returns the original
726 `qt.qApp.exec_loop` function that has been hijacked.
727 """
728 def dummy_mainloop(*args, **kw):
729 pass
730 import qt
731 orig_mainloop = qt.qApp.exec_loop
732 qt.qApp.exec_loop = dummy_mainloop
733 qt.QApplication.exec_loop = dummy_mainloop
734 return orig_mainloop
735
736 def hijack_qt4():
737 """Modifies PyQt4's mainloop with a dummy so user code does not
738 block IPython. This function returns the original
739 `QtGui.qApp.exec_` function that has been hijacked.
740 """
741 def dummy_mainloop(*args, **kw):
742 pass
743 from PyQt4 import QtGui, QtCore
744 orig_mainloop = QtGui.qApp.exec_
745 QtGui.qApp.exec_ = dummy_mainloop
746 QtGui.QApplication.exec_ = dummy_mainloop
747 QtCore.QCoreApplication.exec_ = dummy_mainloop
748 return orig_mainloop
749
750 #-----------------------------------------------------------------------------
751 # The IPShell* classes below are the ones meant to be run by external code as
752 # IPython instances. Note that unless a specific threading strategy is
753 # desired, the factory function start() below should be used instead (it
754 # selects the proper threaded class).
755
756 class IPThread(threading.Thread):
757 def run(self):
758 self.IP.mainloop(self._banner)
759 self.IP.kill()
760
761 class IPShellGTK(IPThread):
762 """Run a gtk mainloop() in a separate thread.
763
764 Python commands can be passed to the thread where they will be executed.
765 This is implemented by periodically checking for passed code using a
766 GTK timeout callback."""
767
768 TIMEOUT = 100 # Millisecond interval between timeouts.
769
770 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
771 debug=1,shell_class=MTInteractiveShell):
772
773 import gtk
774 # Check for set_interactive, coming up in new pygtk.
775 # Disable it so that this code works, but notify
776 # the user that he has a better option as well.
777 # XXX TODO better support when set_interactive is released
778 try:
779 gtk.set_interactive(False)
780 print "Your PyGtk has set_interactive(), so you can use the"
781 print "more stable single-threaded Gtk mode."
782 print "See https://bugs.launchpad.net/ipython/+bug/270856"
783 except AttributeError:
784 pass
785
786 self.gtk = gtk
787 self.gtk_mainloop = hijack_gtk()
788
789 # Allows us to use both Tk and GTK.
790 self.tk = get_tk()
791
792 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
793 else: mainquit = self.gtk.mainquit
794
795 self.IP = make_IPython(argv,user_ns=user_ns,
796 user_global_ns=user_global_ns,
797 debug=debug,
798 shell_class=shell_class,
799 on_kill=[mainquit])
800
801 # HACK: slot for banner in self; it will be passed to the mainloop
802 # method only and .run() needs it. The actual value will be set by
803 # .mainloop().
804 self._banner = None
805
806 threading.Thread.__init__(self)
807
808 def mainloop(self,sys_exit=0,banner=None):
809
810 self._banner = banner
811
812 if self.gtk.pygtk_version >= (2,4,0):
813 import gobject
814 gobject.idle_add(self.on_timer)
815 else:
816 self.gtk.idle_add(self.on_timer)
817
818 if sys.platform != 'win32':
819 try:
820 if self.gtk.gtk_version[0] >= 2:
821 self.gtk.gdk.threads_init()
822 except AttributeError:
823 pass
824 except RuntimeError:
825 error('Your pyGTK likely has not been compiled with '
826 'threading support.\n'
827 'The exception printout is below.\n'
828 'You can either rebuild pyGTK with threads, or '
829 'try using \n'
830 'matplotlib with a different backend (like Tk or WX).\n'
831 'Note that matplotlib will most likely not work in its '
832 'current state!')
833 self.IP.InteractiveTB()
834
835 self.start()
836 self.gtk.gdk.threads_enter()
837 self.gtk_mainloop()
838 self.gtk.gdk.threads_leave()
839 self.join()
840
841 def on_timer(self):
842 """Called when GTK is idle.
843
844 Must return True always, otherwise GTK stops calling it"""
845
846 update_tk(self.tk)
847 self.IP.runcode()
848 time.sleep(0.01)
849 return True
850
851
852 class IPShellWX(IPThread):
853 """Run a wx mainloop() in a separate thread.
854
855 Python commands can be passed to the thread where they will be executed.
856 This is implemented by periodically checking for passed code using a
857 GTK timeout callback."""
858
859 TIMEOUT = 100 # Millisecond interval between timeouts.
860
861 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
862 debug=1,shell_class=MTInteractiveShell):
863
864 self.IP = make_IPython(argv,user_ns=user_ns,
865 user_global_ns=user_global_ns,
866 debug=debug,
867 shell_class=shell_class,
868 on_kill=[self.wxexit])
869
870 wantedwxversion=self.IP.rc.wxversion
871 if wantedwxversion!="0":
872 try:
873 import wxversion
874 except ImportError:
875 error('The wxversion module is needed for WX version selection')
876 else:
877 try:
878 wxversion.select(wantedwxversion)
879 except:
880 self.IP.InteractiveTB()
881 error('Requested wxPython version %s could not be loaded' %
882 wantedwxversion)
883
884 import wx
885
886 threading.Thread.__init__(self)
887 self.wx = wx
888 self.wx_mainloop = hijack_wx()
889
890 # Allows us to use both Tk and GTK.
891 self.tk = get_tk()
892
893 # HACK: slot for banner in self; it will be passed to the mainloop
894 # method only and .run() needs it. The actual value will be set by
895 # .mainloop().
896 self._banner = None
897
898 self.app = None
899
900 def wxexit(self, *args):
901 if self.app is not None:
902 self.app.agent.timer.Stop()
903 self.app.ExitMainLoop()
904
905 def mainloop(self,sys_exit=0,banner=None):
906
907 self._banner = banner
908
909 self.start()
910
911 class TimerAgent(self.wx.MiniFrame):
912 wx = self.wx
913 IP = self.IP
914 tk = self.tk
915 def __init__(self, parent, interval):
916 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
917 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
918 size=(100, 100),style=style)
919 self.Show(False)
920 self.interval = interval
921 self.timerId = self.wx.NewId()
922
923 def StartWork(self):
924 self.timer = self.wx.Timer(self, self.timerId)
925 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
926 self.timer.Start(self.interval)
927
928 def OnTimer(self, event):
929 update_tk(self.tk)
930 self.IP.runcode()
931
932 class App(self.wx.App):
933 wx = self.wx
934 TIMEOUT = self.TIMEOUT
935 def OnInit(self):
936 'Create the main window and insert the custom frame'
937 self.agent = TimerAgent(None, self.TIMEOUT)
938 self.agent.Show(False)
939 self.agent.StartWork()
940 return True
941
942 self.app = App(redirect=False)
943 self.wx_mainloop(self.app)
944 self.join()
945
946
947 class IPShellQt(IPThread):
948 """Run a Qt event loop in a separate thread.
949
950 Python commands can be passed to the thread where they will be executed.
951 This is implemented by periodically checking for passed code using a
952 Qt timer / slot."""
953
954 TIMEOUT = 100 # Millisecond interval between timeouts.
955
956 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
957 debug=0, shell_class=MTInteractiveShell):
958
959 import qt
960
961 self.exec_loop = hijack_qt()
962
963 # Allows us to use both Tk and QT.
964 self.tk = get_tk()
965
966 self.IP = make_IPython(argv,
967 user_ns=user_ns,
968 user_global_ns=user_global_ns,
969 debug=debug,
970 shell_class=shell_class,
971 on_kill=[qt.qApp.exit])
972
973 # HACK: slot for banner in self; it will be passed to the mainloop
974 # method only and .run() needs it. The actual value will be set by
975 # .mainloop().
976 self._banner = None
977
978 threading.Thread.__init__(self)
979
980 def mainloop(self, sys_exit=0, banner=None):
981
982 import qt
983
984 self._banner = banner
985
986 if qt.QApplication.startingUp():
987 a = qt.QApplication(sys.argv)
988
989 self.timer = qt.QTimer()
990 qt.QObject.connect(self.timer,
991 qt.SIGNAL('timeout()'),
992 self.on_timer)
993
994 self.start()
995 self.timer.start(self.TIMEOUT, True)
996 while True:
997 if self.IP._kill: break
998 self.exec_loop()
999 self.join()
1000
1001 def on_timer(self):
1002 update_tk(self.tk)
1003 result = self.IP.runcode()
1004 self.timer.start(self.TIMEOUT, True)
1005 return result
1006
1007
1008 class IPShellQt4(IPThread):
1009 """Run a Qt event loop in a separate thread.
1010
1011 Python commands can be passed to the thread where they will be executed.
1012 This is implemented by periodically checking for passed code using a
1013 Qt timer / slot."""
1014
1015 TIMEOUT = 100 # Millisecond interval between timeouts.
1016
1017 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1018 debug=0, shell_class=MTInteractiveShell):
1019
1020 from PyQt4 import QtCore, QtGui
1021
1022 try:
1023 # present in PyQt4-4.2.1 or later
1024 QtCore.pyqtRemoveInputHook()
1025 except AttributeError:
1026 pass
1027
1028 if QtCore.PYQT_VERSION_STR == '4.3':
1029 warn('''PyQt4 version 4.3 detected.
1030 If you experience repeated threading warnings, please update PyQt4.
1031 ''')
1032
1033 self.exec_ = hijack_qt4()
1034
1035 # Allows us to use both Tk and QT.
1036 self.tk = get_tk()
1037
1038 self.IP = make_IPython(argv,
1039 user_ns=user_ns,
1040 user_global_ns=user_global_ns,
1041 debug=debug,
1042 shell_class=shell_class,
1043 on_kill=[QtGui.qApp.exit])
1044
1045 # HACK: slot for banner in self; it will be passed to the mainloop
1046 # method only and .run() needs it. The actual value will be set by
1047 # .mainloop().
1048 self._banner = None
1049
1050 threading.Thread.__init__(self)
1051
1052 def mainloop(self, sys_exit=0, banner=None):
1053
1054 from PyQt4 import QtCore, QtGui
1055
1056 self._banner = banner
1057
1058 if QtGui.QApplication.startingUp():
1059 a = QtGui.QApplication(sys.argv)
1060
1061 self.timer = QtCore.QTimer()
1062 QtCore.QObject.connect(self.timer,
1063 QtCore.SIGNAL('timeout()'),
1064 self.on_timer)
1065
1066 self.start()
1067 self.timer.start(self.TIMEOUT)
1068 while True:
1069 if self.IP._kill: break
1070 self.exec_()
1071 self.join()
1072
1073 def on_timer(self):
1074 update_tk(self.tk)
1075 result = self.IP.runcode()
1076 self.timer.start(self.TIMEOUT)
1077 return result
1078
1079
1080 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1081 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1082 def _load_pylab(user_ns):
1083 """Allow users to disable pulling all of pylab into the top-level
1084 namespace.
1085
1086 This little utility must be called AFTER the actual ipython instance is
1087 running, since only then will the options file have been fully parsed."""
1088
1089 ip = IPython.ipapi.get()
1090 if ip.options.pylab_import_all:
1091 ip.ex("from matplotlib.pylab import *")
1092 ip.IP.user_config_ns.update(ip.user_ns)
1093
1094
1095 class IPShellMatplotlib(IPShell):
1096 """Subclass IPShell with MatplotlibShell as the internal shell.
1097
1098 Single-threaded class, meant for the Tk* and FLTK* backends.
1099
1100 Having this on a separate class simplifies the external driver code."""
1101
1102 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1103 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1104 shell_class=MatplotlibShell)
1105 _load_pylab(self.IP.user_ns)
1106
1107 class IPShellMatplotlibGTK(IPShellGTK):
1108 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1109
1110 Multi-threaded class, meant for the GTK* backends."""
1111
1112 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1113 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1114 shell_class=MatplotlibMTShell)
1115 _load_pylab(self.IP.user_ns)
1116
1117 class IPShellMatplotlibWX(IPShellWX):
1118 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1119
1120 Multi-threaded class, meant for the WX* backends."""
1121
1122 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1123 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1124 shell_class=MatplotlibMTShell)
1125 _load_pylab(self.IP.user_ns)
1126
1127 class IPShellMatplotlibQt(IPShellQt):
1128 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1129
1130 Multi-threaded class, meant for the Qt* backends."""
1131
1132 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1133 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1134 shell_class=MatplotlibMTShell)
1135 _load_pylab(self.IP.user_ns)
1136
1137 class IPShellMatplotlibQt4(IPShellQt4):
1138 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1139
1140 Multi-threaded class, meant for the Qt4* backends."""
1141
1142 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1143 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1144 shell_class=MatplotlibMTShell)
1145 _load_pylab(self.IP.user_ns)
1146
1147 #-----------------------------------------------------------------------------
1148 # Factory functions to actually start the proper thread-aware shell
1149
1150 def _select_shell(argv):
1151 """Select a shell from the given argv vector.
1152
1153 This function implements the threading selection policy, allowing runtime
1154 control of the threading mode, both for general users and for matplotlib.
1155
1156 Return:
1157 Shell class to be instantiated for runtime operation.
1158 """
1159
1160 global USE_TK
1161
1162 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1163 'wthread' : IPShellMatplotlibWX,
1164 'qthread' : IPShellMatplotlibQt,
1165 'q4thread' : IPShellMatplotlibQt4,
1166 'tkthread' : IPShellMatplotlib, # Tk is built-in
1167 }
1168
1169 th_shell = {'gthread' : IPShellGTK,
1170 'wthread' : IPShellWX,
1171 'qthread' : IPShellQt,
1172 'q4thread' : IPShellQt4,
1173 'tkthread' : IPShell, # Tk is built-in
1174 }
1175
1176 backends = {'gthread' : 'GTKAgg',
1177 'wthread' : 'WXAgg',
1178 'qthread' : 'QtAgg',
1179 'q4thread' :'Qt4Agg',
1180 'tkthread' :'TkAgg',
1181 }
1182
1183 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1184 'tkthread'])
1185 user_opts = set([s.replace('-','') for s in argv[:3]])
1186 special_opts = user_opts & all_opts
1187
1188 if 'tk' in special_opts:
1189 USE_TK = True
1190 special_opts.remove('tk')
1191
1192 if 'pylab' in special_opts:
1193
1194 try:
1195 import matplotlib
1196 except ImportError:
1197 error('matplotlib could NOT be imported! Starting normal IPython.')
1198 return IPShell
1199
1200 special_opts.remove('pylab')
1201 # If there's any option left, it means the user wants to force the
1202 # threading backend, else it's auto-selected from the rc file
1203 if special_opts:
1204 th_mode = special_opts.pop()
1205 matplotlib.rcParams['backend'] = backends[th_mode]
1206 else:
1207 backend = matplotlib.rcParams['backend']
1208 if backend.startswith('GTK'):
1209 th_mode = 'gthread'
1210 elif backend.startswith('WX'):
1211 th_mode = 'wthread'
1212 elif backend.startswith('Qt4'):
1213 th_mode = 'q4thread'
1214 elif backend.startswith('Qt'):
1215 th_mode = 'qthread'
1216 else:
1217 # Any other backend, use plain Tk
1218 th_mode = 'tkthread'
1219
1220 return mpl_shell[th_mode]
1221 else:
1222 # No pylab requested, just plain threads
1223 try:
1224 th_mode = special_opts.pop()
1225 except KeyError:
1226 th_mode = 'tkthread'
1227 return th_shell[th_mode]
1228
1229
1230 # This is the one which should be called by external code.
1231 def start(user_ns = None):
1232 """Return a running shell instance, dealing with threading options.
1233
1234 This is a factory function which will instantiate the proper IPython shell
1235 based on the user's threading choice. Such a selector is needed because
1236 different GUI toolkits require different thread handling details."""
1237
1238 shell = _select_shell(sys.argv)
1239 return shell(user_ns = user_ns)
1240
42
1241 # Some aliases for backwards compatibility
1242 IPythonShell = IPShell
1243 IPythonShellEmbed = IPShellEmbed
1244 #************************ End of file <Shell.py> ***************************
@@ -1,72 +1,67 b''
1 # -*- coding: utf-8 -*-
1 #!/usr/bin/env python
2 # encoding: utf-8
2 """
3 """
3 IPython -- An enhanced Interactive Python
4 IPython.
4
5
5 One of Python's nicest features is its interactive interpreter. This allows
6 IPython is a set of tools for interactive and exploratory computing in Python.
6 very fast testing of ideas without the overhead of creating test files as is
7 typical in most programming languages. However, the interpreter supplied with
8 the standard Python distribution is fairly primitive (and IDLE isn't really
9 much better).
10
11 IPython tries to:
12
13 i - provide an efficient environment for interactive work in Python
14 programming. It tries to address what we see as shortcomings of the standard
15 Python prompt, and adds many features to make interactive work much more
16 efficient.
17
18 ii - offer a flexible framework so that it can be used as the base
19 environment for other projects and problems where Python can be the
20 underlying language. Specifically scientific environments like Mathematica,
21 IDL and Mathcad inspired its design, but similar ideas can be useful in many
22 fields. Python is a fabulous language for implementing this kind of system
23 (due to its dynamic and introspective features), and with suitable libraries
24 entire systems could be built leveraging Python's power.
25
26 iii - serve as an embeddable, ready to go interpreter for your own programs.
27
28 IPython requires Python 2.4 or newer.
29 """
7 """
30
8
31 #*****************************************************************************
9 #-----------------------------------------------------------------------------
32 # Copyright (C) 2008-2009 The IPython Development Team
10 # Copyright (C) 2008-2009 The IPython Development Team
33 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
34 #
11 #
35 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
36 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
37 #*****************************************************************************
14 #-----------------------------------------------------------------------------
15
16 #-----------------------------------------------------------------------------
17 # Imports
18 #-----------------------------------------------------------------------------
19 from __future__ import absolute_import
38
20
39 # Enforce proper version requirements
21 import os
40 import sys
22 import sys
41
23
42 if sys.version[0:3] < '2.4':
24 #-----------------------------------------------------------------------------
43 raise ImportError('Python Version 2.4 or above is required for IPython.')
25 # Setup everything
26 #-----------------------------------------------------------------------------
27
28 if sys.version[0:3] < '2.5':
29 raise ImportError('Python Version 2.5 or above is required for IPython.')
30
44
31
45 # Make it easy to import extensions - they are always directly on pythonpath.
32 # Make it easy to import extensions - they are always directly on pythonpath.
46 # Therefore, non-IPython modules can be added to Extensions directory
33 # Therefore, non-IPython modules can be added to extensions directory.
47 import os
34 # This should probably be in ipapp.py.
48 sys.path.append(os.path.dirname(__file__) + "/Extensions")
35 sys.path.append(os.path.join(os.path.dirname(__file__), "extensions"))
49
36
50 # Define what gets imported with a 'from IPython import *'
37 #-----------------------------------------------------------------------------
51 __all__ = ['ipapi','generics','ipstruct','Release','Shell']
38 # Setup the top level names
39 #-----------------------------------------------------------------------------
52
40
53 # Load __all__ in IPython namespace so that a simple 'import IPython' gives
41 from .config.loader import Config
54 # access to them via IPython.<name>
42 from .core import release
55 glob,loc = globals(),locals()
43 from .core.application import Application
56 for name in __all__:
44 from .core.ipapp import IPythonApp
57 #print 'Importing: ',name # dbg
45 from .core.embed import embed
58 __import__(name,glob,loc,[])
46 from .core.error import TryNext
47 from .core.iplib import InteractiveShell
48 from .testing import test
59
49
60 import Shell
50 from .lib import (
51 enable_wx, disable_wx,
52 enable_gtk, disable_gtk,
53 enable_qt4, disable_qt4,
54 enable_tk, disable_tk,
55 set_inputhook, clear_inputhook,
56 current_gui, spin,
57 appstart_qt4, appstart_wx,
58 appstart_gtk, appstart_tk
59 )
61
60
62 # Release data
61 # Release data
63 from IPython import Release # do it explicitly so pydoc can see it - pydoc bug
62 __author__ = ''
64 __author__ = '%s <%s>\n%s <%s>\n%s <%s>' % \
63 for author, email in release.authors.values():
65 ( Release.authors['Fernando'] + Release.authors['Janko'] + \
64 __author__ += author + ' <' + email + '>\n'
66 Release.authors['Nathan'] )
65 __license__ = release.license
67 __license__ = Release.license
66 __version__ = release.version
68 __version__ = Release.version
67 __revision__ = release.revision
69 __revision__ = Release.revision
70
71 # Namespace cleanup
72 del name,glob,loc
1 NO CONTENT: file renamed from IPython/UserConfig/__init__.py to IPython/config/default/__init__.py
NO CONTENT: file renamed from IPython/UserConfig/__init__.py to IPython/config/default/__init__.py
1 NO CONTENT: file renamed from IPython/tests/__init__.py to IPython/config/profile/__init__.py
NO CONTENT: file renamed from IPython/tests/__init__.py to IPython/config/profile/__init__.py
1 NO CONTENT: file renamed from IPython/tools/__init__.py to IPython/core/__init__.py
NO CONTENT: file renamed from IPython/tools/__init__.py to IPython/core/__init__.py
@@ -44,7 +44,6 b' its input.'
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47
48 """
47 """
49
48
50 #*****************************************************************************
49 #*****************************************************************************
@@ -54,39 +53,82 b' used, and this module (and the readline module) are silently inactive.'
54 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
55 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
56 #
55 #
56 # Copyright (C) 2008-2010 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64
64
65 #-----------------------------------------------------------------------------
66 # Imports
67 #-----------------------------------------------------------------------------
68
65 import __builtin__
69 import __builtin__
66 import __main__
70 import __main__
67 import glob
71 import glob
72 import inspect
73 import itertools
68 import keyword
74 import keyword
69 import os
75 import os
70 import re
76 import re
71 import shlex
77 import shlex
72 import sys
78 import sys
73 import IPython.rlineimpl as readline
74 import itertools
75 from IPython.ipstruct import Struct
76 from IPython import ipapi
77 from IPython import generics
78 import types
79
79
80 # Python 2.4 offers sets as a builtin
80 from IPython.core.error import TryNext
81 try:
81 from IPython.core.prefilter import ESC_MAGIC
82 set()
82 from IPython.utils import generics
83 except NameError:
83 from IPython.utils.frame import debugx
84 from sets import Set as set
84 from IPython.utils.dir2 import dir2
85 import IPython.utils.rlineimpl as readline
85
86
86 from IPython.genutils import debugx, dir2
87 #-----------------------------------------------------------------------------
88 # Globals
89 #-----------------------------------------------------------------------------
87
90
91 # Public API
88 __all__ = ['Completer','IPCompleter']
92 __all__ = ['Completer','IPCompleter']
89
93
94 if sys.platform == 'win32':
95 PROTECTABLES = ' '
96 else:
97 PROTECTABLES = ' ()'
98
99 #-----------------------------------------------------------------------------
100 # Main functions and classes
101 #-----------------------------------------------------------------------------
102
103 def protect_filename(s):
104 """Escape a string to protect certain characters."""
105
106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
107 for ch in s])
108
109
110 def single_dir_expand(matches):
111 "Recursively expand match lists containing a single dir."
112
113 if len(matches) == 1 and os.path.isdir(matches[0]):
114 # Takes care of links to directories also. Use '/'
115 # explicitly, even under Windows, so that name completions
116 # don't end up escaped.
117 d = matches[0]
118 if d[-1] in ['/','\\']:
119 d = d[:-1]
120
121 subdirs = os.listdir(d)
122 if subdirs:
123 matches = [ (d + '/' + p) for p in subdirs]
124 return single_dir_expand(matches)
125 else:
126 return matches
127 else:
128 return matches
129
130 class Bunch: pass
131
90 class Completer:
132 class Completer:
91 def __init__(self,namespace=None,global_namespace=None):
133 def __init__(self,namespace=None,global_namespace=None):
92 """Create a new completer for the command line.
134 """Create a new completer for the command line.
@@ -149,6 +191,7 b' class Completer:'
149 defined in self.namespace or self.global_namespace that match.
191 defined in self.namespace or self.global_namespace that match.
150
192
151 """
193 """
194 #print 'Completer->global_matches, txt=%r' % text # dbg
152 matches = []
195 matches = []
153 match_append = matches.append
196 match_append = matches.append
154 n = len(text)
197 n = len(text)
@@ -174,8 +217,8 b' class Completer:'
174 with a __getattr__ hook is evaluated.
217 with a __getattr__ hook is evaluated.
175
218
176 """
219 """
177 import re
178
220
221 #print 'Completer->attr_matches, txt=%r' % text # dbg
179 # Another option, seems to work great. Catches things like ''.<tab>
222 # Another option, seems to work great. Catches things like ''.<tab>
180 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
223 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
181
224
@@ -195,13 +238,14 b' class Completer:'
195
238
196 try:
239 try:
197 words = generics.complete_object(obj, words)
240 words = generics.complete_object(obj, words)
198 except ipapi.TryNext:
241 except TryNext:
199 pass
242 pass
200 # Build match list to return
243 # Build match list to return
201 n = len(attr)
244 n = len(attr)
202 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
245 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
203 return res
246 return res
204
247
248
205 class IPCompleter(Completer):
249 class IPCompleter(Completer):
206 """Extension of the completer class with IPython-specific features"""
250 """Extension of the completer class with IPython-specific features"""
207
251
@@ -232,8 +276,8 b' class IPCompleter(Completer):'
232 to complete. """
276 to complete. """
233
277
234 Completer.__init__(self,namespace,global_namespace)
278 Completer.__init__(self,namespace,global_namespace)
235 self.magic_prefix = shell.name+'.magic_'
279
236 self.magic_escape = shell.ESC_MAGIC
280 self.magic_escape = ESC_MAGIC
237 self.readline = readline
281 self.readline = readline
238 delims = self.readline.get_completer_delims()
282 delims = self.readline.get_completer_delims()
239 delims = delims.replace(self.magic_escape,'')
283 delims = delims.replace(self.magic_escape,'')
@@ -241,7 +285,8 b' class IPCompleter(Completer):'
241 self.get_line_buffer = self.readline.get_line_buffer
285 self.get_line_buffer = self.readline.get_line_buffer
242 self.get_endidx = self.readline.get_endidx
286 self.get_endidx = self.readline.get_endidx
243 self.omit__names = omit__names
287 self.omit__names = omit__names
244 self.merge_completions = shell.rc.readline_merge_completions
288 self.merge_completions = shell.readline_merge_completions
289 self.shell = shell.shell
245 if alias_table is None:
290 if alias_table is None:
246 alias_table = {}
291 alias_table = {}
247 self.alias_table = alias_table
292 self.alias_table = alias_table
@@ -260,11 +305,13 b' class IPCompleter(Completer):'
260 self.clean_glob = self._clean_glob_win32
305 self.clean_glob = self._clean_glob_win32
261 else:
306 else:
262 self.clean_glob = self._clean_glob
307 self.clean_glob = self._clean_glob
308
309 # All active matcher routines for completion
263 self.matchers = [self.python_matches,
310 self.matchers = [self.python_matches,
264 self.file_matches,
311 self.file_matches,
312 self.magic_matches,
265 self.alias_matches,
313 self.alias_matches,
266 self.python_func_kw_matches]
314 self.python_func_kw_matches]
267
268
315
269 # Code contributed by Alex Schmolck, for ipython/emacs integration
316 # Code contributed by Alex Schmolck, for ipython/emacs integration
270 def all_completions(self, text):
317 def all_completions(self, text):
@@ -275,9 +322,8 b' class IPCompleter(Completer):'
275 try:
322 try:
276 for i in xrange(sys.maxint):
323 for i in xrange(sys.maxint):
277 res = self.complete(text, i)
324 res = self.complete(text, i)
278
325 if not res:
279 if not res: break
326 break
280
281 comp_append(res)
327 comp_append(res)
282 #XXX workaround for ``notDefined.<tab>``
328 #XXX workaround for ``notDefined.<tab>``
283 except NameError:
329 except NameError:
@@ -313,41 +359,12 b' class IPCompleter(Completer):'
313 # don't want to treat as delimiters in filename matching
359 # don't want to treat as delimiters in filename matching
314 # when escaped with backslash
360 # when escaped with backslash
315
361
316 if sys.platform == 'win32':
317 protectables = ' '
318 else:
319 protectables = ' ()'
320
321 if text.startswith('!'):
362 if text.startswith('!'):
322 text = text[1:]
363 text = text[1:]
323 text_prefix = '!'
364 text_prefix = '!'
324 else:
365 else:
325 text_prefix = ''
366 text_prefix = ''
326
367
327 def protect_filename(s):
328 return "".join([(ch in protectables and '\\' + ch or ch)
329 for ch in s])
330
331 def single_dir_expand(matches):
332 "Recursively expand match lists containing a single dir."
333
334 if len(matches) == 1 and os.path.isdir(matches[0]):
335 # Takes care of links to directories also. Use '/'
336 # explicitly, even under Windows, so that name completions
337 # don't end up escaped.
338 d = matches[0]
339 if d[-1] in ['/','\\']:
340 d = d[:-1]
341
342 subdirs = os.listdir(d)
343 if subdirs:
344 matches = [ (d + '/' + p) for p in subdirs]
345 return single_dir_expand(matches)
346 else:
347 return matches
348 else:
349 return matches
350
351 lbuf = self.lbuf
368 lbuf = self.lbuf
352 open_quotes = 0 # track strings with open quotes
369 open_quotes = 0 # track strings with open quotes
353 try:
370 try:
@@ -399,13 +416,24 b' class IPCompleter(Completer):'
399 #print 'mm',matches # dbg
416 #print 'mm',matches # dbg
400 return single_dir_expand(matches)
417 return single_dir_expand(matches)
401
418
419 def magic_matches(self, text):
420 """Match magics"""
421 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
422 # Get all shell magics now rather than statically, so magics loaded at
423 # runtime show up too
424 magics = self.shell.lsmagic()
425 pre = self.magic_escape
426 baretext = text.lstrip(pre)
427 return [ pre+m for m in magics if m.startswith(baretext)]
428
402 def alias_matches(self, text):
429 def alias_matches(self, text):
403 """Match internal system aliases"""
430 """Match internal system aliases"""
404 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
431 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
405
432
406 # if we are not in the first 'item', alias matching
433 # if we are not in the first 'item', alias matching
407 # doesn't make sense - unless we are starting with 'sudo' command.
434 # doesn't make sense - unless we are starting with 'sudo' command.
408 if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'):
435 if ' ' in self.lbuf.lstrip() and \
436 not self.lbuf.lstrip().startswith('sudo'):
409 return []
437 return []
410 text = os.path.expanduser(text)
438 text = os.path.expanduser(text)
411 aliases = self.alias_table.keys()
439 aliases = self.alias_table.keys()
@@ -417,7 +445,7 b' class IPCompleter(Completer):'
417 def python_matches(self,text):
445 def python_matches(self,text):
418 """Match attributes or global python names"""
446 """Match attributes or global python names"""
419
447
420 #print 'Completer->python_matches, txt=<%s>' % text # dbg
448 #print 'Completer->python_matches, txt=%r' % text # dbg
421 if "." in text:
449 if "." in text:
422 try:
450 try:
423 matches = self.attr_matches(text)
451 matches = self.attr_matches(text)
@@ -436,11 +464,7 b' class IPCompleter(Completer):'
436 matches = []
464 matches = []
437 else:
465 else:
438 matches = self.global_matches(text)
466 matches = self.global_matches(text)
439 # this is so completion finds magics when automagic is on:
467
440 if (matches == [] and
441 not text.startswith(os.sep) and
442 not ' ' in self.lbuf):
443 matches = self.attr_matches(self.magic_prefix+text)
444 return matches
468 return matches
445
469
446 def _default_arguments(self, obj):
470 def _default_arguments(self, obj):
@@ -511,9 +535,11 b' class IPCompleter(Completer):'
511 callableMatches = self.attr_matches('.'.join(ids[::-1]))
535 callableMatches = self.attr_matches('.'.join(ids[::-1]))
512 argMatches = []
536 argMatches = []
513 for callableMatch in callableMatches:
537 for callableMatch in callableMatches:
514 try: namedArgs = self._default_arguments(eval(callableMatch,
538 try:
539 namedArgs = self._default_arguments(eval(callableMatch,
515 self.namespace))
540 self.namespace))
516 except: continue
541 except:
542 continue
517 for namedArg in namedArgs:
543 for namedArg in namedArgs:
518 if namedArg.startswith(text):
544 if namedArg.startswith(text):
519 argMatches.append("%s=" %namedArg)
545 argMatches.append("%s=" %namedArg)
@@ -525,7 +551,7 b' class IPCompleter(Completer):'
525 if not line.strip():
551 if not line.strip():
526 return None
552 return None
527
553
528 event = Struct()
554 event = Bunch()
529 event.line = line
555 event.line = line
530 event.symbol = text
556 event.symbol = text
531 cmd = line.split(None,1)[0]
557 cmd = line.split(None,1)[0]
@@ -537,11 +563,9 b' class IPCompleter(Completer):'
537 try_magic = self.custom_completers.s_matches(
563 try_magic = self.custom_completers.s_matches(
538 self.magic_escape + cmd)
564 self.magic_escape + cmd)
539 else:
565 else:
540 try_magic = []
566 try_magic = []
541
542
567
543 for c in itertools.chain(
568 for c in itertools.chain(self.custom_completers.s_matches(cmd),
544 self.custom_completers.s_matches(cmd),
545 try_magic,
569 try_magic,
546 self.custom_completers.flat_matches(self.lbuf)):
570 self.custom_completers.flat_matches(self.lbuf)):
547 #print "try",c # dbg
571 #print "try",c # dbg
@@ -552,8 +576,9 b' class IPCompleter(Completer):'
552 if withcase:
576 if withcase:
553 return withcase
577 return withcase
554 # if none, then case insensitive ones are ok too
578 # if none, then case insensitive ones are ok too
555 return [r for r in res if r.lower().startswith(text.lower())]
579 text_low = text.lower()
556 except ipapi.TryNext:
580 return [r for r in res if r.lower().startswith(text_low)]
581 except TryNext:
557 pass
582 pass
558
583
559 return None
584 return None
@@ -595,14 +620,11 b' class IPCompleter(Completer):'
595 return None
620 return None
596
621
597 magic_escape = self.magic_escape
622 magic_escape = self.magic_escape
598 magic_prefix = self.magic_prefix
599
623
600 self.lbuf = self.full_lbuf[:self.get_endidx()]
624 self.lbuf = self.full_lbuf[:self.get_endidx()]
601
625
602 try:
626 try:
603 if text.startswith(magic_escape):
627 if text.startswith('~'):
604 text = text.replace(magic_escape,magic_prefix)
605 elif text.startswith('~'):
606 text = os.path.expanduser(text)
628 text = os.path.expanduser(text)
607 if state == 0:
629 if state == 0:
608 custom_res = self.dispatch_custom_completer(text)
630 custom_res = self.dispatch_custom_completer(text)
@@ -622,17 +644,14 b' class IPCompleter(Completer):'
622 self.matches = matcher(text)
644 self.matches = matcher(text)
623 if self.matches:
645 if self.matches:
624 break
646 break
625 def uniq(alist):
647 self.matches = list(set(self.matches))
626 set = {}
627 return [set.setdefault(e,e) for e in alist if e not in set]
628 self.matches = uniq(self.matches)
629 try:
648 try:
630 ret = self.matches[state].replace(magic_prefix,magic_escape)
649 #print "MATCH: %r" % self.matches[state] # dbg
631 return ret
650 return self.matches[state]
632 except IndexError:
651 except IndexError:
633 return None
652 return None
634 except:
653 except:
635 #from IPython.ultraTB import AutoFormattedTB; # dbg
654 #from IPython.core.ultratb import AutoFormattedTB; # dbg
636 #tb=AutoFormattedTB('Verbose');tb() #dbg
655 #tb=AutoFormattedTB('Verbose');tb() #dbg
637
656
638 # If completion fails, don't annoy the user.
657 # If completion fails, don't annoy the user.
@@ -26,14 +26,14 b' http://www.python.org/2.2.3/license.html"""'
26 #*****************************************************************************
26 #*****************************************************************************
27
27
28 import bdb
28 import bdb
29 import cmd
30 import linecache
29 import linecache
31 import os
32 import sys
30 import sys
33
31
34 from IPython import PyColorize, ColorANSI, ipapi
32 from IPython.utils import PyColorize
35 from IPython.genutils import Term
33 from IPython.core import ipapi
36 from IPython.excolors import exception_colors
34 from IPython.utils import coloransi
35 from IPython.utils.io import Term
36 from IPython.core.excolors import exception_colors
37
37
38 # See if we can use pydb.
38 # See if we can use pydb.
39 has_pydb = False
39 has_pydb = False
@@ -68,6 +68,7 b' def BdbQuit_excepthook(et,ev,tb):'
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
68 def BdbQuit_IPython_excepthook(self,et,ev,tb):
69 print 'Exiting Debugger.'
69 print 'Exiting Debugger.'
70
70
71
71 class Tracer(object):
72 class Tracer(object):
72 """Class for local debugging, similar to pdb.set_trace.
73 """Class for local debugging, similar to pdb.set_trace.
73
74
@@ -93,7 +94,7 b' class Tracer(object):'
93
94
94 Usage example:
95 Usage example:
95
96
96 from IPython.Debugger import Tracer; debug_here = Tracer()
97 from IPython.core.debugger import Tracer; debug_here = Tracer()
97
98
98 ... later in your code
99 ... later in your code
99 debug_here() # -> will open up the debugger at that point.
100 debug_here() # -> will open up the debugger at that point.
@@ -103,26 +104,23 b' class Tracer(object):'
103 from the Python standard library for usage details.
104 from the Python standard library for usage details.
104 """
105 """
105
106
106 global __IPYTHON__
107 try:
107 try:
108 __IPYTHON__
108 ip = ipapi.get()
109 except NameError:
109 except:
110 # Outside of ipython, we set our own exception hook manually
110 # Outside of ipython, we set our own exception hook manually
111 __IPYTHON__ = ipapi.get(True,False)
112 BdbQuit_excepthook.excepthook_ori = sys.excepthook
111 BdbQuit_excepthook.excepthook_ori = sys.excepthook
113 sys.excepthook = BdbQuit_excepthook
112 sys.excepthook = BdbQuit_excepthook
114 def_colors = 'NoColor'
113 def_colors = 'NoColor'
115 try:
114 try:
116 # Limited tab completion support
115 # Limited tab completion support
117 import rlcompleter,readline
116 import readline
118 readline.parse_and_bind('tab: complete')
117 readline.parse_and_bind('tab: complete')
119 except ImportError:
118 except ImportError:
120 pass
119 pass
121 else:
120 else:
122 # In ipython, we use its custom exception handler mechanism
121 # In ipython, we use its custom exception handler mechanism
123 ip = ipapi.get()
122 def_colors = ip.colors
124 def_colors = ip.options.colors
123 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
125 ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook)
126
124
127 if colors is None:
125 if colors is None:
128 colors = def_colors
126 colors = def_colors
@@ -136,6 +134,7 b' class Tracer(object):'
136
134
137 self.debugger.set_trace(sys._getframe().f_back)
135 self.debugger.set_trace(sys._getframe().f_back)
138
136
137
139 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
138 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
140 """Make new_fn have old_fn's doc string. This is particularly useful
139 """Make new_fn have old_fn's doc string. This is particularly useful
141 for the do_... commands that hook into the help system.
140 for the do_... commands that hook into the help system.
@@ -147,6 +146,7 b' def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):'
147 wrapper.__doc__ = old_fn.__doc__ + additional_text
146 wrapper.__doc__ = old_fn.__doc__ + additional_text
148 return wrapper
147 return wrapper
149
148
149
150 def _file_lines(fname):
150 def _file_lines(fname):
151 """Return the contents of a named file as a list of lines.
151 """Return the contents of a named file as a list of lines.
152
152
@@ -162,143 +162,98 b' def _file_lines(fname):'
162 outfile.close()
162 outfile.close()
163 return out
163 return out
164
164
165
165 class Pdb(OldPdb):
166 class Pdb(OldPdb):
166 """Modified Pdb class, does not load readline."""
167 """Modified Pdb class, does not load readline."""
167
168
168 if sys.version[:3] >= '2.5' or has_pydb:
169 def __init__(self,color_scheme='NoColor',completekey=None,
169 def __init__(self,color_scheme='NoColor',completekey=None,
170 stdin=None, stdout=None):
170 stdin=None, stdout=None):
171
171
172 # Parent constructor:
172 # Parent constructor:
173 if has_pydb and completekey is None:
173 if has_pydb and completekey is None:
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
174 OldPdb.__init__(self,stdin=stdin,stdout=Term.cout)
175 else:
175 else:
176 OldPdb.__init__(self,completekey,stdin,stdout)
176 OldPdb.__init__(self,completekey,stdin,stdout)
177
178 self.prompt = prompt # The default prompt is '(Pdb)'
179
177
180 # IPython changes...
178 self.prompt = prompt # The default prompt is '(Pdb)'
181 self.is_pydb = has_pydb
179
182
180 # IPython changes...
183 if self.is_pydb:
181 self.is_pydb = has_pydb
184
185 # iplib.py's ipalias seems to want pdb's checkline
186 # which located in pydb.fn
187 import pydb.fns
188 self.checkline = lambda filename, lineno: \
189 pydb.fns.checkline(self, filename, lineno)
190
191 self.curframe = None
192 self.do_restart = self.new_do_restart
193
194 self.old_all_completions = __IPYTHON__.Completer.all_completions
195 __IPYTHON__.Completer.all_completions=self.all_completions
196
197 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
198 OldPdb.do_list)
199 self.do_l = self.do_list
200 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
201 OldPdb.do_frame)
202
203 self.aliases = {}
204
205 # Create color table: we copy the default one from the traceback
206 # module and add a few attributes needed for debugging
207 self.color_scheme_table = exception_colors()
208
182
209 # shorthands
183 self.shell = ipapi.get()
210 C = ColorANSI.TermColors
211 cst = self.color_scheme_table
212
184
213 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
185 if self.is_pydb:
214 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
215
186
216 cst['Linux'].colors.breakpoint_enabled = C.LightRed
187 # iplib.py's ipalias seems to want pdb's checkline
217 cst['Linux'].colors.breakpoint_disabled = C.Red
188 # which located in pydb.fn
189 import pydb.fns
190 self.checkline = lambda filename, lineno: \
191 pydb.fns.checkline(self, filename, lineno)
218
192
219 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
193 self.curframe = None
220 cst['LightBG'].colors.breakpoint_disabled = C.Red
194 self.do_restart = self.new_do_restart
221
195
222 self.set_colors(color_scheme)
196 self.old_all_completions = self.shell.Completer.all_completions
197 self.shell.Completer.all_completions=self.all_completions
223
198
224 # Add a python parser so we can syntax highlight source while
199 self.do_list = decorate_fn_with_doc(self.list_command_pydb,
225 # debugging.
200 OldPdb.do_list)
226 self.parser = PyColorize.Parser()
201 self.do_l = self.do_list
202 self.do_frame = decorate_fn_with_doc(self.new_do_frame,
203 OldPdb.do_frame)
227
204
205 self.aliases = {}
228
206
229 else:
207 # Create color table: we copy the default one from the traceback
230 # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor,
208 # module and add a few attributes needed for debugging
231 # because it binds readline and breaks tab-completion. This means we
209 self.color_scheme_table = exception_colors()
232 # have to COPY the constructor here.
233 def __init__(self,color_scheme='NoColor'):
234 bdb.Bdb.__init__(self)
235 cmd.Cmd.__init__(self,completekey=None) # don't load readline
236 self.prompt = 'ipdb> ' # The default prompt is '(Pdb)'
237 self.aliases = {}
238
239 # These two lines are part of the py2.4 constructor, let's put them
240 # unconditionally here as they won't cause any problems in 2.3.
241 self.mainpyfile = ''
242 self._wait_for_mainpyfile = 0
243
244 # Read $HOME/.pdbrc and ./.pdbrc
245 try:
246 self.rcLines = _file_lines(os.path.join(os.environ['HOME'],
247 ".pdbrc"))
248 except KeyError:
249 self.rcLines = []
250 self.rcLines.extend(_file_lines(".pdbrc"))
251
210
252 # Create color table: we copy the default one from the traceback
211 # shorthands
253 # module and add a few attributes needed for debugging
212 C = coloransi.TermColors
254 self.color_scheme_table = exception_colors()
213 cst = self.color_scheme_table
255
214
256 # shorthands
215 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
257 C = ColorANSI.TermColors
216 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
258 cst = self.color_scheme_table
259
217
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
218 cst['Linux'].colors.breakpoint_enabled = C.LightRed
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
219 cst['Linux'].colors.breakpoint_disabled = C.Red
262
220
263 cst['Linux'].colors.breakpoint_enabled = C.LightRed
221 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
264 cst['Linux'].colors.breakpoint_disabled = C.Red
222 cst['LightBG'].colors.breakpoint_disabled = C.Red
265
223
266 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
224 self.set_colors(color_scheme)
267 cst['LightBG'].colors.breakpoint_disabled = C.Red
268
225
269 self.set_colors(color_scheme)
226 # Add a python parser so we can syntax highlight source while
227 # debugging.
228 self.parser = PyColorize.Parser()
270
229
271 # Add a python parser so we can syntax highlight source while
272 # debugging.
273 self.parser = PyColorize.Parser()
274
275 def set_colors(self, scheme):
230 def set_colors(self, scheme):
276 """Shorthand access to the color table scheme selector method."""
231 """Shorthand access to the color table scheme selector method."""
277 self.color_scheme_table.set_active_scheme(scheme)
232 self.color_scheme_table.set_active_scheme(scheme)
278
233
279 def interaction(self, frame, traceback):
234 def interaction(self, frame, traceback):
280 __IPYTHON__.set_completer_frame(frame)
235 self.shell.set_completer_frame(frame)
281 OldPdb.interaction(self, frame, traceback)
236 OldPdb.interaction(self, frame, traceback)
282
237
283 def new_do_up(self, arg):
238 def new_do_up(self, arg):
284 OldPdb.do_up(self, arg)
239 OldPdb.do_up(self, arg)
285 __IPYTHON__.set_completer_frame(self.curframe)
240 self.shell.set_completer_frame(self.curframe)
286 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
241 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
287
242
288 def new_do_down(self, arg):
243 def new_do_down(self, arg):
289 OldPdb.do_down(self, arg)
244 OldPdb.do_down(self, arg)
290 __IPYTHON__.set_completer_frame(self.curframe)
245 self.shell.set_completer_frame(self.curframe)
291
246
292 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
247 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
293
248
294 def new_do_frame(self, arg):
249 def new_do_frame(self, arg):
295 OldPdb.do_frame(self, arg)
250 OldPdb.do_frame(self, arg)
296 __IPYTHON__.set_completer_frame(self.curframe)
251 self.shell.set_completer_frame(self.curframe)
297
252
298 def new_do_quit(self, arg):
253 def new_do_quit(self, arg):
299
254
300 if hasattr(self, 'old_all_completions'):
255 if hasattr(self, 'old_all_completions'):
301 __IPYTHON__.Completer.all_completions=self.old_all_completions
256 self.shell.Completer.all_completions=self.old_all_completions
302
257
303
258
304 return OldPdb.do_quit(self, arg)
259 return OldPdb.do_quit(self, arg)
@@ -312,7 +267,7 b' class Pdb(OldPdb):'
312 return self.do_quit(arg)
267 return self.do_quit(arg)
313
268
314 def postloop(self):
269 def postloop(self):
315 __IPYTHON__.set_completer_frame(None)
270 self.shell.set_completer_frame(None)
316
271
317 def print_stack_trace(self):
272 def print_stack_trace(self):
318 try:
273 try:
@@ -329,7 +284,7 b' class Pdb(OldPdb):'
329 # vds: >>
284 # vds: >>
330 frame, lineno = frame_lineno
285 frame, lineno = frame_lineno
331 filename = frame.f_code.co_filename
286 filename = frame.f_code.co_filename
332 __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0)
287 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
333 # vds: <<
288 # vds: <<
334
289
335 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
290 def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3):
@@ -498,7 +453,7 b' class Pdb(OldPdb):'
498 # vds: >>
453 # vds: >>
499 lineno = first
454 lineno = first
500 filename = self.curframe.f_code.co_filename
455 filename = self.curframe.f_code.co_filename
501 __IPYTHON__.hooks.synchronize_with_editor(filename, lineno, 0)
456 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
502 # vds: <<
457 # vds: <<
503
458
504 do_l = do_list
459 do_l = do_list
@@ -507,16 +462,49 b' class Pdb(OldPdb):'
507 """The debugger interface to magic_pdef"""
462 """The debugger interface to magic_pdef"""
508 namespaces = [('Locals', self.curframe.f_locals),
463 namespaces = [('Locals', self.curframe.f_locals),
509 ('Globals', self.curframe.f_globals)]
464 ('Globals', self.curframe.f_globals)]
510 __IPYTHON__.magic_pdef(arg, namespaces=namespaces)
465 self.shell.magic_pdef(arg, namespaces=namespaces)
511
466
512 def do_pdoc(self, arg):
467 def do_pdoc(self, arg):
513 """The debugger interface to magic_pdoc"""
468 """The debugger interface to magic_pdoc"""
514 namespaces = [('Locals', self.curframe.f_locals),
469 namespaces = [('Locals', self.curframe.f_locals),
515 ('Globals', self.curframe.f_globals)]
470 ('Globals', self.curframe.f_globals)]
516 __IPYTHON__.magic_pdoc(arg, namespaces=namespaces)
471 self.shell.magic_pdoc(arg, namespaces=namespaces)
517
472
518 def do_pinfo(self, arg):
473 def do_pinfo(self, arg):
519 """The debugger equivalant of ?obj"""
474 """The debugger equivalant of ?obj"""
520 namespaces = [('Locals', self.curframe.f_locals),
475 namespaces = [('Locals', self.curframe.f_locals),
521 ('Globals', self.curframe.f_globals)]
476 ('Globals', self.curframe.f_globals)]
522 __IPYTHON__.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
477 self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces)
478
479 def checkline(self, filename, lineno):
480 """Check whether specified line seems to be executable.
481
482 Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
483 line or EOF). Warning: testing is not comprehensive.
484 """
485 #######################################################################
486 # XXX Hack! Use python-2.5 compatible code for this call, because with
487 # all of our changes, we've drifted from the pdb api in 2.6. For now,
488 # changing:
489 #
490 #line = linecache.getline(filename, lineno, self.curframe.f_globals)
491 # to:
492 #
493 line = linecache.getline(filename, lineno)
494 #
495 # does the trick. But in reality, we need to fix this by reconciling
496 # our updates with the new Pdb APIs in Python 2.6.
497 #
498 # End hack. The rest of this method is copied verbatim from 2.6 pdb.py
499 #######################################################################
500
501 if not line:
502 print >>self.stdout, 'End of file'
503 return 0
504 line = line.strip()
505 # Don't allow setting breakpoint at a blank line
506 if (not line or (line[0] == '#') or
507 (line[:3] == '"""') or line[:3] == "'''"):
508 print >>self.stdout, '*** Blank or comment'
509 return 0
510 return lineno
@@ -10,9 +10,7 b' Color schemes for exception handling code in IPython.'
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 #****************************************************************************
13 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
14 # Required modules
15 from IPython.ColorANSI import ColorSchemeTable, TermColors, ColorScheme
16
14
17 def exception_colors():
15 def exception_colors():
18 """Return a color table with fields for exception reporting.
16 """Return a color table with fields for exception reporting.
@@ -34,9 +32,9 b' def exception_colors():'
34 >>> ec.active_scheme_name
32 >>> ec.active_scheme_name
35 'NoColor'
33 'NoColor'
36 >>> ec.active_colors.keys()
34 >>> ec.active_colors.keys()
37 ['em', 'caret', '__allownew', 'name', 'val', 'vName', 'Normal', 'normalEm',
35 ['em', 'filenameEm', 'excName', 'valEm', 'nameEm', 'line', 'topline',
38 'filename', 'linenoEm', 'excName', 'lineno', 'valEm', 'filenameEm',
36 'name', 'caret', 'val', 'vName', 'Normal', 'filename', 'linenoEm',
39 'nameEm', 'line', 'topline']
37 'lineno', 'normalEm']
40 """
38 """
41
39
42 ex_colors = ColorSchemeTable()
40 ex_colors = ColorSchemeTable()
@@ -15,6 +15,37 b' sessions.'
15
15
16 import types
16 import types
17
17
18 def init_fakemod_dict(fm,adict=None):
19 """Initialize a FakeModule instance __dict__.
20
21 Kept as a standalone function and not a method so the FakeModule API can
22 remain basically empty.
23
24 This should be considered for private IPython use, used in managing
25 namespaces for %run.
26
27 Parameters
28 ----------
29
30 fm : FakeModule instance
31
32 adict : dict, optional
33 """
34
35 dct = {}
36 # It seems pydoc (and perhaps others) needs any module instance to
37 # implement a __nonzero__ method, so we add it if missing:
38 dct.setdefault('__nonzero__',lambda : True)
39 dct.setdefault('__file__',__file__)
40
41 if adict is not None:
42 dct.update(adict)
43
44 # Hard assignment of the object's __dict__. This is nasty but deliberate.
45 fm.__dict__.clear()
46 fm.__dict__.update(dct)
47
48
18 class FakeModule(types.ModuleType):
49 class FakeModule(types.ModuleType):
19 """Simple class with attribute access to fake a module.
50 """Simple class with attribute access to fake a module.
20
51
@@ -29,14 +60,7 b' class FakeModule(types.ModuleType):'
29
60
30 # tmp to force __dict__ instance creation, else self.__dict__ fails
61 # tmp to force __dict__ instance creation, else self.__dict__ fails
31 self.__iptmp = None
62 self.__iptmp = None
32
33 # It seems pydoc (and perhaps others) needs any module instance to
34 # implement a __nonzero__ method, so we add it if missing:
35 self.__dict__.setdefault('__nonzero__',lambda : True)
36 self.__dict__.setdefault('__file__',__file__)
37
38 # cleanup our temp trick
63 # cleanup our temp trick
39 del self.__iptmp
64 del self.__iptmp
40
65 # Now, initialize the actual data in the instance dict.
41 if adict is not None:
66 init_fakemod_dict(self,adict)
42 self.__dict__.update(adict)
@@ -5,9 +5,9 b''
5 import fnmatch
5 import fnmatch
6 import os
6 import os
7
7
8 # IPython imports
8 from IPython.utils.io import Term, ask_yes_no
9 from IPython.genutils import Term, ask_yes_no, warn
9 from IPython.utils.warn import warn
10 import IPython.ipapi
10 from IPython.core import ipapi
11
11
12 def magic_history(self, parameter_s = ''):
12 def magic_history(self, parameter_s = ''):
13 """Print input history (_i<n> variables), with most recent last.
13 """Print input history (_i<n> variables), with most recent last.
@@ -15,20 +15,25 b" def magic_history(self, parameter_s = ''):"
15 %history -> print at most 40 inputs (some may be multi-line)\\
15 %history -> print at most 40 inputs (some may be multi-line)\\
16 %history n -> print at most n inputs\\
16 %history n -> print at most n inputs\\
17 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
17 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
18
19 Each input's number <n> is shown, and is accessible as the
20 automatically generated variable _i<n>. Multi-line statements are
21 printed starting at a new line for easy copy/paste.
22
23
18
24 Options:
19 By default, input history is printed without line numbers so it can be
20 directly pasted into an editor.
25
21
26 -n: do NOT print line numbers. This is useful if you want to get a
22 With -n, each input's number <n> is shown, and is accessible as the
27 printout of many lines which can be directly pasted into a text
23 automatically generated variable _i<n> as well as In[<n>]. Multi-line
28 editor.
24 statements are printed starting at a new line for easy copy/paste.
25
26 Options:
29
27
28 -n: print line numbers for each input.
30 This feature is only available if numbered prompts are in use.
29 This feature is only available if numbered prompts are in use.
31
30
31 -o: also print outputs for each input.
32
33 -p: print classic '>>>' python prompts before each input. This is useful
34 for making documentation, and in conjunction with -o, for producing
35 doctest-ready output.
36
32 -t: (default) print the 'translated' history, as IPython understands it.
37 -t: (default) print the 'translated' history, as IPython understands it.
33 IPython filters your input and converts it all into valid Python source
38 IPython filters your input and converts it all into valid Python source
34 before executing it (things like magics or aliases are turned into
39 before executing it (things like magics or aliases are turned into
@@ -48,12 +53,10 b" def magic_history(self, parameter_s = ''):"
48 confirmation first if it already exists.
53 confirmation first if it already exists.
49 """
54 """
50
55
51 ip = self.api
56 if not self.outputcache.do_full_cache:
52 shell = self.shell
53 if not shell.outputcache.do_full_cache:
54 print 'This feature is only available if numbered prompts are in use.'
57 print 'This feature is only available if numbered prompts are in use.'
55 return
58 return
56 opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list')
59 opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list')
57
60
58 # Check if output to specific file was requested.
61 # Check if output to specific file was requested.
59 try:
62 try:
@@ -72,50 +75,54 b" def magic_history(self, parameter_s = ''):"
72 close_at_end = True
75 close_at_end = True
73
76
74 if 't' in opts:
77 if 't' in opts:
75 input_hist = shell.input_hist
78 input_hist = self.input_hist
76 elif 'r' in opts:
79 elif 'r' in opts:
77 input_hist = shell.input_hist_raw
80 input_hist = self.input_hist_raw
78 else:
81 else:
79 input_hist = shell.input_hist
82 input_hist = self.input_hist
80
83
81 default_length = 40
84 default_length = 40
82 pattern = None
85 pattern = None
83 if 'g' in opts:
86 if 'g' in opts:
84 init = 1
87 init = 1
85 final = len(input_hist)
88 final = len(input_hist)
86 parts = parameter_s.split(None,1)
89 parts = parameter_s.split(None, 1)
87 if len(parts) == 1:
90 if len(parts) == 1:
88 parts += '*'
91 parts += '*'
89 head, pattern = parts
92 head, pattern = parts
90 pattern = "*" + pattern + "*"
93 pattern = "*" + pattern + "*"
91 elif len(args) == 0:
94 elif len(args) == 0:
92 final = len(input_hist)
95 final = len(input_hist)-1
93 init = max(1,final-default_length)
96 init = max(1,final-default_length)
94 elif len(args) == 1:
97 elif len(args) == 1:
95 final = len(input_hist)
98 final = len(input_hist)
96 init = max(1,final-int(args[0]))
99 init = max(1, final-int(args[0]))
97 elif len(args) == 2:
100 elif len(args) == 2:
98 init,final = map(int,args)
101 init, final = map(int, args)
99 else:
102 else:
100 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
103 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
101 print self.magic_hist.__doc__
104 print >> Term.cout, self.magic_hist.__doc__
102 return
105 return
106
103 width = len(str(final))
107 width = len(str(final))
104 line_sep = ['','\n']
108 line_sep = ['','\n']
105 print_nums = not opts.has_key('n')
109 print_nums = 'n' in opts
110 print_outputs = 'o' in opts
111 pyprompts = 'p' in opts
106
112
107 found = False
113 found = False
108 if pattern is not None:
114 if pattern is not None:
109 sh = ip.IP.shadowhist.all()
115 sh = self.shadowhist.all()
110 for idx, s in sh:
116 for idx, s in sh:
111 if fnmatch.fnmatch(s, pattern):
117 if fnmatch.fnmatch(s, pattern):
112 print "0%d: %s" %(idx, s)
118 print >> outfile, "0%d: %s" %(idx, s)
113 found = True
119 found = True
114
120
115 if found:
121 if found:
116 print "==="
122 print >> outfile, "==="
117 print "shadow history ends, fetch by %rep <number> (must start with 0)"
123 print >> outfile, \
118 print "=== start of normal history ==="
124 "shadow history ends, fetch by %rep <number> (must start with 0)"
125 print >> outfile, "=== start of normal history ==="
119
126
120 for in_num in range(init,final):
127 for in_num in range(init,final):
121 inline = input_hist[in_num]
128 inline = input_hist[in_num]
@@ -125,8 +132,21 b" def magic_history(self, parameter_s = ''):"
125 multiline = int(inline.count('\n') > 1)
132 multiline = int(inline.count('\n') > 1)
126 if print_nums:
133 if print_nums:
127 print >> outfile, \
134 print >> outfile, \
128 '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
135 '%s:%s' % (str(in_num).ljust(width), line_sep[multiline]),
129 print >> outfile, inline,
136 if pyprompts:
137 print >> outfile, '>>>',
138 if multiline:
139 lines = inline.splitlines()
140 print >> outfile, '\n... '.join(lines)
141 print >> outfile, '... '
142 else:
143 print >> outfile, inline,
144 else:
145 print >> outfile, inline,
146 if print_outputs:
147 output = self.shell.user_ns['Out'].get(in_num)
148 if output is not None:
149 print >> outfile, repr(output)
130
150
131 if close_at_end:
151 if close_at_end:
132 outfile.close()
152 outfile.close()
@@ -169,9 +189,8 b' def rep_f(self, arg):'
169 """
189 """
170
190
171 opts,args = self.parse_options(arg,'',mode='list')
191 opts,args = self.parse_options(arg,'',mode='list')
172 ip = self.api
173 if not args:
192 if not args:
174 ip.set_next_input(str(ip.user_ns["_"]))
193 self.set_next_input(str(self.user_ns["_"]))
175 return
194 return
176
195
177 if len(args) == 1 and not '-' in args[0]:
196 if len(args) == 1 and not '-' in args[0]:
@@ -180,33 +199,33 b' def rep_f(self, arg):'
180 # get from shadow hist
199 # get from shadow hist
181 num = int(arg[1:])
200 num = int(arg[1:])
182 line = self.shadowhist.get(num)
201 line = self.shadowhist.get(num)
183 ip.set_next_input(str(line))
202 self.set_next_input(str(line))
184 return
203 return
185 try:
204 try:
186 num = int(args[0])
205 num = int(args[0])
187 ip.set_next_input(str(ip.IP.input_hist_raw[num]).rstrip())
206 self.set_next_input(str(self.input_hist_raw[num]).rstrip())
188 return
207 return
189 except ValueError:
208 except ValueError:
190 pass
209 pass
191
210
192 for h in reversed(self.shell.input_hist_raw):
211 for h in reversed(self.input_hist_raw):
193 if 'rep' in h:
212 if 'rep' in h:
194 continue
213 continue
195 if fnmatch.fnmatch(h,'*' + arg + '*'):
214 if fnmatch.fnmatch(h,'*' + arg + '*'):
196 ip.set_next_input(str(h).rstrip())
215 self.set_next_input(str(h).rstrip())
197 return
216 return
198
217
199 try:
218 try:
200 lines = self.extract_input_slices(args, True)
219 lines = self.extract_input_slices(args, True)
201 print "lines",lines
220 print "lines",lines
202 ip.runlines(lines)
221 self.runlines(lines)
203 except ValueError:
222 except ValueError:
204 print "Not found in recent history:", args
223 print "Not found in recent history:", args
205
224
206
225
207 _sentinel = object()
226 _sentinel = object()
208
227
209 class ShadowHist:
228 class ShadowHist(object):
210 def __init__(self,db):
229 def __init__(self,db):
211 # cmd => idx mapping
230 # cmd => idx mapping
212 self.curidx = 0
231 self.curidx = 0
@@ -229,7 +248,7 b' class ShadowHist:'
229 #print "new",newidx # dbg
248 #print "new",newidx # dbg
230 self.db.hset('shadowhist',ent, newidx)
249 self.db.hset('shadowhist',ent, newidx)
231 except:
250 except:
232 IPython.ipapi.get().IP.showtraceback()
251 ipapi.get().showtraceback()
233 print "WARNING: disabling shadow history"
252 print "WARNING: disabling shadow history"
234 self.disabled = True
253 self.disabled = True
235
254
@@ -249,10 +268,10 b' class ShadowHist:'
249
268
250
269
251 def init_ipython(ip):
270 def init_ipython(ip):
252 import ipy_completers
271 ip.define_magic("rep",rep_f)
253
272 ip.define_magic("hist",magic_hist)
254 ip.expose_magic("rep",rep_f)
273 ip.define_magic("history",magic_history)
255 ip.expose_magic("hist",magic_hist)
256 ip.expose_magic("history",magic_history)
257
274
258 ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
275 # XXX - ipy_completers are in quarantine, need to be updated to new apis
276 #import ipy_completers
277 #ipy_completers.quick_completer('%hist' ,'-g -t -r -n')
@@ -19,14 +19,14 b" For example, suppose that you have a module called 'myiphooks' in your"
19 PYTHONPATH, which contains the following definition:
19 PYTHONPATH, which contains the following definition:
20
20
21 import os
21 import os
22 import IPython.ipapi
22 from IPython.core import ipapi
23 ip = IPython.ipapi.get()
23 ip = ipapi.get()
24
24
25 def calljed(self,filename, linenum):
25 def calljed(self,filename, linenum):
26 "My editor hook calls the jed editor directly."
26 "My editor hook calls the jed editor directly."
27 print "Calling my own editor, jed ..."
27 print "Calling my own editor, jed ..."
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
28 if os.system('jed +%d %s' % (linenum,filename)) != 0:
29 raise ipapi.TryNext()
29 raise TryNext()
30
30
31 ip.set_hook('editor', calljed)
31 ip.set_hook('editor', calljed)
32
32
@@ -41,20 +41,24 b' somewhere in your configuration files or ipython command line.'
41 # the file COPYING, distributed as part of this software.
41 # the file COPYING, distributed as part of this software.
42 #*****************************************************************************
42 #*****************************************************************************
43
43
44 from IPython import ipapi
44 import os, bisect
45 import sys
45
46
46 import os,bisect
47 from genutils import Term,shell
48 from pprint import PrettyPrinter
47 from pprint import PrettyPrinter
49
48
49 from IPython.utils.io import Term
50 from IPython.utils.process import shell
51
52 from IPython.core.error import TryNext
53
50 # List here all the default hooks. For now it's just the editor functions
54 # List here all the default hooks. For now it's just the editor functions
51 # but over time we'll move here all the public API for user-accessible things.
55 # but over time we'll move here all the public API for user-accessible things.
52 # vds: >>
56
53 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
57 __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display',
54 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
58 'input_prefilter', 'shutdown_hook', 'late_startup_hook',
55 'generate_prompt', 'generate_output_prompt','shell_hook',
59 'generate_prompt', 'generate_output_prompt','shell_hook',
56 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook']
60 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook',
57 # vds: <<
61 'clipboard_get']
58
62
59 pformat = PrettyPrinter().pformat
63 pformat = PrettyPrinter().pformat
60
64
@@ -67,7 +71,7 b' def editor(self,filename, linenum=None):'
67
71
68 # IPython configures a default editor at startup by reading $EDITOR from
72 # IPython configures a default editor at startup by reading $EDITOR from
69 # the environment, and falling back on vi (unix) or notepad (win32).
73 # the environment, and falling back on vi (unix) or notepad (win32).
70 editor = self.rc.editor
74 editor = self.editor
71
75
72 # marker for at which line to open the file (for existing objects)
76 # marker for at which line to open the file (for existing objects)
73 if linenum is None or editor=='notepad':
77 if linenum is None or editor=='notepad':
@@ -81,7 +85,7 b' def editor(self,filename, linenum=None):'
81
85
82 # Call the actual editor
86 # Call the actual editor
83 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
87 if os.system('%s %s %s' % (editor,linemark,filename)) != 0:
84 raise ipapi.TryNext()
88 raise TryNext()
85
89
86 import tempfile
90 import tempfile
87 def fix_error_editor(self,filename,linenum,column,msg):
91 def fix_error_editor(self,filename,linenum,column,msg):
@@ -97,20 +101,20 b' def fix_error_editor(self,filename,linenum,column,msg):'
97 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
101 t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
98 t.flush()
102 t.flush()
99 return t
103 return t
100 if os.path.basename(self.rc.editor) != 'vim':
104 if os.path.basename(self.editor) != 'vim':
101 self.hooks.editor(filename,linenum)
105 self.hooks.editor(filename,linenum)
102 return
106 return
103 t = vim_quickfix_file()
107 t = vim_quickfix_file()
104 try:
108 try:
105 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
109 if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name):
106 raise ipapi.TryNext()
110 raise TryNext()
107 finally:
111 finally:
108 t.close()
112 t.close()
109
113
110 # vds: >>
114
111 def synchronize_with_editor(self, filename, linenum, column):
115 def synchronize_with_editor(self, filename, linenum, column):
112 pass
116 pass
113 # vds: <<
117
114
118
115 class CommandChainDispatcher:
119 class CommandChainDispatcher:
116 """ Dispatch calls to a chain of commands until some func can handle it
120 """ Dispatch calls to a chain of commands until some func can handle it
@@ -136,14 +140,13 b' class CommandChainDispatcher:'
136 for prio,cmd in self.chain:
140 for prio,cmd in self.chain:
137 #print "prio",prio,"cmd",cmd #dbg
141 #print "prio",prio,"cmd",cmd #dbg
138 try:
142 try:
139 ret = cmd(*args, **kw)
143 return cmd(*args, **kw)
140 return ret
144 except TryNext, exc:
141 except ipapi.TryNext, exc:
142 if exc.args or exc.kwargs:
145 if exc.args or exc.kwargs:
143 args = exc.args
146 args = exc.args
144 kw = exc.kwargs
147 kw = exc.kwargs
145 # if no function will accept it, raise TryNext up to the caller
148 # if no function will accept it, raise TryNext up to the caller
146 raise ipapi.TryNext
149 raise TryNext
147
150
148 def __str__(self):
151 def __str__(self):
149 return str(self.chain)
152 return str(self.chain)
@@ -158,14 +161,15 b' class CommandChainDispatcher:'
158 Handy if the objects are not callable.
161 Handy if the objects are not callable.
159 """
162 """
160 return iter(self.chain)
163 return iter(self.chain)
161
164
165
162 def result_display(self,arg):
166 def result_display(self,arg):
163 """ Default display hook.
167 """ Default display hook.
164
168
165 Called for displaying the result to the user.
169 Called for displaying the result to the user.
166 """
170 """
167
171
168 if self.rc.pprint:
172 if self.pprint:
169 out = pformat(arg)
173 out = pformat(arg)
170 if '\n' in out:
174 if '\n' in out:
171 # So that multi-line strings line up with the left column of
175 # So that multi-line strings line up with the left column of
@@ -181,6 +185,7 b' def result_display(self,arg):'
181 # the default display hook doesn't manipulate the value to put in history
185 # the default display hook doesn't manipulate the value to put in history
182 return None
186 return None
183
187
188
184 def input_prefilter(self,line):
189 def input_prefilter(self,line):
185 """ Default input prefilter
190 """ Default input prefilter
186
191
@@ -195,6 +200,7 b' def input_prefilter(self,line):'
195 #print "attempt to rewrite",line #dbg
200 #print "attempt to rewrite",line #dbg
196 return line
201 return line
197
202
203
198 def shutdown_hook(self):
204 def shutdown_hook(self):
199 """ default shutdown hook
205 """ default shutdown hook
200
206
@@ -204,32 +210,36 b' def shutdown_hook(self):'
204 #print "default shutdown hook ok" # dbg
210 #print "default shutdown hook ok" # dbg
205 return
211 return
206
212
213
207 def late_startup_hook(self):
214 def late_startup_hook(self):
208 """ Executed after ipython has been constructed and configured
215 """ Executed after ipython has been constructed and configured
209
216
210 """
217 """
211 #print "default startup hook ok" # dbg
218 #print "default startup hook ok" # dbg
212
219
220
213 def generate_prompt(self, is_continuation):
221 def generate_prompt(self, is_continuation):
214 """ calculate and return a string with the prompt to display """
222 """ calculate and return a string with the prompt to display """
215 ip = self.api
216 if is_continuation:
223 if is_continuation:
217 return str(ip.IP.outputcache.prompt2)
224 return str(self.outputcache.prompt2)
218 return str(ip.IP.outputcache.prompt1)
225 return str(self.outputcache.prompt1)
226
219
227
220 def generate_output_prompt(self):
228 def generate_output_prompt(self):
221 ip = self.api
229 return str(self.outputcache.prompt_out)
222 return str(ip.IP.outputcache.prompt_out)
230
223
231
224 def shell_hook(self,cmd):
232 def shell_hook(self,cmd):
225 """ Run system/shell command a'la os.system() """
233 """ Run system/shell command a'la os.system() """
226
234
227 shell(cmd, header=self.rc.system_header, verbose=self.rc.system_verbose)
235 shell(cmd, header=self.system_header, verbose=self.system_verbose)
236
228
237
229 def show_in_pager(self,s):
238 def show_in_pager(self,s):
230 """ Run a string through pager """
239 """ Run a string through pager """
231 # raising TryNext here will use the default paging functionality
240 # raising TryNext here will use the default paging functionality
232 raise ipapi.TryNext
241 raise TryNext
242
233
243
234 def pre_prompt_hook(self):
244 def pre_prompt_hook(self):
235 """ Run before displaying the next prompt
245 """ Run before displaying the next prompt
@@ -240,8 +250,27 b' def pre_prompt_hook(self):'
240
250
241 return None
251 return None
242
252
253
243 def pre_runcode_hook(self):
254 def pre_runcode_hook(self):
244 """ Executed before running the (prefiltered) code in IPython """
255 """ Executed before running the (prefiltered) code in IPython """
245 return None
256 return None
246
247
257
258
259 def clipboard_get(self):
260 """ Get text from the clipboard.
261 """
262 from IPython.lib.clipboard import (
263 osx_clipboard_get, tkinter_clipboard_get,
264 win32_clipboard_get
265 )
266 if sys.platform == 'win32':
267 chain = [win32_clipboard_get, tkinter_clipboard_get]
268 elif sys.platform == 'darwin':
269 chain = [osx_clipboard_get, tkinter_clipboard_get]
270 else:
271 chain = [tkinter_clipboard_get]
272 dispatcher = CommandChainDispatcher()
273 for func in chain:
274 dispatcher.add(func)
275 text = dispatcher()
276 return text
1 NO CONTENT: file renamed from IPython/Logger.py to IPython/core/logger.py
NO CONTENT: file renamed from IPython/Logger.py to IPython/core/logger.py
@@ -7,10 +7,8 b''
7 # the file COPYING, distributed as part of this software.
7 # the file COPYING, distributed as part of this software.
8 #*****************************************************************************
8 #*****************************************************************************
9
9
10 import IPython.ipapi
10 from IPython.utils.io import Term
11
11 from IPython.core.autocall import IPyAutocall
12 from IPython.genutils import Term
13 from IPython.ipapi import IPyAutocall
14
12
15 class Macro(IPyAutocall):
13 class Macro(IPyAutocall):
16 """Simple class to store the value of macros as strings.
14 """Simple class to store the value of macros as strings.
This diff has been collapsed as it changes many lines, (791 lines changed) Show them Hide them
@@ -1,34 +1,33 b''
1 # -*- coding: utf-8 -*-
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #*****************************************************************************
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 #
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
12 #-----------------------------------------------------------------------------
12
13
13 #****************************************************************************
14 #-----------------------------------------------------------------------------
14 # Modules and globals
15 # Imports
16 #-----------------------------------------------------------------------------
15
17
16 # Python standard modules
17 import __builtin__
18 import __builtin__
18 import bdb
19 import bdb
19 import inspect
20 import inspect
20 import os
21 import os
21 import pdb
22 import pydoc
23 import sys
22 import sys
23 import shutil
24 import re
24 import re
25 import tempfile
26 import time
25 import time
27 import cPickle as pickle
28 import textwrap
26 import textwrap
27 import types
29 from cStringIO import StringIO
28 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
31 from pprint import pprint, pformat
30 from pprint import pformat
32
31
33 # cProfile was added in Python2.5
32 # cProfile was added in Python2.5
34 try:
33 try:
@@ -41,23 +40,32 b' except ImportError:'
41 except ImportError:
40 except ImportError:
42 profile = pstats = None
41 profile = pstats = None
43
42
44 # Homebrewed
45 import IPython
43 import IPython
46 from IPython import Debugger, OInspect, wildcard
44 from IPython.core import debugger, oinspect
47 from IPython.FakeModule import FakeModule
45 from IPython.core.error import TryNext
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
46 from IPython.core.error import UsageError
49 from IPython.PyColorize import Parser
47 from IPython.core.fakemodule import FakeModule
50 from IPython.ipstruct import Struct
48 from IPython.core.macro import Macro
51 from IPython.macro import Macro
49 from IPython.core.page import page
52 from IPython.genutils import *
50 from IPython.core.prefilter import ESC_MAGIC
53 from IPython import platutils
51 from IPython.lib.pylabtools import mpl_runner
54 import IPython.generics
52 from IPython.lib.inputhook import enable_gui
55 import IPython.ipapi
53 from IPython.external.Itpl import itpl, printpl
56 from IPython.ipapi import UsageError
57 from IPython.testing import decorators as testdec
54 from IPython.testing import decorators as testdec
58
55 from IPython.utils.io import Term, file_read, nlprint
59 #***************************************************************************
56 from IPython.utils.path import get_py_filename
57 from IPython.utils.process import arg_split, abbrev_cwd
58 from IPython.utils.terminal import set_term_title
59 from IPython.utils.text import LSString, SList, StringTypes
60 from IPython.utils.timing import clock, clock2
61 from IPython.utils.warn import warn, error
62 from IPython.utils.ipstruct import Struct
63 import IPython.utils.generics
64
65 #-----------------------------------------------------------------------------
60 # Utility functions
66 # Utility functions
67 #-----------------------------------------------------------------------------
68
61 def on_off(tag):
69 def on_off(tag):
62 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
63 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
@@ -76,10 +84,19 b' def compress_dhist(dh):'
76 done.add(h)
84 done.add(h)
77
85
78 return newhead + tail
86 return newhead + tail
79
87
80
88
81 #***************************************************************************
89 #***************************************************************************
82 # Main class implementing Magic functionality
90 # Main class implementing Magic functionality
91
92 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
93 # on construction of the main InteractiveShell object. Something odd is going
94 # on with super() calls, Component and the MRO... For now leave it as-is, but
95 # eventually this needs to be clarified.
96 # BG: This is because InteractiveShell inherits from this, but is itself a
97 # Component. This messes up the MRO in some way. The fix is that we need to
98 # make Magic a component that InteractiveShell does not subclass.
99
83 class Magic:
100 class Magic:
84 """Magic functions for InteractiveShell.
101 """Magic functions for InteractiveShell.
85
102
@@ -203,9 +220,9 b' python-profiler package from non-free.""")'
203 namespaces = [ ('Interactive', self.shell.user_ns),
220 namespaces = [ ('Interactive', self.shell.user_ns),
204 ('IPython internal', self.shell.internal_ns),
221 ('IPython internal', self.shell.internal_ns),
205 ('Python builtin', __builtin__.__dict__),
222 ('Python builtin', __builtin__.__dict__),
206 ('Alias', self.shell.alias_table),
223 ('Alias', self.shell.alias_manager.alias_table),
207 ]
224 ]
208 alias_ns = self.shell.alias_table
225 alias_ns = self.shell.alias_manager.alias_table
209
226
210 # initialize results to 'null'
227 # initialize results to 'null'
211 found = 0; obj = None; ospace = None; ds = None;
228 found = 0; obj = None; ospace = None; ds = None;
@@ -242,7 +259,7 b' python-profiler package from non-free.""")'
242
259
243 # Try to see if it's magic
260 # Try to see if it's magic
244 if not found:
261 if not found:
245 if oname.startswith(self.shell.ESC_MAGIC):
262 if oname.startswith(ESC_MAGIC):
246 oname = oname[1:]
263 oname = oname[1:]
247 obj = getattr(self,'magic_'+oname,None)
264 obj = getattr(self,'magic_'+oname,None)
248 if obj is not None:
265 if obj is not None:
@@ -262,7 +279,7 b' python-profiler package from non-free.""")'
262 def arg_err(self,func):
279 def arg_err(self,func):
263 """Print docstring if incorrect arguments were passed"""
280 """Print docstring if incorrect arguments were passed"""
264 print 'Error in arguments:'
281 print 'Error in arguments:'
265 print OInspect.getdoc(func)
282 print oinspect.getdoc(func)
266
283
267 def format_latex(self,strng):
284 def format_latex(self,strng):
268 """Format a string for latex inclusion."""
285 """Format a string for latex inclusion."""
@@ -270,10 +287,10 b' python-profiler package from non-free.""")'
270 # Characters that need to be escaped for latex:
287 # Characters that need to be escaped for latex:
271 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
288 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
272 # Magic command names as headers:
289 # Magic command names as headers:
273 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
290 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
274 re.MULTILINE)
291 re.MULTILINE)
275 # Magic commands
292 # Magic commands
276 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
293 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
277 re.MULTILINE)
294 re.MULTILINE)
278 # Paragraph continue
295 # Paragraph continue
279 par_re = re.compile(r'\\$',re.MULTILINE)
296 par_re = re.compile(r'\\$',re.MULTILINE)
@@ -331,7 +348,7 b' python-profiler package from non-free.""")'
331 raise ValueError,'incorrect mode given: %s' % mode
348 raise ValueError,'incorrect mode given: %s' % mode
332 # Get options
349 # Get options
333 list_all = kw.get('list_all',0)
350 list_all = kw.get('list_all',0)
334 posix = kw.get('posix',True)
351 posix = kw.get('posix', os.name == 'posix')
335
352
336 # Check if we have more than one argument to warrant extra processing:
353 # Check if we have more than one argument to warrant extra processing:
337 odict = {} # Dictionary with options
354 odict = {} # Dictionary with options
@@ -374,10 +391,10 b' python-profiler package from non-free.""")'
374 # Functions for IPython shell work (vars,funcs, config, etc)
391 # Functions for IPython shell work (vars,funcs, config, etc)
375 def magic_lsmagic(self, parameter_s = ''):
392 def magic_lsmagic(self, parameter_s = ''):
376 """List currently available magic functions."""
393 """List currently available magic functions."""
377 mesc = self.shell.ESC_MAGIC
394 mesc = ESC_MAGIC
378 print 'Available magic functions:\n'+mesc+\
395 print 'Available magic functions:\n'+mesc+\
379 (' '+mesc).join(self.lsmagic())
396 (' '+mesc).join(self.lsmagic())
380 print '\n' + Magic.auto_status[self.shell.rc.automagic]
397 print '\n' + Magic.auto_status[self.shell.automagic]
381 return None
398 return None
382
399
383 def magic_magic(self, parameter_s = ''):
400 def magic_magic(self, parameter_s = ''):
@@ -422,11 +439,11 b' python-profiler package from non-free.""")'
422
439
423
440
424 if mode == 'rest':
441 if mode == 'rest':
425 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(self.shell.ESC_MAGIC,
442 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
426 fname,fndoc))
443 fname,fndoc))
427
444
428 else:
445 else:
429 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
446 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
430 fname,fndoc))
447 fname,fndoc))
431
448
432 magic_docs = ''.join(magic_docs)
449 magic_docs = ''.join(magic_docs)
@@ -469,22 +486,22 b' ipythonrc file, placing a line like:'
469
486
470 will define %pf as a new name for %profile.
487 will define %pf as a new name for %profile.
471
488
472 You can also call magics in code using the ipmagic() function, which IPython
489 You can also call magics in code using the magic() function, which IPython
473 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
490 automatically adds to the builtin namespace. Type 'magic?' for details.
474
491
475 For a list of the available magic functions, use %lsmagic. For a description
492 For a list of the available magic functions, use %lsmagic. For a description
476 of any of them, type %magic_name?, e.g. '%cd?'.
493 of any of them, type %magic_name?, e.g. '%cd?'.
477
494
478 Currently the magic system has the following functions:\n"""
495 Currently the magic system has the following functions:\n"""
479
496
480 mesc = self.shell.ESC_MAGIC
497 mesc = ESC_MAGIC
481 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
498 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
482 "\n\n%s%s\n\n%s" % (outmsg,
499 "\n\n%s%s\n\n%s" % (outmsg,
483 magic_docs,mesc,mesc,
500 magic_docs,mesc,mesc,
484 (' '+mesc).join(self.lsmagic()),
501 (' '+mesc).join(self.lsmagic()),
485 Magic.auto_status[self.shell.rc.automagic] ) )
502 Magic.auto_status[self.shell.automagic] ) )
486
503
487 page(outmsg,screen_lines=self.shell.rc.screen_length)
504 page(outmsg,screen_lines=self.shell.usable_screen_length)
488
505
489
506
490 def magic_autoindent(self, parameter_s = ''):
507 def magic_autoindent(self, parameter_s = ''):
@@ -511,15 +528,14 b' Currently the magic system has the following functions:\\n"""'
511 delete the variable (del var), the previously shadowed magic function
528 delete the variable (del var), the previously shadowed magic function
512 becomes visible to automagic again."""
529 becomes visible to automagic again."""
513
530
514 rc = self.shell.rc
515 arg = parameter_s.lower()
531 arg = parameter_s.lower()
516 if parameter_s in ('on','1','true'):
532 if parameter_s in ('on','1','true'):
517 rc.automagic = True
533 self.shell.automagic = True
518 elif parameter_s in ('off','0','false'):
534 elif parameter_s in ('off','0','false'):
519 rc.automagic = False
535 self.shell.automagic = False
520 else:
536 else:
521 rc.automagic = not rc.automagic
537 self.shell.automagic = not self.shell.automagic
522 print '\n' + Magic.auto_status[rc.automagic]
538 print '\n' + Magic.auto_status[self.shell.automagic]
523
539
524 @testdec.skip_doctest
540 @testdec.skip_doctest
525 def magic_autocall(self, parameter_s = ''):
541 def magic_autocall(self, parameter_s = ''):
@@ -565,8 +581,6 b' Currently the magic system has the following functions:\\n"""'
565 # all-random (note for auto-testing)
581 # all-random (note for auto-testing)
566 """
582 """
567
583
568 rc = self.shell.rc
569
570 if parameter_s:
584 if parameter_s:
571 arg = int(parameter_s)
585 arg = int(parameter_s)
572 else:
586 else:
@@ -577,18 +591,18 b' Currently the magic system has the following functions:\\n"""'
577 return
591 return
578
592
579 if arg in (0,1,2):
593 if arg in (0,1,2):
580 rc.autocall = arg
594 self.shell.autocall = arg
581 else: # toggle
595 else: # toggle
582 if rc.autocall:
596 if self.shell.autocall:
583 self._magic_state.autocall_save = rc.autocall
597 self._magic_state.autocall_save = self.shell.autocall
584 rc.autocall = 0
598 self.shell.autocall = 0
585 else:
599 else:
586 try:
600 try:
587 rc.autocall = self._magic_state.autocall_save
601 self.shell.autocall = self._magic_state.autocall_save
588 except AttributeError:
602 except AttributeError:
589 rc.autocall = self._magic_state.autocall_save = 1
603 self.shell.autocall = self._magic_state.autocall_save = 1
590
604
591 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
605 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
592
606
593 def magic_system_verbose(self, parameter_s = ''):
607 def magic_system_verbose(self, parameter_s = ''):
594 """Set verbose printing of system calls.
608 """Set verbose printing of system calls.
@@ -599,10 +613,13 b' Currently the magic system has the following functions:\\n"""'
599 val = bool(eval(parameter_s))
613 val = bool(eval(parameter_s))
600 else:
614 else:
601 val = None
615 val = None
602
616
603 self.shell.rc_set_toggle('system_verbose',val)
617 if self.shell.system_verbose:
618 self.shell.system_verbose = False
619 else:
620 self.shell.system_verbose = True
604 print "System verbose printing is:",\
621 print "System verbose printing is:",\
605 ['OFF','ON'][self.shell.rc.system_verbose]
622 ['OFF','ON'][self.shell.system_verbose]
606
623
607
624
608 def magic_page(self, parameter_s=''):
625 def magic_page(self, parameter_s=''):
@@ -632,8 +649,8 b' Currently the magic system has the following functions:\\n"""'
632
649
633 def magic_profile(self, parameter_s=''):
650 def magic_profile(self, parameter_s=''):
634 """Print your currently active IPyhton profile."""
651 """Print your currently active IPyhton profile."""
635 if self.shell.rc.profile:
652 if self.shell.profile:
636 printpl('Current IPython profile: $self.shell.rc.profile.')
653 printpl('Current IPython profile: $self.shell.profile.')
637 else:
654 else:
638 print 'No profile active.'
655 print 'No profile active.'
639
656
@@ -717,9 +734,9 b' Currently the magic system has the following functions:\\n"""'
717
734
718 if info.found:
735 if info.found:
719 try:
736 try:
720 IPython.generics.inspect_object(info.obj)
737 IPython.utils.generics.inspect_object(info.obj)
721 return
738 return
722 except IPython.ipapi.TryNext:
739 except TryNext:
723 pass
740 pass
724 # Get the docstring of the class property if it exists.
741 # Get the docstring of the class property if it exists.
725 path = oname.split('.')
742 path = oname.split('.')
@@ -847,7 +864,7 b' Currently the magic system has the following functions:\\n"""'
847 elif opts.has_key('c'):
864 elif opts.has_key('c'):
848 ignore_case = False
865 ignore_case = False
849 else:
866 else:
850 ignore_case = not shell.rc.wildcards_case_sensitive
867 ignore_case = not shell.wildcards_case_sensitive
851
868
852 # Build list of namespaces to search from user options
869 # Build list of namespaces to search from user options
853 def_search.extend(opt('s',[]))
870 def_search.extend(opt('s',[]))
@@ -860,7 +877,7 b' Currently the magic system has the following functions:\\n"""'
860 show_all=opt('a'),ignore_case=ignore_case)
877 show_all=opt('a'),ignore_case=ignore_case)
861 except:
878 except:
862 shell.showtraceback()
879 shell.showtraceback()
863
880
864 def magic_who_ls(self, parameter_s=''):
881 def magic_who_ls(self, parameter_s=''):
865 """Return a sorted list of all interactive variables.
882 """Return a sorted list of all interactive variables.
866
883
@@ -869,18 +886,16 b' Currently the magic system has the following functions:\\n"""'
869
886
870 user_ns = self.shell.user_ns
887 user_ns = self.shell.user_ns
871 internal_ns = self.shell.internal_ns
888 internal_ns = self.shell.internal_ns
872 user_config_ns = self.shell.user_config_ns
889 user_ns_hidden = self.shell.user_ns_hidden
873 out = []
890 out = [ i for i in user_ns
891 if not i.startswith('_') \
892 and not (i in internal_ns or i in user_ns_hidden) ]
893
874 typelist = parameter_s.split()
894 typelist = parameter_s.split()
895 if typelist:
896 typeset = set(typelist)
897 out = [i for i in out if type(i).__name__ in typeset]
875
898
876 for i in user_ns:
877 if not (i.startswith('_') or i.startswith('_i')) \
878 and not (i in internal_ns or i in user_config_ns):
879 if typelist:
880 if type(user_ns[i]).__name__ in typelist:
881 out.append(i)
882 else:
883 out.append(i)
884 out.sort()
899 out.sort()
885 return out
900 return out
886
901
@@ -972,7 +987,7 b' Currently the magic system has the following functions:\\n"""'
972 return self.shell.user_ns[i]
987 return self.shell.user_ns[i]
973
988
974 # some types are well known and can be shorter
989 # some types are well known and can be shorter
975 abbrevs = {'IPython.macro.Macro' : 'Macro'}
990 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
976 def type_name(v):
991 def type_name(v):
977 tn = type(v).__name__
992 tn = type(v).__name__
978 return abbrevs.get(tn,tn)
993 return abbrevs.get(tn,tn)
@@ -1131,7 +1146,6 b' Currently the magic system has the following functions:\\n"""'
1131 log_raw_input = 'r' in opts
1146 log_raw_input = 'r' in opts
1132 timestamp = 't' in opts
1147 timestamp = 't' in opts
1133
1148
1134 rc = self.shell.rc
1135 logger = self.shell.logger
1149 logger = self.shell.logger
1136
1150
1137 # if no args are given, the defaults set in the logger constructor by
1151 # if no args are given, the defaults set in the logger constructor by
@@ -1148,16 +1162,17 b' Currently the magic system has the following functions:\\n"""'
1148 # put logfname into rc struct as if it had been called on the command
1162 # put logfname into rc struct as if it had been called on the command
1149 # line, so it ends up saved in the log header Save it in case we need
1163 # line, so it ends up saved in the log header Save it in case we need
1150 # to restore it...
1164 # to restore it...
1151 old_logfile = rc.opts.get('logfile','')
1165 old_logfile = self.shell.logfile
1152 if logfname:
1166 if logfname:
1153 logfname = os.path.expanduser(logfname)
1167 logfname = os.path.expanduser(logfname)
1154 rc.opts.logfile = logfname
1168 self.shell.logfile = logfname
1155 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1169
1170 loghead = '# IPython log file\n\n'
1156 try:
1171 try:
1157 started = logger.logstart(logfname,loghead,logmode,
1172 started = logger.logstart(logfname,loghead,logmode,
1158 log_output,timestamp,log_raw_input)
1173 log_output,timestamp,log_raw_input)
1159 except:
1174 except:
1160 rc.opts.logfile = old_logfile
1175 self.shell.logfile = old_logfile
1161 warn("Couldn't start log: %s" % sys.exc_info()[1])
1176 warn("Couldn't start log: %s" % sys.exc_info()[1])
1162 else:
1177 else:
1163 # log input history up to this point, optionally interleaving
1178 # log input history up to this point, optionally interleaving
@@ -1265,7 +1280,6 b' Currently the magic system has the following functions:\\n"""'
1265 If you want IPython to automatically do this on every exception, see
1280 If you want IPython to automatically do this on every exception, see
1266 the %pdb magic for more details.
1281 the %pdb magic for more details.
1267 """
1282 """
1268
1269 self.shell.debugger(force=True)
1283 self.shell.debugger(force=True)
1270
1284
1271 @testdec.skip_doctest
1285 @testdec.skip_doctest
@@ -1420,7 +1434,7 b' Currently the magic system has the following functions:\\n"""'
1420 output = stdout_trap.getvalue()
1434 output = stdout_trap.getvalue()
1421 output = output.rstrip()
1435 output = output.rstrip()
1422
1436
1423 page(output,screen_lines=self.shell.rc.screen_length)
1437 page(output,screen_lines=self.shell.usable_screen_length)
1424 print sys_exit,
1438 print sys_exit,
1425
1439
1426 dump_file = opts.D[0]
1440 dump_file = opts.D[0]
@@ -1561,14 +1575,14 b' Currently the magic system has the following functions:\\n"""'
1561 filename = file_finder(arg_lst[0])
1575 filename = file_finder(arg_lst[0])
1562 except IndexError:
1576 except IndexError:
1563 warn('you must provide at least a filename.')
1577 warn('you must provide at least a filename.')
1564 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1578 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1565 return
1579 return
1566 except IOError,msg:
1580 except IOError,msg:
1567 error(msg)
1581 error(msg)
1568 return
1582 return
1569
1583
1570 if filename.lower().endswith('.ipy'):
1584 if filename.lower().endswith('.ipy'):
1571 self.api.runlines(open(filename).read())
1585 self.shell.safe_execfile_ipy(filename)
1572 return
1586 return
1573
1587
1574 # Control the response to exit() calls made by the script being run
1588 # Control the response to exit() calls made by the script being run
@@ -1584,23 +1598,17 b' Currently the magic system has the following functions:\\n"""'
1584 prog_ns = self.shell.user_ns
1598 prog_ns = self.shell.user_ns
1585 __name__save = self.shell.user_ns['__name__']
1599 __name__save = self.shell.user_ns['__name__']
1586 prog_ns['__name__'] = '__main__'
1600 prog_ns['__name__'] = '__main__'
1587 main_mod = FakeModule(prog_ns)
1601 main_mod = self.shell.new_main_mod(prog_ns)
1588 else:
1602 else:
1589 # Run in a fresh, empty namespace
1603 # Run in a fresh, empty namespace
1590 if opts.has_key('n'):
1604 if opts.has_key('n'):
1591 name = os.path.splitext(os.path.basename(filename))[0]
1605 name = os.path.splitext(os.path.basename(filename))[0]
1592 else:
1606 else:
1593 name = '__main__'
1607 name = '__main__'
1594 main_mod = FakeModule()
1608
1609 main_mod = self.shell.new_main_mod()
1595 prog_ns = main_mod.__dict__
1610 prog_ns = main_mod.__dict__
1596 prog_ns['__name__'] = name
1611 prog_ns['__name__'] = name
1597
1598 # The shell MUST hold a reference to main_mod so after %run exits,
1599 # the python deletion mechanism doesn't zero it out (leaving
1600 # dangling references). However, we should drop old versions of
1601 # main_mod. There is now a proper API to manage this caching in
1602 # the main shell object, we use that.
1603 self.shell.cache_main_mod(main_mod)
1604
1612
1605 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1613 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1606 # set the __file__ global in the script's namespace
1614 # set the __file__ global in the script's namespace
@@ -1627,7 +1635,7 b' Currently the magic system has the following functions:\\n"""'
1627 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1635 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1628 else:
1636 else:
1629 if opts.has_key('d'):
1637 if opts.has_key('d'):
1630 deb = Debugger.Pdb(self.shell.rc.colors)
1638 deb = debugger.Pdb(self.shell.colors)
1631 # reset Breakpoint state, which is moronically kept
1639 # reset Breakpoint state, which is moronically kept
1632 # in a class
1640 # in a class
1633 bdb.Breakpoint.next = 1
1641 bdb.Breakpoint.next = 1
@@ -1681,7 +1689,7 b' Currently the magic system has the following functions:\\n"""'
1681 exit_ignore=exit_ignore)
1689 exit_ignore=exit_ignore)
1682 t1 = clock2()
1690 t1 = clock2()
1683 t_usr = t1[0]-t0[0]
1691 t_usr = t1[0]-t0[0]
1684 t_sys = t1[1]-t1[1]
1692 t_sys = t1[1]-t0[1]
1685 print "\nIPython CPU timings (estimated):"
1693 print "\nIPython CPU timings (estimated):"
1686 print " User : %10s s." % t_usr
1694 print " User : %10s s." % t_usr
1687 print " System: %10s s." % t_sys
1695 print " System: %10s s." % t_sys
@@ -1693,7 +1701,7 b' Currently the magic system has the following functions:\\n"""'
1693 exit_ignore=exit_ignore)
1701 exit_ignore=exit_ignore)
1694 t1 = clock2()
1702 t1 = clock2()
1695 t_usr = t1[0]-t0[0]
1703 t_usr = t1[0]-t0[0]
1696 t_sys = t1[1]-t1[1]
1704 t_sys = t1[1]-t0[1]
1697 print "\nIPython CPU timings (estimated):"
1705 print "\nIPython CPU timings (estimated):"
1698 print "Total runs performed:",nruns
1706 print "Total runs performed:",nruns
1699 print " Times : %10s %10s" % ('Total','Per run')
1707 print " Times : %10s %10s" % ('Total','Per run')
@@ -1703,13 +1711,33 b' Currently the magic system has the following functions:\\n"""'
1703 else:
1711 else:
1704 # regular execution
1712 # regular execution
1705 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1713 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1714
1706 if opts.has_key('i'):
1715 if opts.has_key('i'):
1707 self.shell.user_ns['__name__'] = __name__save
1716 self.shell.user_ns['__name__'] = __name__save
1708 else:
1717 else:
1718 # The shell MUST hold a reference to prog_ns so after %run
1719 # exits, the python deletion mechanism doesn't zero it out
1720 # (leaving dangling references).
1721 self.shell.cache_main_mod(prog_ns,filename)
1709 # update IPython interactive namespace
1722 # update IPython interactive namespace
1710 del prog_ns['__name__']
1723
1724 # Some forms of read errors on the file may mean the
1725 # __name__ key was never set; using pop we don't have to
1726 # worry about a possible KeyError.
1727 prog_ns.pop('__name__', None)
1728
1711 self.shell.user_ns.update(prog_ns)
1729 self.shell.user_ns.update(prog_ns)
1712 finally:
1730 finally:
1731 # It's a bit of a mystery why, but __builtins__ can change from
1732 # being a module to becoming a dict missing some key data after
1733 # %run. As best I can see, this is NOT something IPython is doing
1734 # at all, and similar problems have been reported before:
1735 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1736 # Since this seems to be done by the interpreter itself, the best
1737 # we can do is to at least restore __builtins__ for the user on
1738 # exit.
1739 self.shell.user_ns['__builtins__'] = __builtin__
1740
1713 # Ensure key global structures are restored
1741 # Ensure key global structures are restored
1714 sys.argv = save_argv
1742 sys.argv = save_argv
1715 if restore_main:
1743 if restore_main:
@@ -1719,29 +1747,11 b' Currently the magic system has the following functions:\\n"""'
1719 # added. Otherwise it will trap references to objects
1747 # added. Otherwise it will trap references to objects
1720 # contained therein.
1748 # contained therein.
1721 del sys.modules[main_mod_name]
1749 del sys.modules[main_mod_name]
1750
1722 self.shell.reloadhist()
1751 self.shell.reloadhist()
1723
1752
1724 return stats
1753 return stats
1725
1754
1726 def magic_runlog(self, parameter_s =''):
1727 """Run files as logs.
1728
1729 Usage:\\
1730 %runlog file1 file2 ...
1731
1732 Run the named files (treating them as log files) in sequence inside
1733 the interpreter, and return to the prompt. This is much slower than
1734 %run because each line is executed in a try/except block, but it
1735 allows running files with syntax errors in them.
1736
1737 Normally IPython will guess when a file is one of its own logfiles, so
1738 you can typically use %run even for logs. This shorthand allows you to
1739 force any file to be treated as a log file."""
1740
1741 for f in parameter_s.split():
1742 self.shell.safe_execfile(f,self.shell.user_ns,
1743 self.shell.user_ns,islog=1)
1744
1745 @testdec.skip_doctest
1755 @testdec.skip_doctest
1746 def magic_timeit(self, parameter_s =''):
1756 def magic_timeit(self, parameter_s =''):
1747 """Time execution of a Python statement or expression
1757 """Time execution of a Python statement or expression
@@ -1800,7 +1810,28 b' Currently the magic system has the following functions:\\n"""'
1800 import timeit
1810 import timeit
1801 import math
1811 import math
1802
1812
1803 units = [u"s", u"ms", u"\xb5s", u"ns"]
1813 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1814 # certain terminals. Until we figure out a robust way of
1815 # auto-detecting if the terminal can deal with it, use plain 'us' for
1816 # microseconds. I am really NOT happy about disabling the proper
1817 # 'micro' prefix, but crashing is worse... If anyone knows what the
1818 # right solution for this is, I'm all ears...
1819 #
1820 # Note: using
1821 #
1822 # s = u'\xb5'
1823 # s.encode(sys.getdefaultencoding())
1824 #
1825 # is not sufficient, as I've seen terminals where that fails but
1826 # print s
1827 #
1828 # succeeds
1829 #
1830 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1831
1832 #units = [u"s", u"ms",u'\xb5',"ns"]
1833 units = [u"s", u"ms",u'us',"ns"]
1834
1804 scaling = [1, 1e3, 1e6, 1e9]
1835 scaling = [1, 1e3, 1e6, 1e9]
1805
1836
1806 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1837 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
@@ -1839,9 +1870,9 b' Currently the magic system has the following functions:\\n"""'
1839 # determine number so that 0.2 <= total time < 2.0
1870 # determine number so that 0.2 <= total time < 2.0
1840 number = 1
1871 number = 1
1841 for i in range(1, 10):
1872 for i in range(1, 10):
1842 number *= 10
1843 if timer.timeit(number) >= 0.2:
1873 if timer.timeit(number) >= 0.2:
1844 break
1874 break
1875 number *= 10
1845
1876
1846 best = min(timer.repeat(repeat, number)) / number
1877 best = min(timer.repeat(repeat, number)) / number
1847
1878
@@ -2024,7 +2055,7 b' Currently the magic system has the following functions:\\n"""'
2024 #print 'rng',ranges # dbg
2055 #print 'rng',ranges # dbg
2025 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2056 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2026 macro = Macro(lines)
2057 macro = Macro(lines)
2027 self.shell.user_ns.update({name:macro})
2058 self.shell.define_macro(name, macro)
2028 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2029 print 'Macro contents:'
2060 print 'Macro contents:'
2030 print macro,
2061 print macro,
@@ -2221,7 +2252,7 b' Currently the magic system has the following functions:\\n"""'
2221
2252
2222 If you wish to write your own editor hook, you can put it in a
2253 If you wish to write your own editor hook, you can put it in a
2223 configuration file which you load at startup time. The default hook
2254 configuration file which you load at startup time. The default hook
2224 is defined in the IPython.hooks module, and you can use that as a
2255 is defined in the IPython.core.hooks module, and you can use that as a
2225 starting example for further modifications. That file also has
2256 starting example for further modifications. That file also has
2226 general instructions on how to set a new hook for use once you've
2257 general instructions on how to set a new hook for use once you've
2227 defined it."""
2258 defined it."""
@@ -2354,7 +2385,7 b' Currently the magic system has the following functions:\\n"""'
2354 sys.stdout.flush()
2385 sys.stdout.flush()
2355 try:
2386 try:
2356 self.shell.hooks.editor(filename,lineno)
2387 self.shell.hooks.editor(filename,lineno)
2357 except IPython.ipapi.TryNext:
2388 except TryNext:
2358 warn('Could not open editor')
2389 warn('Could not open editor')
2359 return
2390 return
2360
2391
@@ -2430,7 +2461,7 b' Currently the magic system has the following functions:\\n"""'
2430 # local shortcut
2461 # local shortcut
2431 shell = self.shell
2462 shell = self.shell
2432
2463
2433 import IPython.rlineimpl as readline
2464 import IPython.utils.rlineimpl as readline
2434
2465
2435 if not readline.have_readline and sys.platform == "win32":
2466 if not readline.have_readline and sys.platform == "win32":
2436 msg = """\
2467 msg = """\
@@ -2455,7 +2486,7 b' Defaulting color scheme to \'NoColor\'"""'
2455 except:
2486 except:
2456 color_switch_err('prompt')
2487 color_switch_err('prompt')
2457 else:
2488 else:
2458 shell.rc.colors = \
2489 shell.colors = \
2459 shell.outputcache.color_table.active_scheme_name
2490 shell.outputcache.color_table.active_scheme_name
2460 # Set exception colors
2491 # Set exception colors
2461 try:
2492 try:
@@ -2472,7 +2503,7 b' Defaulting color scheme to \'NoColor\'"""'
2472 color_switch_err('system exception handler')
2503 color_switch_err('system exception handler')
2473
2504
2474 # Set info (for 'object?') colors
2505 # Set info (for 'object?') colors
2475 if shell.rc.color_info:
2506 if shell.color_info:
2476 try:
2507 try:
2477 shell.inspector.set_active_scheme(new_scheme)
2508 shell.inspector.set_active_scheme(new_scheme)
2478 except:
2509 except:
@@ -2491,36 +2522,26 b' Defaulting color scheme to \'NoColor\'"""'
2491 than more) in your system, using colored object information displays
2522 than more) in your system, using colored object information displays
2492 will not work properly. Test it and see."""
2523 will not work properly. Test it and see."""
2493
2524
2494 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2525 self.shell.color_info = not self.shell.color_info
2495 self.magic_colors(self.shell.rc.colors)
2526 self.magic_colors(self.shell.colors)
2496 print 'Object introspection functions have now coloring:',
2527 print 'Object introspection functions have now coloring:',
2497 print ['OFF','ON'][self.shell.rc.color_info]
2528 print ['OFF','ON'][int(self.shell.color_info)]
2498
2529
2499 def magic_Pprint(self, parameter_s=''):
2530 def magic_Pprint(self, parameter_s=''):
2500 """Toggle pretty printing on/off."""
2531 """Toggle pretty printing on/off."""
2501
2532
2502 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2533 self.shell.pprint = 1 - self.shell.pprint
2503 print 'Pretty printing has been turned', \
2534 print 'Pretty printing has been turned', \
2504 ['OFF','ON'][self.shell.rc.pprint]
2535 ['OFF','ON'][self.shell.pprint]
2505
2536
2506 def magic_exit(self, parameter_s=''):
2507 """Exit IPython, confirming if configured to do so.
2508
2509 You can configure whether IPython asks for confirmation upon exit by
2510 setting the confirm_exit flag in the ipythonrc file."""
2511
2512 self.shell.exit()
2513
2514 def magic_quit(self, parameter_s=''):
2515 """Exit IPython, confirming if configured to do so (like %exit)"""
2516
2517 self.shell.exit()
2518
2519 def magic_Exit(self, parameter_s=''):
2537 def magic_Exit(self, parameter_s=''):
2520 """Exit IPython without confirmation."""
2538 """Exit IPython without confirmation."""
2521
2539
2522 self.shell.ask_exit()
2540 self.shell.ask_exit()
2523
2541
2542 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2543 magic_exit = magic_quit = magic_Quit = magic_Exit
2544
2524 #......................................................................
2545 #......................................................................
2525 # Functions to implement unix shell-type things
2546 # Functions to implement unix shell-type things
2526
2547
@@ -2580,52 +2601,27 b' Defaulting color scheme to \'NoColor\'"""'
2580 par = parameter_s.strip()
2601 par = parameter_s.strip()
2581 if not par:
2602 if not par:
2582 stored = self.db.get('stored_aliases', {} )
2603 stored = self.db.get('stored_aliases', {} )
2583 atab = self.shell.alias_table
2604 aliases = sorted(self.shell.alias_manager.aliases)
2584 aliases = atab.keys()
2605 # for k, v in stored:
2585 aliases.sort()
2606 # atab.append(k, v[0])
2586 res = []
2607
2587 showlast = []
2608 print "Total number of aliases:", len(aliases)
2588 for alias in aliases:
2609 return aliases
2589 special = False
2610
2590 try:
2611 # Now try to define a new one
2591 tgt = atab[alias][1]
2592 except (TypeError, AttributeError):
2593 # unsubscriptable? probably a callable
2594 tgt = atab[alias]
2595 special = True
2596 # 'interesting' aliases
2597 if (alias in stored or
2598 special or
2599 alias.lower() != os.path.splitext(tgt)[0].lower() or
2600 ' ' in tgt):
2601 showlast.append((alias, tgt))
2602 else:
2603 res.append((alias, tgt ))
2604
2605 # show most interesting aliases last
2606 res.extend(showlast)
2607 print "Total number of aliases:",len(aliases)
2608 return res
2609 try:
2612 try:
2610 alias,cmd = par.split(None,1)
2613 alias,cmd = par.split(None, 1)
2611 except:
2614 except:
2612 print OInspect.getdoc(self.magic_alias)
2615 print oinspect.getdoc(self.magic_alias)
2613 else:
2616 else:
2614 nargs = cmd.count('%s')
2617 self.shell.alias_manager.soft_define_alias(alias, cmd)
2615 if nargs>0 and cmd.find('%l')>=0:
2616 error('The %s and %l specifiers are mutually exclusive '
2617 'in alias definitions.')
2618 else: # all looks OK
2619 self.shell.alias_table[alias] = (nargs,cmd)
2620 self.shell.alias_table_validate(verbose=0)
2621 # end magic_alias
2618 # end magic_alias
2622
2619
2623 def magic_unalias(self, parameter_s = ''):
2620 def magic_unalias(self, parameter_s = ''):
2624 """Remove an alias"""
2621 """Remove an alias"""
2625
2622
2626 aname = parameter_s.strip()
2623 aname = parameter_s.strip()
2627 if aname in self.shell.alias_table:
2624 self.shell.alias_manager.undefine_alias(aname)
2628 del self.shell.alias_table[aname]
2629 stored = self.db.get('stored_aliases', {} )
2625 stored = self.db.get('stored_aliases', {} )
2630 if aname in stored:
2626 if aname in stored:
2631 print "Removing %stored alias",aname
2627 print "Removing %stored alias",aname
@@ -2646,24 +2642,21 b' Defaulting color scheme to \'NoColor\'"""'
2646 This function also resets the root module cache of module completer,
2642 This function also resets the root module cache of module completer,
2647 used on slow filesystems.
2643 used on slow filesystems.
2648 """
2644 """
2649
2645 from IPython.core.alias import InvalidAliasError
2650
2651 ip = self.api
2652
2646
2653 # for the benefit of module completer in ipy_completers.py
2647 # for the benefit of module completer in ipy_completers.py
2654 del ip.db['rootmodules']
2648 del self.db['rootmodules']
2655
2649
2656 path = [os.path.abspath(os.path.expanduser(p)) for p in
2650 path = [os.path.abspath(os.path.expanduser(p)) for p in
2657 os.environ.get('PATH','').split(os.pathsep)]
2651 os.environ.get('PATH','').split(os.pathsep)]
2658 path = filter(os.path.isdir,path)
2652 path = filter(os.path.isdir,path)
2659
2653
2660 alias_table = self.shell.alias_table
2661 syscmdlist = []
2654 syscmdlist = []
2655 # Now define isexec in a cross platform manner.
2662 if os.name == 'posix':
2656 if os.name == 'posix':
2663 isexec = lambda fname:os.path.isfile(fname) and \
2657 isexec = lambda fname:os.path.isfile(fname) and \
2664 os.access(fname,os.X_OK)
2658 os.access(fname,os.X_OK)
2665 else:
2659 else:
2666
2667 try:
2660 try:
2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2661 winext = os.environ['pathext'].replace(';','|').replace('.','')
2669 except KeyError:
2662 except KeyError:
@@ -2673,6 +2666,8 b' Defaulting color scheme to \'NoColor\'"""'
2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2666 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2667 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2675 savedir = os.getcwd()
2668 savedir = os.getcwd()
2669
2670 # Now walk the paths looking for executables to alias.
2676 try:
2671 try:
2677 # write the whole loop for posix/Windows so we don't have an if in
2672 # write the whole loop for posix/Windows so we don't have an if in
2678 # the innermost part
2673 # the innermost part
@@ -2680,33 +2675,34 b' Defaulting color scheme to \'NoColor\'"""'
2680 for pdir in path:
2675 for pdir in path:
2681 os.chdir(pdir)
2676 os.chdir(pdir)
2682 for ff in os.listdir(pdir):
2677 for ff in os.listdir(pdir):
2683 if isexec(ff) and ff not in self.shell.no_alias:
2678 if isexec(ff):
2684 # each entry in the alias table must be (N,name),
2679 try:
2685 # where N is the number of positional arguments of the
2680 # Removes dots from the name since ipython
2686 # alias.
2681 # will assume names with dots to be python.
2687 # Dots will be removed from alias names, since ipython
2682 self.shell.alias_manager.define_alias(
2688 # assumes names with dots to be python code
2683 ff.replace('.',''), ff)
2689 alias_table[ff.replace('.','')] = (0,ff)
2684 except InvalidAliasError:
2690 syscmdlist.append(ff)
2685 pass
2686 else:
2687 syscmdlist.append(ff)
2691 else:
2688 else:
2689 no_alias = self.shell.alias_manager.no_alias
2692 for pdir in path:
2690 for pdir in path:
2693 os.chdir(pdir)
2691 os.chdir(pdir)
2694 for ff in os.listdir(pdir):
2692 for ff in os.listdir(pdir):
2695 base, ext = os.path.splitext(ff)
2693 base, ext = os.path.splitext(ff)
2696 if isexec(ff) and base.lower() not in self.shell.no_alias:
2694 if isexec(ff) and base.lower() not in no_alias:
2697 if ext.lower() == '.exe':
2695 if ext.lower() == '.exe':
2698 ff = base
2696 ff = base
2699 alias_table[base.lower().replace('.','')] = (0,ff)
2697 try:
2700 syscmdlist.append(ff)
2698 # Removes dots from the name since ipython
2701 # Make sure the alias table doesn't contain keywords or builtins
2699 # will assume names with dots to be python.
2702 self.shell.alias_table_validate()
2700 self.shell.alias_manager.define_alias(
2703 # Call again init_auto_alias() so we get 'rm -i' and other
2701 base.lower().replace('.',''), ff)
2704 # modified aliases since %rehashx will probably clobber them
2702 except InvalidAliasError:
2705
2703 pass
2706 # no, we don't want them. if %rehashx clobbers them, good,
2704 syscmdlist.append(ff)
2707 # we'll probably get better versions
2705 db = self.db
2708 # self.shell.init_auto_alias()
2709 db = ip.db
2710 db['syscmdlist'] = syscmdlist
2706 db['syscmdlist'] = syscmdlist
2711 finally:
2707 finally:
2712 os.chdir(savedir)
2708 os.chdir(savedir)
@@ -2816,9 +2812,8 b' Defaulting color scheme to \'NoColor\'"""'
2816 if ps:
2812 if ps:
2817 try:
2813 try:
2818 os.chdir(os.path.expanduser(ps))
2814 os.chdir(os.path.expanduser(ps))
2819 if self.shell.rc.term_title:
2815 if self.shell.term_title:
2820 #print 'set term title:',self.shell.rc.term_title # dbg
2816 set_term_title('IPython: ' + abbrev_cwd())
2821 platutils.set_term_title('IPy ' + abbrev_cwd())
2822 except OSError:
2817 except OSError:
2823 print sys.exc_info()[1]
2818 print sys.exc_info()[1]
2824 else:
2819 else:
@@ -2830,8 +2825,8 b' Defaulting color scheme to \'NoColor\'"""'
2830
2825
2831 else:
2826 else:
2832 os.chdir(self.shell.home_dir)
2827 os.chdir(self.shell.home_dir)
2833 if self.shell.rc.term_title:
2828 if self.shell.term_title:
2834 platutils.set_term_title("IPy ~")
2829 set_term_title('IPython: ' + '~')
2835 cwd = os.getcwd()
2830 cwd = os.getcwd()
2836 dhist = self.shell.user_ns['_dh']
2831 dhist = self.shell.user_ns['_dh']
2837
2832
@@ -3131,10 +3126,10 b' Defaulting color scheme to \'NoColor\'"""'
3131 """
3126 """
3132
3127
3133 start = parameter_s.strip()
3128 start = parameter_s.strip()
3134 esc_magic = self.shell.ESC_MAGIC
3129 esc_magic = ESC_MAGIC
3135 # Identify magic commands even if automagic is on (which means
3130 # Identify magic commands even if automagic is on (which means
3136 # the in-memory version is different from that typed by the user).
3131 # the in-memory version is different from that typed by the user).
3137 if self.shell.rc.automagic:
3132 if self.shell.automagic:
3138 start_magic = esc_magic+start
3133 start_magic = esc_magic+start
3139 else:
3134 else:
3140 start_magic = start
3135 start_magic = start
@@ -3228,7 +3223,62 b' Defaulting color scheme to \'NoColor\'"""'
3228 return
3223 return
3229
3224
3230 page(self.shell.pycolorize(cont),
3225 page(self.shell.pycolorize(cont),
3231 screen_lines=self.shell.rc.screen_length)
3226 screen_lines=self.shell.usable_screen_length)
3227
3228 def _rerun_pasted(self):
3229 """ Rerun a previously pasted command.
3230 """
3231 b = self.user_ns.get('pasted_block', None)
3232 if b is None:
3233 raise UsageError('No previous pasted block available')
3234 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3235 exec b in self.user_ns
3236
3237 def _get_pasted_lines(self, sentinel):
3238 """ Yield pasted lines until the user enters the given sentinel value.
3239 """
3240 from IPython.core import iplib
3241 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3242 while True:
3243 l = iplib.raw_input_original(':')
3244 if l == sentinel:
3245 return
3246 else:
3247 yield l
3248
3249 def _strip_pasted_lines_for_code(self, raw_lines):
3250 """ Strip non-code parts of a sequence of lines to return a block of
3251 code.
3252 """
3253 # Regular expressions that declare text we strip from the input:
3254 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3255 r'^\s*(\s?>)+', # Python input prompt
3256 r'^\s*\.{3,}', # Continuation prompts
3257 r'^\++',
3258 ]
3259
3260 strip_from_start = map(re.compile,strip_re)
3261
3262 lines = []
3263 for l in raw_lines:
3264 for pat in strip_from_start:
3265 l = pat.sub('',l)
3266 lines.append(l)
3267
3268 block = "\n".join(lines) + '\n'
3269 #print "block:\n",block
3270 return block
3271
3272 def _execute_block(self, block, par):
3273 """ Execute a block, or store it in a variable, per the user's request.
3274 """
3275 if not par:
3276 b = textwrap.dedent(block)
3277 self.user_ns['pasted_block'] = b
3278 exec b in self.user_ns
3279 else:
3280 self.user_ns[par] = SList(block.splitlines())
3281 print "Block assigned to '%s'" % par
3232
3282
3233 def magic_cpaste(self, parameter_s=''):
3283 def magic_cpaste(self, parameter_s=''):
3234 """Allows you to paste & execute a pre-formatted code block from clipboard.
3284 """Allows you to paste & execute a pre-formatted code block from clipboard.
@@ -3255,84 +3305,81 b' Defaulting color scheme to \'NoColor\'"""'
3255 will be what was just pasted.
3305 will be what was just pasted.
3256
3306
3257 IPython statements (magics, shell escapes) are not supported (yet).
3307 IPython statements (magics, shell escapes) are not supported (yet).
3308
3309 See also
3310 --------
3311 paste: automatically pull code from clipboard.
3258 """
3312 """
3313
3259 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3314 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3260 par = args.strip()
3315 par = args.strip()
3261 if opts.has_key('r'):
3316 if opts.has_key('r'):
3262 b = self.user_ns.get('pasted_block', None)
3317 self._rerun_pasted()
3263 if b is None:
3264 raise UsageError('No previous pasted block available')
3265 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3266 exec b in self.user_ns
3267 return
3318 return
3268
3319
3269 sentinel = opts.get('s','--')
3320 sentinel = opts.get('s','--')
3270
3321
3271 # Regular expressions that declare text we strip from the input:
3322 block = self._strip_pasted_lines_for_code(
3272 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3323 self._get_pasted_lines(sentinel))
3273 r'^\s*(\s?>)+', # Python input prompt
3274 r'^\s*\.{3,}', # Continuation prompts
3275 r'^\++',
3276 ]
3277
3324
3278 strip_from_start = map(re.compile,strip_re)
3325 self._execute_block(block, par)
3279
3326
3280 from IPython import iplib
3327 def magic_paste(self, parameter_s=''):
3281 lines = []
3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3282 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3283 while 1:
3284 l = iplib.raw_input_original(':')
3285 if l ==sentinel:
3286 break
3287
3288 for pat in strip_from_start:
3289 l = pat.sub('',l)
3290 lines.append(l)
3291
3292 block = "\n".join(lines) + '\n'
3293 #print "block:\n",block
3294 if not par:
3295 b = textwrap.dedent(block)
3296 self.user_ns['pasted_block'] = b
3297 exec b in self.user_ns
3298 else:
3299 self.user_ns[par] = SList(block.splitlines())
3300 print "Block assigned to '%s'" % par
3301
3302 def magic_quickref(self,arg):
3303 """ Show a quick reference sheet """
3304 import IPython.usage
3305 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3306
3329
3307 page(qr)
3330 The text is pulled directly from the clipboard without user
3331 intervention and printed back on the screen before execution (unless
3332 the -q flag is given to force quiet mode).
3333
3334 The block is dedented prior to execution to enable execution of method
3335 definitions. '>' and '+' characters at the beginning of a line are
3336 ignored, to allow pasting directly from e-mails, diff files and
3337 doctests (the '...' continuation prompt is also stripped). The
3338 executed block is also assigned to variable named 'pasted_block' for
3339 later editing with '%edit pasted_block'.
3308
3340
3309 def magic_upgrade(self,arg):
3341 You can also pass a variable name as an argument, e.g. '%paste foo'.
3310 """ Upgrade your IPython installation
3342 This assigns the pasted block to variable 'foo' as string, without
3343 dedenting or executing it (preceding >>> and + is still stripped)
3344
3345 Options
3346 -------
3311
3347
3312 This will copy the config files that don't yet exist in your
3348 -r: re-executes the block previously entered by cpaste.
3313 ipython dir from the system config dir. Use this after upgrading
3314 IPython if you don't wish to delete your .ipython dir.
3315
3349
3316 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3350 -q: quiet mode: do not echo the pasted text back to the terminal.
3317 new users)
3351
3352 IPython statements (magics, shell escapes) are not supported (yet).
3318
3353
3354 See also
3355 --------
3356 cpaste: manually paste code into terminal until you mark its end.
3319 """
3357 """
3320 ip = self.getapi()
3358 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3321 ipinstallation = path(IPython.__file__).dirname()
3359 par = args.strip()
3322 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3360 if opts.has_key('r'):
3323 src_config = ipinstallation / 'UserConfig'
3361 self._rerun_pasted()
3324 userdir = path(ip.options.ipythondir)
3362 return
3325 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3363
3326 print ">",cmd
3364 text = self.shell.hooks.clipboard_get()
3327 shell(cmd)
3365 block = self._strip_pasted_lines_for_code(text.splitlines())
3328 if arg == '-nolegacy':
3366
3329 legacy = userdir.files('ipythonrc*')
3367 # By default, echo back to terminal unless quiet mode is requested
3330 print "Nuking legacy files:",legacy
3368 if not opts.has_key('q'):
3369 write = self.shell.write
3370 write(self.shell.pycolorize(block))
3371 if not block.endswith('\n'):
3372 write('\n')
3373 write("## -- End pasted text --\n")
3331
3374
3332 [p.remove() for p in legacy]
3375 self._execute_block(block, par)
3333 suffix = (sys.platform == 'win32' and '.ini' or '')
3334 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3335
3376
3377 def magic_quickref(self,arg):
3378 """ Show a quick reference sheet """
3379 import IPython.core.usage
3380 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3381
3382 page(qr)
3336
3383
3337 def magic_doctest_mode(self,parameter_s=''):
3384 def magic_doctest_mode(self,parameter_s=''):
3338 """Toggle doctest mode on and off.
3385 """Toggle doctest mode on and off.
@@ -3354,14 +3401,11 b' Defaulting color scheme to \'NoColor\'"""'
3354 your existing IPython session.
3401 your existing IPython session.
3355 """
3402 """
3356
3403
3357 # XXX - Fix this to have cleaner activate/deactivate calls.
3404 from IPython.utils.ipstruct import Struct
3358 from IPython.Extensions import InterpreterPasteInput as ipaste
3359 from IPython.ipstruct import Struct
3360
3405
3361 # Shorthands
3406 # Shorthands
3362 shell = self.shell
3407 shell = self.shell
3363 oc = shell.outputcache
3408 oc = shell.outputcache
3364 rc = shell.rc
3365 meta = shell.meta
3409 meta = shell.meta
3366 # dstore is a data store kept in the instance metadata bag to track any
3410 # dstore is a data store kept in the instance metadata bag to track any
3367 # changes we make, so we can undo them later.
3411 # changes we make, so we can undo them later.
@@ -3370,17 +3414,15 b' Defaulting color scheme to \'NoColor\'"""'
3370
3414
3371 # save a few values we'll need to recover later
3415 # save a few values we'll need to recover later
3372 mode = save_dstore('mode',False)
3416 mode = save_dstore('mode',False)
3373 save_dstore('rc_pprint',rc.pprint)
3417 save_dstore('rc_pprint',shell.pprint)
3374 save_dstore('xmode',shell.InteractiveTB.mode)
3418 save_dstore('xmode',shell.InteractiveTB.mode)
3375 save_dstore('rc_separate_out',rc.separate_out)
3419 save_dstore('rc_separate_out',shell.separate_out)
3376 save_dstore('rc_separate_out2',rc.separate_out2)
3420 save_dstore('rc_separate_out2',shell.separate_out2)
3377 save_dstore('rc_prompts_pad_left',rc.prompts_pad_left)
3421 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3378 save_dstore('rc_separate_in',rc.separate_in)
3422 save_dstore('rc_separate_in',shell.separate_in)
3379
3423
3380 if mode == False:
3424 if mode == False:
3381 # turn on
3425 # turn on
3382 ipaste.activate_prefilter()
3383
3384 oc.prompt1.p_template = '>>> '
3426 oc.prompt1.p_template = '>>> '
3385 oc.prompt2.p_template = '... '
3427 oc.prompt2.p_template = '... '
3386 oc.prompt_out.p_template = ''
3428 oc.prompt_out.p_template = ''
@@ -3393,17 +3435,15 b' Defaulting color scheme to \'NoColor\'"""'
3393 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3435 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3394 oc.prompt_out.pad_left = False
3436 oc.prompt_out.pad_left = False
3395
3437
3396 rc.pprint = False
3438 shell.pprint = False
3397
3439
3398 shell.magic_xmode('Plain')
3440 shell.magic_xmode('Plain')
3399
3441
3400 else:
3442 else:
3401 # turn off
3443 # turn off
3402 ipaste.deactivate_prefilter()
3444 oc.prompt1.p_template = shell.prompt_in1
3403
3445 oc.prompt2.p_template = shell.prompt_in2
3404 oc.prompt1.p_template = rc.prompt_in1
3446 oc.prompt_out.p_template = shell.prompt_out
3405 oc.prompt2.p_template = rc.prompt_in2
3406 oc.prompt_out.p_template = rc.prompt_out
3407
3447
3408 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3448 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3409
3449
@@ -3413,7 +3453,7 b' Defaulting color scheme to \'NoColor\'"""'
3413 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3453 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3414 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3454 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3415
3455
3416 rc.pprint = dstore.rc_pprint
3456 shell.pprint = dstore.rc_pprint
3417
3457
3418 shell.magic_xmode(dstore.xmode)
3458 shell.magic_xmode(dstore.xmode)
3419
3459
@@ -3422,4 +3462,157 b' Defaulting color scheme to \'NoColor\'"""'
3422 print 'Doctest mode is:',
3462 print 'Doctest mode is:',
3423 print ['OFF','ON'][dstore.mode]
3463 print ['OFF','ON'][dstore.mode]
3424
3464
3465 def magic_gui(self, parameter_s=''):
3466 """Enable or disable IPython GUI event loop integration.
3467
3468 %gui [-a] [GUINAME]
3469
3470 This magic replaces IPython's threaded shells that were activated
3471 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3472 can now be enabled, disabled and swtiched at runtime and keyboard
3473 interrupts should work without any problems. The following toolkits
3474 are supported: wxPython, PyQt4, PyGTK, and Tk::
3475
3476 %gui wx # enable wxPython event loop integration
3477 %gui qt4|qt # enable PyQt4 event loop integration
3478 %gui gtk # enable PyGTK event loop integration
3479 %gui tk # enable Tk event loop integration
3480 %gui # disable all event loop integration
3481
3482 WARNING: after any of these has been called you can simply create
3483 an application object, but DO NOT start the event loop yourself, as
3484 we have already handled that.
3485
3486 If you want us to create an appropriate application object add the
3487 "-a" flag to your command::
3488
3489 %gui -a wx
3490
3491 This is highly recommended for most users.
3492 """
3493 opts, arg = self.parse_options(parameter_s,'a')
3494 if arg=='': arg = None
3495 return enable_gui(arg, 'a' in opts)
3496
3497 def magic_load_ext(self, module_str):
3498 """Load an IPython extension by its module name."""
3499 return self.load_extension(module_str)
3500
3501 def magic_unload_ext(self, module_str):
3502 """Unload an IPython extension by its module name."""
3503 self.unload_extension(module_str)
3504
3505 def magic_reload_ext(self, module_str):
3506 """Reload an IPython extension by its module name."""
3507 self.reload_extension(module_str)
3508
3509 @testdec.skip_doctest
3510 def magic_install_profiles(self, s):
3511 """Install the default IPython profiles into the .ipython dir.
3512
3513 If the default profiles have already been installed, they will not
3514 be overwritten. You can force overwriting them by using the ``-o``
3515 option::
3516
3517 In [1]: %install_profiles -o
3518 """
3519 if '-o' in s:
3520 overwrite = True
3521 else:
3522 overwrite = False
3523 from IPython.config import profile
3524 profile_dir = os.path.split(profile.__file__)[0]
3525 ipython_dir = self.ipython_dir
3526 files = os.listdir(profile_dir)
3527
3528 to_install = []
3529 for f in files:
3530 if f.startswith('ipython_config'):
3531 src = os.path.join(profile_dir, f)
3532 dst = os.path.join(ipython_dir, f)
3533 if (not os.path.isfile(dst)) or overwrite:
3534 to_install.append((f, src, dst))
3535 if len(to_install)>0:
3536 print "Installing profiles to: ", ipython_dir
3537 for (f, src, dst) in to_install:
3538 shutil.copy(src, dst)
3539 print " %s" % f
3540
3541 def magic_install_default_config(self, s):
3542 """Install IPython's default config file into the .ipython dir.
3543
3544 If the default config file (:file:`ipython_config.py`) is already
3545 installed, it will not be overwritten. You can force overwriting
3546 by using the ``-o`` option::
3547
3548 In [1]: %install_default_config
3549 """
3550 if '-o' in s:
3551 overwrite = True
3552 else:
3553 overwrite = False
3554 from IPython.config import default
3555 config_dir = os.path.split(default.__file__)[0]
3556 ipython_dir = self.ipython_dir
3557 default_config_file_name = 'ipython_config.py'
3558 src = os.path.join(config_dir, default_config_file_name)
3559 dst = os.path.join(ipython_dir, default_config_file_name)
3560 if (not os.path.isfile(dst)) or overwrite:
3561 shutil.copy(src, dst)
3562 print "Installing default config file: %s" % dst
3563
3564 # Pylab support: simple wrappers that activate pylab, load gui input
3565 # handling and modify slightly %run
3566
3567 @testdec.skip_doctest
3568 def _pylab_magic_run(self, parameter_s=''):
3569 Magic.magic_run(self, parameter_s,
3570 runner=mpl_runner(self.shell.safe_execfile))
3571
3572 _pylab_magic_run.__doc__ = magic_run.__doc__
3573
3574 @testdec.skip_doctest
3575 def magic_pylab(self, s):
3576 """Load numpy and matplotlib to work interactively.
3577
3578 %pylab [GUINAME]
3579
3580 This function lets you activate pylab (matplotlib, numpy and
3581 interactive support) at any point during an IPython session.
3582
3583 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3584 pylab and mlab, as well as all names from numpy and pylab.
3585
3586 Parameters
3587 ----------
3588 guiname : optional
3589 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3590 'tk'). If given, the corresponding Matplotlib backend is used,
3591 otherwise matplotlib's default (which you can override in your
3592 matplotlib config file) is used.
3593
3594 Examples
3595 --------
3596 In this case, where the MPL default is TkAgg:
3597 In [2]: %pylab
3598
3599 Welcome to pylab, a matplotlib-based Python environment.
3600 Backend in use: TkAgg
3601 For more information, type 'help(pylab)'.
3602
3603 But you can explicitly request a different backend:
3604 In [3]: %pylab qt
3605
3606 Welcome to pylab, a matplotlib-based Python environment.
3607 Backend in use: Qt4Agg
3608 For more information, type 'help(pylab)'.
3609 """
3610 self.shell.enable_pylab(s)
3611
3612 def magic_tb(self, s):
3613 """Print the last traceback with the currently active exception mode.
3614
3615 See %xmode for changing exception reporting modes."""
3616 self.shell.showtraceback()
3617
3425 # end Magic
3618 # end Magic
@@ -27,11 +27,13 b' import sys'
27 import types
27 import types
28
28
29 # IPython's own
29 # IPython's own
30 from IPython import PyColorize
30 from IPython.core.page import page
31 from IPython.genutils import page,indent,Term
31 from IPython.external.Itpl import itpl
32 from IPython.Itpl import itpl
32 from IPython.utils import PyColorize
33 from IPython.wildcard import list_namespace
33 from IPython.utils.io import Term
34 from IPython.ColorANSI import *
34 from IPython.utils.text import indent
35 from IPython.utils.wildcard import list_namespace
36 from IPython.utils.coloransi import *
35
37
36 #****************************************************************************
38 #****************************************************************************
37 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
39 # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We
1 NO CONTENT: file renamed from IPython/OutputTrap.py to IPython/core/outputtrap.py
NO CONTENT: file renamed from IPython/OutputTrap.py to IPython/core/outputtrap.py
1 NO CONTENT: file renamed from IPython/Prompts.py to IPython/core/prompts.py
NO CONTENT: file renamed from IPython/Prompts.py to IPython/core/prompts.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Release.py to IPython/core/release.py
NO CONTENT: file renamed from IPython/Release.py to IPython/core/release.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/shadowns.py to IPython/core/shadowns.py
NO CONTENT: file renamed from IPython/shadowns.py to IPython/core/shadowns.py
1 NO CONTENT: file renamed from IPython/tools/tests/__init__.py to IPython/core/tests/__init__.py
NO CONTENT: file renamed from IPython/tools/tests/__init__.py to IPython/core/tests/__init__.py
1 NO CONTENT: file renamed from IPython/tests/tclass.py to IPython/core/tests/tclass.py
NO CONTENT: file renamed from IPython/tests/tclass.py to IPython/core/tests/tclass.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/kernel/core/ultraTB.py to IPython/core/ultratb.py
NO CONTENT: file renamed from IPython/kernel/core/ultraTB.py to IPython/core/ultratb.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Gnuplot2.py to IPython/deathrow/Gnuplot2.py
NO CONTENT: file renamed from IPython/Gnuplot2.py to IPython/deathrow/Gnuplot2.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/GnuplotInteractive.py to IPython/deathrow/GnuplotInteractive.py
NO CONTENT: file renamed from IPython/GnuplotInteractive.py to IPython/deathrow/GnuplotInteractive.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/GnuplotRuntime.py to IPython/deathrow/GnuplotRuntime.py
NO CONTENT: file renamed from IPython/GnuplotRuntime.py to IPython/deathrow/GnuplotRuntime.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Itpl.py to IPython/deathrow/Itpl.py
NO CONTENT: file renamed from IPython/Itpl.py to IPython/deathrow/Itpl.py
1 NO CONTENT: file renamed from IPython/Extensions/PhysicalQInput.py to IPython/deathrow/PhysicalQInput.py
NO CONTENT: file renamed from IPython/Extensions/PhysicalQInput.py to IPython/deathrow/PhysicalQInput.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/PhysicalQInteractive.py to IPython/deathrow/PhysicalQInteractive.py
NO CONTENT: file renamed from IPython/Extensions/PhysicalQInteractive.py to IPython/deathrow/PhysicalQInteractive.py
1 NO CONTENT: file renamed from IPython/Extensions/astyle.py to IPython/deathrow/astyle.py
NO CONTENT: file renamed from IPython/Extensions/astyle.py to IPython/deathrow/astyle.py
1 NO CONTENT: file renamed from IPython/dtutils.py to IPython/deathrow/dtutils.py
NO CONTENT: file renamed from IPython/dtutils.py to IPython/deathrow/dtutils.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ibrowse.py to IPython/deathrow/ibrowse.py
NO CONTENT: file renamed from IPython/Extensions/ibrowse.py to IPython/deathrow/ibrowse.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/igrid.py to IPython/deathrow/igrid.py
NO CONTENT: file renamed from IPython/Extensions/igrid.py to IPython/deathrow/igrid.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/igrid_help.css to IPython/deathrow/igrid_help.css
NO CONTENT: file renamed from IPython/Extensions/igrid_help.css to IPython/deathrow/igrid_help.css
1 NO CONTENT: file renamed from IPython/Extensions/igrid_help.html to IPython/deathrow/igrid_help.html
NO CONTENT: file renamed from IPython/Extensions/igrid_help.html to IPython/deathrow/igrid_help.html
1 NO CONTENT: file renamed from IPython/Extensions/ipipe.py to IPython/deathrow/ipipe.py
NO CONTENT: file renamed from IPython/Extensions/ipipe.py to IPython/deathrow/ipipe.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_constants.py to IPython/deathrow/ipy_constants.py
NO CONTENT: file renamed from IPython/Extensions/ipy_constants.py to IPython/deathrow/ipy_constants.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_defaults.py to IPython/deathrow/ipy_defaults.py
NO CONTENT: file renamed from IPython/Extensions/ipy_defaults.py to IPython/deathrow/ipy_defaults.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_kitcfg.py to IPython/deathrow/ipy_kitcfg.py
NO CONTENT: file renamed from IPython/Extensions/ipy_kitcfg.py to IPython/deathrow/ipy_kitcfg.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_legacy.py to IPython/deathrow/ipy_legacy.py
NO CONTENT: file renamed from IPython/Extensions/ipy_legacy.py to IPython/deathrow/ipy_legacy.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_p4.py to IPython/deathrow/ipy_p4.py
NO CONTENT: file renamed from IPython/Extensions/ipy_p4.py to IPython/deathrow/ipy_p4.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_none.py to IPython/deathrow/ipy_profile_none.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_none.py to IPython/deathrow/ipy_profile_none.py
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_numpy.py to IPython/deathrow/ipy_profile_numpy.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_numpy.py to IPython/deathrow/ipy_profile_numpy.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_scipy.py to IPython/deathrow/ipy_profile_scipy.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_scipy.py to IPython/deathrow/ipy_profile_scipy.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_sh.py to IPython/deathrow/ipy_profile_sh.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_sh.py to IPython/deathrow/ipy_profile_sh.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_zope.py to IPython/deathrow/ipy_profile_zope.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_zope.py to IPython/deathrow/ipy_profile_zope.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_traits_completer.py to IPython/deathrow/ipy_traits_completer.py
NO CONTENT: file renamed from IPython/Extensions/ipy_traits_completer.py to IPython/deathrow/ipy_traits_completer.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_vimserver.py to IPython/deathrow/ipy_vimserver.py
NO CONTENT: file renamed from IPython/Extensions/ipy_vimserver.py to IPython/deathrow/ipy_vimserver.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/numeric_formats.py to IPython/deathrow/numeric_formats.py
NO CONTENT: file renamed from IPython/Extensions/numeric_formats.py to IPython/deathrow/numeric_formats.py
1 NO CONTENT: file renamed from IPython/numutils.py to IPython/deathrow/numutils.py
NO CONTENT: file renamed from IPython/numutils.py to IPython/deathrow/numutils.py
1 NO CONTENT: file renamed from IPython/Extensions/scitedirector.py to IPython/deathrow/scitedirector.py
NO CONTENT: file renamed from IPython/Extensions/scitedirector.py to IPython/deathrow/scitedirector.py
1 NO CONTENT: file renamed from IPython/twshell.py to IPython/deathrow/twshell.py
NO CONTENT: file renamed from IPython/twshell.py to IPython/deathrow/twshell.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/InterpreterPasteInput.py to IPython/extensions/InterpreterPasteInput.py
NO CONTENT: file renamed from IPython/Extensions/InterpreterPasteInput.py to IPython/extensions/InterpreterPasteInput.py
1 NO CONTENT: file renamed from IPython/Extensions/__init__.py to IPython/extensions/__init__.py
NO CONTENT: file renamed from IPython/Extensions/__init__.py to IPython/extensions/__init__.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/frontend/_process/__init__.py to IPython/frontend/process/__init__.py
NO CONTENT: file renamed from IPython/frontend/_process/__init__.py to IPython/frontend/process/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/_process/killableprocess.py to IPython/frontend/process/killableprocess.py
NO CONTENT: file renamed from IPython/frontend/_process/killableprocess.py to IPython/frontend/process/killableprocess.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/frontend/_process/pipedprocess.py to IPython/frontend/process/pipedprocess.py
NO CONTENT: file renamed from IPython/frontend/_process/pipedprocess.py to IPython/frontend/process/pipedprocess.py
1 NO CONTENT: file renamed from IPython/frontend/_process/winprocess.py to IPython/frontend/process/winprocess.py
NO CONTENT: file renamed from IPython/frontend/_process/winprocess.py to IPython/frontend/process/winprocess.py
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100755 => 100644
NO CONTENT: modified file chmod 100755 => 100644
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/background_jobs.py to IPython/lib/backgroundjobs.py
NO CONTENT: file renamed from IPython/background_jobs.py to IPython/lib/backgroundjobs.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/deep_reload.py to IPython/lib/deepreload.py
NO CONTENT: file renamed from IPython/deep_reload.py to IPython/lib/deepreload.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/demo.py to IPython/lib/demo.py
NO CONTENT: file renamed from IPython/demo.py to IPython/lib/demo.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/irunner.py to IPython/lib/irunner.py
NO CONTENT: file renamed from IPython/irunner.py to IPython/lib/irunner.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/InterpreterExec.py to IPython/quarantine/InterpreterExec.py
NO CONTENT: file renamed from IPython/Extensions/InterpreterExec.py to IPython/quarantine/InterpreterExec.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/clearcmd.py to IPython/quarantine/clearcmd.py
NO CONTENT: file renamed from IPython/Extensions/clearcmd.py to IPython/quarantine/clearcmd.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/envpersist.py to IPython/quarantine/envpersist.py
NO CONTENT: file renamed from IPython/Extensions/envpersist.py to IPython/quarantine/envpersist.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ext_rescapture.py to IPython/quarantine/ext_rescapture.py
NO CONTENT: file renamed from IPython/Extensions/ext_rescapture.py to IPython/quarantine/ext_rescapture.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_app_completers.py to IPython/quarantine/ipy_app_completers.py
NO CONTENT: file renamed from IPython/Extensions/ipy_app_completers.py to IPython/quarantine/ipy_app_completers.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_autoreload.py to IPython/quarantine/ipy_autoreload.py
NO CONTENT: file renamed from IPython/Extensions/ipy_autoreload.py to IPython/quarantine/ipy_autoreload.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_bzr.py to IPython/quarantine/ipy_bzr.py
NO CONTENT: file renamed from IPython/Extensions/ipy_bzr.py to IPython/quarantine/ipy_bzr.py
1 NO CONTENT: file renamed from IPython/Extensions/ipy_completers.py to IPython/quarantine/ipy_completers.py
NO CONTENT: file renamed from IPython/Extensions/ipy_completers.py to IPython/quarantine/ipy_completers.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_editors.py to IPython/quarantine/ipy_editors.py
NO CONTENT: file renamed from IPython/Extensions/ipy_editors.py to IPython/quarantine/ipy_editors.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_exportdb.py to IPython/quarantine/ipy_exportdb.py
NO CONTENT: file renamed from IPython/Extensions/ipy_exportdb.py to IPython/quarantine/ipy_exportdb.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_extutil.py to IPython/quarantine/ipy_extutil.py
NO CONTENT: file renamed from IPython/Extensions/ipy_extutil.py to IPython/quarantine/ipy_extutil.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_fsops.py to IPython/quarantine/ipy_fsops.py
NO CONTENT: file renamed from IPython/Extensions/ipy_fsops.py to IPython/quarantine/ipy_fsops.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_gnuglobal.py to IPython/quarantine/ipy_gnuglobal.py
NO CONTENT: file renamed from IPython/Extensions/ipy_gnuglobal.py to IPython/quarantine/ipy_gnuglobal.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_greedycompleter.py to IPython/quarantine/ipy_greedycompleter.py
NO CONTENT: file renamed from IPython/Extensions/ipy_greedycompleter.py to IPython/quarantine/ipy_greedycompleter.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_jot.py to IPython/quarantine/ipy_jot.py
NO CONTENT: file renamed from IPython/Extensions/ipy_jot.py to IPython/quarantine/ipy_jot.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_lookfor.py to IPython/quarantine/ipy_lookfor.py
NO CONTENT: file renamed from IPython/Extensions/ipy_lookfor.py to IPython/quarantine/ipy_lookfor.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_profile_doctest.py to IPython/quarantine/ipy_profile_doctest.py
NO CONTENT: file renamed from IPython/Extensions/ipy_profile_doctest.py to IPython/quarantine/ipy_profile_doctest.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_pydb.py to IPython/quarantine/ipy_pydb.py
NO CONTENT: file renamed from IPython/Extensions/ipy_pydb.py to IPython/quarantine/ipy_pydb.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_rehashdir.py to IPython/quarantine/ipy_rehashdir.py
NO CONTENT: file renamed from IPython/Extensions/ipy_rehashdir.py to IPython/quarantine/ipy_rehashdir.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_render.py to IPython/quarantine/ipy_render.py
NO CONTENT: file renamed from IPython/Extensions/ipy_render.py to IPython/quarantine/ipy_render.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_server.py to IPython/quarantine/ipy_server.py
NO CONTENT: file renamed from IPython/Extensions/ipy_server.py to IPython/quarantine/ipy_server.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_signals.py to IPython/quarantine/ipy_signals.py
NO CONTENT: file renamed from IPython/Extensions/ipy_signals.py to IPython/quarantine/ipy_signals.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_stock_completers.py to IPython/quarantine/ipy_stock_completers.py
NO CONTENT: file renamed from IPython/Extensions/ipy_stock_completers.py to IPython/quarantine/ipy_stock_completers.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_synchronize_with.py to IPython/quarantine/ipy_synchronize_with.py
NO CONTENT: file renamed from IPython/Extensions/ipy_synchronize_with.py to IPython/quarantine/ipy_synchronize_with.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_system_conf.py to IPython/quarantine/ipy_system_conf.py
NO CONTENT: file renamed from IPython/Extensions/ipy_system_conf.py to IPython/quarantine/ipy_system_conf.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_which.py to IPython/quarantine/ipy_which.py
NO CONTENT: file renamed from IPython/Extensions/ipy_which.py to IPython/quarantine/ipy_which.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_winpdb.py to IPython/quarantine/ipy_winpdb.py
NO CONTENT: file renamed from IPython/Extensions/ipy_winpdb.py to IPython/quarantine/ipy_winpdb.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ipy_workdir.py to IPython/quarantine/ipy_workdir.py
NO CONTENT: file renamed from IPython/Extensions/ipy_workdir.py to IPython/quarantine/ipy_workdir.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/jobctrl.py to IPython/quarantine/jobctrl.py
NO CONTENT: file renamed from IPython/Extensions/jobctrl.py to IPython/quarantine/jobctrl.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/ledit.py to IPython/quarantine/ledit.py
NO CONTENT: file renamed from IPython/Extensions/ledit.py to IPython/quarantine/ledit.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/pspersistence.py to IPython/quarantine/pspersistence.py
NO CONTENT: file renamed from IPython/Extensions/pspersistence.py to IPython/quarantine/pspersistence.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/win32clip.py to IPython/quarantine/win32clip.py
NO CONTENT: file renamed from IPython/Extensions/win32clip.py to IPython/quarantine/win32clip.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from scripts/ipython-wx to IPython/scripts/ipython-wx
NO CONTENT: file renamed from scripts/ipython-wx to IPython/scripts/ipython-wx
1 NO CONTENT: file renamed from scripts/ipythonx to IPython/scripts/ipythonx
NO CONTENT: file renamed from scripts/ipythonx to IPython/scripts/ipythonx
1 NO CONTENT: file renamed from scripts/irunner to IPython/scripts/irunner
NO CONTENT: file renamed from scripts/irunner to IPython/scripts/irunner
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from scripts/pycolor to IPython/scripts/pycolor
NO CONTENT: file renamed from scripts/pycolor to IPython/scripts/pycolor
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/PyColorize.py to IPython/utils/PyColorize.py
NO CONTENT: file renamed from IPython/PyColorize.py to IPython/utils/PyColorize.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/ColorANSI.py to IPython/utils/coloransi.py
NO CONTENT: file renamed from IPython/ColorANSI.py to IPython/utils/coloransi.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/tools/growl.py to IPython/utils/growl.py
NO CONTENT: file renamed from IPython/tools/growl.py to IPython/utils/growl.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/Extensions/pickleshare.py to IPython/utils/pickleshare.py
NO CONTENT: file renamed from IPython/Extensions/pickleshare.py to IPython/utils/pickleshare.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/rlineimpl.py to IPython/utils/rlineimpl.py
NO CONTENT: file renamed from IPython/rlineimpl.py to IPython/utils/rlineimpl.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/strdispatch.py to IPython/utils/strdispatch.py
NO CONTENT: file renamed from IPython/strdispatch.py to IPython/utils/strdispatch.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/tests/test_genutils.py to IPython/utils/tests/test_path.py
NO CONTENT: file renamed from IPython/tests/test_genutils.py to IPython/utils/tests/test_path.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/upgrade_dir.py to IPython/utils/upgradedir.py
NO CONTENT: file renamed from IPython/upgrade_dir.py to IPython/utils/upgradedir.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from IPython/wildcard.py to IPython/utils/wildcard.py
NO CONTENT: file renamed from IPython/wildcard.py to IPython/utils/wildcard.py
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file chmod 100644 => 100755
NO CONTENT: modified file chmod 100644 => 100755
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from debian/irunner.1 to docs/man/irunner.1
NO CONTENT: file renamed from debian/irunner.1 to docs/man/irunner.1
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from docs/source/history.txt to docs/source/about/history.txt
NO CONTENT: file renamed from docs/source/history.txt to docs/source/about/history.txt
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from docs/source/license_and_copyright.txt to docs/source/about/license_and_copyright.txt
NO CONTENT: file renamed from docs/source/license_and_copyright.txt to docs/source/about/license_and_copyright.txt
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from docs/source/config/initial_config.txt to docs/source/config/old.txt
NO CONTENT: file renamed from docs/source/config/initial_config.txt to docs/source/config/old.txt
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file renamed from docs/source/changes.txt to docs/source/whatsnew/version0.9.txt
NO CONTENT: file renamed from docs/source/changes.txt to docs/source/whatsnew/version0.9.txt
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (690 lines changed) Show them Hide them
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
This diff has been collapsed as it changes many lines, (631 lines changed) Show them Hide them
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed, binary diff hidden
NO CONTENT: file was removed, binary diff hidden
1 NO CONTENT: file was removed, binary diff hidden
NO CONTENT: file was removed, binary diff hidden
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
1 NO CONTENT: file was removed
NO CONTENT: file was removed
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now