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,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 |
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 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 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,64 +1,67 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | IPython. |
|
4 | IPython. | |
5 |
|
5 | |||
6 | IPython is a set of tools for interactive and exploratory computing in Python. |
|
6 | IPython is a set of tools for interactive and exploratory computing in Python. | |
7 | """ |
|
7 | """ | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (C) 2008-2009 The IPython Development Team |
|
10 | # Copyright (C) 2008-2009 The IPython Development Team | |
11 | # |
|
11 | # | |
12 | # 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 | |
13 | # the file COPYING, distributed as part of this software. |
|
13 | # the file COPYING, distributed as part of this software. | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Imports |
|
17 | # Imports | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
|
19 | from __future__ import absolute_import | |||
19 |
|
20 | |||
20 | import os |
|
21 | import os | |
21 | import sys |
|
22 | import sys | |
22 | from IPython.core import release |
|
|||
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Setup everything |
|
25 | # Setup everything | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 |
|
28 | if sys.version[0:3] < '2.5': | ||
29 | if sys.version[0:3] < '2.4': |
|
29 | raise ImportError('Python Version 2.5 or above is required for IPython.') | |
30 | raise ImportError('Python Version 2.4 or above is required for IPython.') |
|
|||
31 |
|
30 | |||
32 |
|
31 | |||
33 | # 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. | |
34 | # Therefore, non-IPython modules can be added to extensions directory |
|
33 | # Therefore, non-IPython modules can be added to extensions directory | |
35 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) |
|
34 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) | |
36 |
|
35 | |||
37 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
38 | # Setup the top level names |
|
37 | # Setup the top level names | |
39 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
40 |
|
39 | |||
41 | # In some cases, these are causing circular imports. |
|
40 | # In some cases, these are causing circular imports. | |
42 | from IPython.core.iplib import InteractiveShell |
|
41 | from .config.loader import Config | |
43 |
from |
|
42 | from .core import release | |
44 | from IPython.core.error import TryNext |
|
43 | from .core.application import Application | |
|
44 | from .core.ipapp import IPythonApp | |||
|
45 | from .core.embed import embed | |||
|
46 | from .core.error import TryNext | |||
|
47 | from .core.iplib import InteractiveShell | |||
|
48 | from .testing import test | |||
45 |
|
49 | |||
46 |
from |
|
50 | from .lib import ( | |
47 | enable_wx, disable_wx, |
|
51 | enable_wx, disable_wx, | |
48 | enable_gtk, disable_gtk, |
|
52 | enable_gtk, disable_gtk, | |
49 | enable_qt4, disable_qt4, |
|
53 | enable_qt4, disable_qt4, | |
50 | enable_tk, disable_tk, |
|
54 | enable_tk, disable_tk, | |
51 | set_inputhook, clear_inputhook, |
|
55 | set_inputhook, clear_inputhook, | |
52 | current_gui, spin, |
|
56 | current_gui, spin, | |
53 | appstart_qt4, appstart_wx, |
|
57 | appstart_qt4, appstart_wx, | |
54 | appstart_gtk, appstart_tk |
|
58 | appstart_gtk, appstart_tk | |
55 | ) |
|
59 | ) | |
56 |
|
60 | |||
57 | # Release data |
|
61 | # Release data | |
58 | __author__ = '' |
|
62 | __author__ = '' | |
59 | for author, email in release.authors.values(): |
|
63 | for author, email in release.authors.values(): | |
60 | __author__ += author + ' <' + email + '>\n' |
|
64 | __author__ += author + ' <' + email + '>\n' | |
61 | __license__ = release.license |
|
65 | __license__ = release.license | |
62 | __version__ = release.version |
|
66 | __version__ = release.version | |
63 | __revision__ = release.revision |
|
67 | __revision__ = release.revision | |
64 |
|
@@ -1,148 +1,148 b'' | |||||
1 | # Get the config being loaded so we can set attributes on it |
|
1 | # Get the config being loaded so we can set attributes on it | |
2 | c = get_config() |
|
2 | c = get_config() | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Global options |
|
5 | # Global options | |
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 |
|
7 | |||
8 | # c.Global.display_banner = True |
|
8 | # c.Global.display_banner = True | |
9 |
|
9 | |||
10 | # c.Global.classic = False |
|
10 | # c.Global.classic = False | |
11 |
|
11 | |||
12 | # c.Global.nosep = True |
|
12 | # c.Global.nosep = True | |
13 |
|
13 | |||
14 | # Set this to determine the detail of what is logged at startup. |
|
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. |
|
15 | # The default is 30 and possible values are 0,10,20,30,40,50. | |
16 | c.Global.log_level = 20 |
|
16 | # c.Global.log_level = 20 | |
17 |
|
17 | |||
18 | # This should be a list of importable Python modules that have an |
|
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 |
|
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 |
|
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 |
|
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. |
|
22 | # during extension loading, so you can put them there as well. | |
23 | # c.Global.extensions = [ |
|
23 | # c.Global.extensions = [ | |
24 | # 'myextension' |
|
24 | # 'myextension' | |
25 | # ] |
|
25 | # ] | |
26 |
|
26 | |||
27 | # These lines are run in IPython in the user's namespace after extensions |
|
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. |
|
28 | # are loaded. They can contain full IPython syntax with magics etc. | |
29 | # c.Global.exec_lines = [ |
|
29 | # c.Global.exec_lines = [ | |
30 | # 'import numpy', |
|
30 | # 'import numpy', | |
31 | # 'a = 10; b = 20', |
|
31 | # 'a = 10; b = 20', | |
32 | # '1/0' |
|
32 | # '1/0' | |
33 | # ] |
|
33 | # ] | |
34 |
|
34 | |||
35 | # These files are run in IPython in the user's namespace. Files with a .py |
|
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 |
|
36 | # extension need to be pure Python. Files with a .ipy extension can have | |
37 | # custom IPython syntax (like magics, etc.). |
|
37 | # custom IPython syntax (like magics, etc.). | |
38 | # These files need to be in the cwd, the ipythondir or be absolute paths. |
|
38 | # These files need to be in the cwd, the ipython_dir or be absolute paths. | |
39 | # c.Global.exec_files = [ |
|
39 | # c.Global.exec_files = [ | |
40 | # 'mycode.py', |
|
40 | # 'mycode.py', | |
41 | # 'fancy.ipy' |
|
41 | # 'fancy.ipy' | |
42 | # ] |
|
42 | # ] | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # InteractiveShell options |
|
45 | # InteractiveShell options | |
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 |
|
47 | |||
48 | # c.InteractiveShell.autocall = 1 |
|
48 | # c.InteractiveShell.autocall = 1 | |
49 |
|
49 | |||
50 | # c.InteractiveShell.autoedit_syntax = False |
|
50 | # c.InteractiveShell.autoedit_syntax = False | |
51 |
|
51 | |||
52 | # c.InteractiveShell.autoindent = True |
|
52 | # c.InteractiveShell.autoindent = True | |
53 |
|
53 | |||
54 | # c.InteractiveShell.automagic = False |
|
54 | # c.InteractiveShell.automagic = False | |
55 |
|
55 | |||
56 | # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner' |
|
56 | # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner' | |
57 |
|
57 | |||
58 | # c.InteractiveShell.banner2 = "This is for extra banner text" |
|
58 | # c.InteractiveShell.banner2 = "This is for extra banner text" | |
59 |
|
59 | |||
60 | # c.InteractiveShell.cache_size = 1000 |
|
60 | # c.InteractiveShell.cache_size = 1000 | |
61 |
|
61 | |||
62 | # c.InteractiveShell.colors = 'LightBG' |
|
62 | # c.InteractiveShell.colors = 'LightBG' | |
63 |
|
63 | |||
64 | # c.InteractiveShell.color_info = True |
|
64 | # c.InteractiveShell.color_info = True | |
65 |
|
65 | |||
66 | # c.InteractiveShell.confirm_exit = True |
|
66 | # c.InteractiveShell.confirm_exit = True | |
67 |
|
67 | |||
68 | # c.InteractiveShell.deep_reload = False |
|
68 | # c.InteractiveShell.deep_reload = False | |
69 |
|
69 | |||
70 | # c.InteractiveShell.editor = 'nano' |
|
70 | # c.InteractiveShell.editor = 'nano' | |
71 |
|
71 | |||
72 | # c.InteractiveShell.logstart = True |
|
72 | # c.InteractiveShell.logstart = True | |
73 |
|
73 | |||
74 | # c.InteractiveShell.logfile = 'ipython_log.py' |
|
74 | # c.InteractiveShell.logfile = u'ipython_log.py' | |
75 |
|
75 | |||
76 | # c.InteractiveShell.logappend = 'mylog.py' |
|
76 | # c.InteractiveShell.logappend = u'mylog.py' | |
77 |
|
77 | |||
78 | # c.InteractiveShell.object_info_string_level = 0 |
|
78 | # c.InteractiveShell.object_info_string_level = 0 | |
79 |
|
79 | |||
80 | # c.InteractiveShell.pager = 'less' |
|
80 | # c.InteractiveShell.pager = 'less' | |
81 |
|
81 | |||
82 | # c.InteractiveShell.pdb = False |
|
82 | # c.InteractiveShell.pdb = False | |
83 |
|
83 | |||
84 | # c.InteractiveShell.pprint = True |
|
84 | # c.InteractiveShell.pprint = True | |
85 |
|
85 | |||
86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' |
|
86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' | |
87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' |
|
87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' | |
88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' |
|
88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' | |
89 | # c.InteractiveShell.prompts_pad_left = True |
|
89 | # c.InteractiveShell.prompts_pad_left = True | |
90 |
|
90 | |||
91 | # c.InteractiveShell.quiet = False |
|
91 | # c.InteractiveShell.quiet = False | |
92 |
|
92 | |||
93 | # Readline |
|
93 | # Readline | |
94 | # c.InteractiveShell.readline_use = True |
|
94 | # c.InteractiveShell.readline_use = True | |
95 |
|
95 | |||
96 | # c.InteractiveShell.readline_parse_and_bind = [ |
|
96 | # c.InteractiveShell.readline_parse_and_bind = [ | |
97 | # 'tab: complete', |
|
97 | # 'tab: complete', | |
98 | # '"\C-l": possible-completions', |
|
98 | # '"\C-l": possible-completions', | |
99 | # 'set show-all-if-ambiguous on', |
|
99 | # 'set show-all-if-ambiguous on', | |
100 | # '"\C-o": tab-insert', |
|
100 | # '"\C-o": tab-insert', | |
101 | # '"\M-i": " "', |
|
101 | # '"\M-i": " "', | |
102 | # '"\M-o": "\d\d\d\d"', |
|
102 | # '"\M-o": "\d\d\d\d"', | |
103 | # '"\M-I": "\d\d\d\d"', |
|
103 | # '"\M-I": "\d\d\d\d"', | |
104 | # '"\C-r": reverse-search-history', |
|
104 | # '"\C-r": reverse-search-history', | |
105 | # '"\C-s": forward-search-history', |
|
105 | # '"\C-s": forward-search-history', | |
106 | # '"\C-p": history-search-backward', |
|
106 | # '"\C-p": history-search-backward', | |
107 | # '"\C-n": history-search-forward', |
|
107 | # '"\C-n": history-search-forward', | |
108 | # '"\e[A": history-search-backward', |
|
108 | # '"\e[A": history-search-backward', | |
109 | # '"\e[B": history-search-forward', |
|
109 | # '"\e[B": history-search-forward', | |
110 | # '"\C-k": kill-line', |
|
110 | # '"\C-k": kill-line', | |
111 | # '"\C-u": unix-line-discard', |
|
111 | # '"\C-u": unix-line-discard', | |
112 | # ] |
|
112 | # ] | |
113 | # c.InteractiveShell.readline_remove_delims = '-/~' |
|
113 | # c.InteractiveShell.readline_remove_delims = '-/~' | |
114 | # c.InteractiveShell.readline_merge_completions = True |
|
114 | # c.InteractiveShell.readline_merge_completions = True | |
115 | # c.InteractiveShell.readline_omit_names = 0 |
|
115 | # c.InteractiveShell.readline_omit_names = 0 | |
116 |
|
116 | |||
117 | # c.InteractiveShell.screen_length = 0 |
|
117 | # c.InteractiveShell.screen_length = 0 | |
118 |
|
118 | |||
119 | # c.InteractiveShell.separate_in = '\n' |
|
119 | # c.InteractiveShell.separate_in = '\n' | |
120 | # c.InteractiveShell.separate_out = '' |
|
120 | # c.InteractiveShell.separate_out = '' | |
121 | # c.InteractiveShell.separate_out2 = '' |
|
121 | # c.InteractiveShell.separate_out2 = '' | |
122 |
|
122 | |||
123 | # c.InteractiveShell.system_header = "IPython system call: " |
|
123 | # c.InteractiveShell.system_header = "IPython system call: " | |
124 |
|
124 | |||
125 | # c.InteractiveShell.system_verbose = True |
|
125 | # c.InteractiveShell.system_verbose = True | |
126 |
|
126 | |||
127 | # c.InteractiveShell.term_title = False |
|
127 | # c.InteractiveShell.term_title = False | |
128 |
|
128 | |||
129 | # c.InteractiveShell.wildcards_case_sensitive = True |
|
129 | # c.InteractiveShell.wildcards_case_sensitive = True | |
130 |
|
130 | |||
131 | # c.InteractiveShell.xmode = 'Context' |
|
131 | # c.InteractiveShell.xmode = 'Context' | |
132 |
|
132 | |||
133 | #----------------------------------------------------------------------------- |
|
133 | #----------------------------------------------------------------------------- | |
134 | # PrefilterManager options |
|
134 | # PrefilterManager options | |
135 | #----------------------------------------------------------------------------- |
|
135 | #----------------------------------------------------------------------------- | |
136 |
|
136 | |||
137 | # c.PrefilterManager.multi_line_specials = True |
|
137 | # c.PrefilterManager.multi_line_specials = True | |
138 |
|
138 | |||
139 | #----------------------------------------------------------------------------- |
|
139 | #----------------------------------------------------------------------------- | |
140 | # AliasManager options |
|
140 | # AliasManager options | |
141 | #----------------------------------------------------------------------------- |
|
141 | #----------------------------------------------------------------------------- | |
142 |
|
142 | |||
143 | # Do this to disable all defaults |
|
143 | # Do this to disable all defaults | |
144 | # c.AliasManager.default_aliases = [] |
|
144 | # c.AliasManager.default_aliases = [] | |
145 |
|
145 | |||
146 | # c.AliasManager.user_aliases = [ |
|
146 | # c.AliasManager.user_aliases = [ | |
147 | # ('foo', 'echo Hi') |
|
147 | # ('foo', 'echo Hi') | |
148 | # ] No newline at end of file |
|
148 | # ] |
@@ -1,329 +1,377 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | # coding: utf-8 | |
2 | # encoding: utf-8 |
|
|||
3 | """A simple configuration system. |
|
2 | """A simple configuration system. | |
4 |
|
3 | |||
5 |
Authors |
|
4 | Authors | |
6 |
|
5 | ------- | ||
7 | * Brian Granger |
|
6 | * Brian Granger | |
|
7 | * Fernando Perez | |||
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | # Copyright (C) 2008-2009 The IPython Development Team | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Imports |
|
18 | # Imports | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | import __builtin__ |
|
21 | import __builtin__ | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 |
|
24 | |||
25 | from IPython.external import argparse |
|
25 | from IPython.external import argparse | |
26 | from IPython.utils.genutils import filefind |
|
26 | from IPython.utils.genutils import filefind | |
27 |
|
27 | |||
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 | # Exceptions |
|
29 | # Exceptions | |
30 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 |
|
32 | |||
33 | class ConfigError(Exception): |
|
33 | class ConfigError(Exception): | |
34 | pass |
|
34 | pass | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | class ConfigLoaderError(ConfigError): |
|
37 | class ConfigLoaderError(ConfigError): | |
38 | pass |
|
38 | pass | |
39 |
|
39 | |||
40 |
|
40 | #----------------------------------------------------------------------------- | ||
|
41 | # Argparse fix | |||
|
42 | #----------------------------------------------------------------------------- | |||
|
43 | # Unfortunately argparse by default prints help messages to stderr instead of | |||
|
44 | # stdout. This makes it annoying to capture long help screens at the command | |||
|
45 | # line, since one must know how to pipe stderr, which many users don't know how | |||
|
46 | # to do. So we override the print_help method with one that defaults to | |||
|
47 | # stdout and use our class instead. | |||
|
48 | ||||
|
49 | class ArgumentParser(argparse.ArgumentParser): | |||
|
50 | """Simple argparse subclass that prints help to stdout by default.""" | |||
|
51 | ||||
|
52 | def print_help(self, file=None): | |||
|
53 | if file is None: | |||
|
54 | file = sys.stdout | |||
|
55 | return super(ArgumentParser, self).print_help(file) | |||
|
56 | ||||
|
57 | print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__ | |||
|
58 | ||||
41 | #----------------------------------------------------------------------------- |
|
59 | #----------------------------------------------------------------------------- | |
42 | # Config class for holding config information |
|
60 | # Config class for holding config information | |
43 | #----------------------------------------------------------------------------- |
|
61 | #----------------------------------------------------------------------------- | |
44 |
|
62 | |||
45 |
|
63 | |||
46 | class Config(dict): |
|
64 | class Config(dict): | |
47 | """An attribute based dict that can do smart merges.""" |
|
65 | """An attribute based dict that can do smart merges.""" | |
48 |
|
66 | |||
49 | def __init__(self, *args, **kwds): |
|
67 | def __init__(self, *args, **kwds): | |
50 | dict.__init__(self, *args, **kwds) |
|
68 | dict.__init__(self, *args, **kwds) | |
51 | # This sets self.__dict__ = self, but it has to be done this way |
|
69 | # This sets self.__dict__ = self, but it has to be done this way | |
52 | # because we are also overriding __setattr__. |
|
70 | # because we are also overriding __setattr__. | |
53 | dict.__setattr__(self, '__dict__', self) |
|
71 | dict.__setattr__(self, '__dict__', self) | |
54 |
|
72 | |||
55 | def _merge(self, other): |
|
73 | def _merge(self, other): | |
56 | to_update = {} |
|
74 | to_update = {} | |
57 | for k, v in other.items(): |
|
75 | for k, v in other.items(): | |
58 | if not self.has_key(k): |
|
76 | if not self.has_key(k): | |
59 | to_update[k] = v |
|
77 | to_update[k] = v | |
60 | else: # I have this key |
|
78 | else: # I have this key | |
61 | if isinstance(v, Config): |
|
79 | if isinstance(v, Config): | |
62 | # Recursively merge common sub Configs |
|
80 | # Recursively merge common sub Configs | |
63 | self[k]._merge(v) |
|
81 | self[k]._merge(v) | |
64 | else: |
|
82 | else: | |
65 | # Plain updates for non-Configs |
|
83 | # Plain updates for non-Configs | |
66 | to_update[k] = v |
|
84 | to_update[k] = v | |
67 |
|
85 | |||
68 | self.update(to_update) |
|
86 | self.update(to_update) | |
69 |
|
87 | |||
70 | def _is_section_key(self, key): |
|
88 | def _is_section_key(self, key): | |
71 | if key[0].upper()==key[0] and not key.startswith('_'): |
|
89 | if key[0].upper()==key[0] and not key.startswith('_'): | |
72 | return True |
|
90 | return True | |
73 | else: |
|
91 | else: | |
74 | return False |
|
92 | return False | |
75 |
|
93 | |||
76 | def has_key(self, key): |
|
94 | def has_key(self, key): | |
77 | if self._is_section_key(key): |
|
95 | if self._is_section_key(key): | |
78 | return True |
|
96 | return True | |
79 | else: |
|
97 | else: | |
80 | return dict.has_key(self, key) |
|
98 | return dict.has_key(self, key) | |
81 |
|
99 | |||
82 | def _has_section(self, key): |
|
100 | def _has_section(self, key): | |
83 | if self._is_section_key(key): |
|
101 | if self._is_section_key(key): | |
84 | if dict.has_key(self, key): |
|
102 | if dict.has_key(self, key): | |
85 | return True |
|
103 | return True | |
86 | return False |
|
104 | return False | |
87 |
|
105 | |||
88 | def copy(self): |
|
106 | def copy(self): | |
89 | return type(self)(dict.copy(self)) |
|
107 | return type(self)(dict.copy(self)) | |
90 |
|
108 | |||
91 | def __copy__(self): |
|
109 | def __copy__(self): | |
92 | return self.copy() |
|
110 | return self.copy() | |
93 |
|
111 | |||
94 | def __deepcopy__(self, memo): |
|
112 | def __deepcopy__(self, memo): | |
95 | import copy |
|
113 | import copy | |
96 | return type(self)(copy.deepcopy(self.items())) |
|
114 | return type(self)(copy.deepcopy(self.items())) | |
97 |
|
115 | |||
98 | def __getitem__(self, key): |
|
116 | def __getitem__(self, key): | |
99 | # Because we use this for an exec namespace, we need to delegate |
|
117 | # Because we use this for an exec namespace, we need to delegate | |
100 | # the lookup of names in __builtin__ to itself. This means |
|
118 | # the lookup of names in __builtin__ to itself. This means | |
101 | # that you can't have section or attribute names that are |
|
119 | # that you can't have section or attribute names that are | |
102 | # builtins. |
|
120 | # builtins. | |
103 | try: |
|
121 | try: | |
104 | return getattr(__builtin__, key) |
|
122 | return getattr(__builtin__, key) | |
105 | except AttributeError: |
|
123 | except AttributeError: | |
106 | pass |
|
124 | pass | |
107 | if self._is_section_key(key): |
|
125 | if self._is_section_key(key): | |
108 | try: |
|
126 | try: | |
109 | return dict.__getitem__(self, key) |
|
127 | return dict.__getitem__(self, key) | |
110 | except KeyError: |
|
128 | except KeyError: | |
111 | c = Config() |
|
129 | c = Config() | |
112 | dict.__setitem__(self, key, c) |
|
130 | dict.__setitem__(self, key, c) | |
113 | return c |
|
131 | return c | |
114 | else: |
|
132 | else: | |
115 | return dict.__getitem__(self, key) |
|
133 | return dict.__getitem__(self, key) | |
116 |
|
134 | |||
117 | def __setitem__(self, key, value): |
|
135 | def __setitem__(self, key, value): | |
118 | # Don't allow names in __builtin__ to be modified. |
|
136 | # Don't allow names in __builtin__ to be modified. | |
119 | if hasattr(__builtin__, key): |
|
137 | if hasattr(__builtin__, key): | |
120 | raise ConfigError('Config variable names cannot have the same name ' |
|
138 | raise ConfigError('Config variable names cannot have the same name ' | |
121 | 'as a Python builtin: %s' % key) |
|
139 | 'as a Python builtin: %s' % key) | |
122 | if self._is_section_key(key): |
|
140 | if self._is_section_key(key): | |
123 | if not isinstance(value, Config): |
|
141 | if not isinstance(value, Config): | |
124 | raise ValueError('values whose keys begin with an uppercase ' |
|
142 | raise ValueError('values whose keys begin with an uppercase ' | |
125 | 'char must be Config instances: %r, %r' % (key, value)) |
|
143 | 'char must be Config instances: %r, %r' % (key, value)) | |
126 | else: |
|
144 | else: | |
127 | dict.__setitem__(self, key, value) |
|
145 | dict.__setitem__(self, key, value) | |
128 |
|
146 | |||
129 | def __getattr__(self, key): |
|
147 | def __getattr__(self, key): | |
130 | try: |
|
148 | try: | |
131 | return self.__getitem__(key) |
|
149 | return self.__getitem__(key) | |
132 | except KeyError, e: |
|
150 | except KeyError, e: | |
133 | raise AttributeError(e) |
|
151 | raise AttributeError(e) | |
134 |
|
152 | |||
135 | def __setattr__(self, key, value): |
|
153 | def __setattr__(self, key, value): | |
136 | try: |
|
154 | try: | |
137 | self.__setitem__(key, value) |
|
155 | self.__setitem__(key, value) | |
138 | except KeyError, e: |
|
156 | except KeyError, e: | |
139 | raise AttributeError(e) |
|
157 | raise AttributeError(e) | |
140 |
|
158 | |||
141 | def __delattr__(self, key): |
|
159 | def __delattr__(self, key): | |
142 | try: |
|
160 | try: | |
143 | dict.__delitem__(self, key) |
|
161 | dict.__delitem__(self, key) | |
144 | except KeyError, e: |
|
162 | except KeyError, e: | |
145 | raise AttributeError(e) |
|
163 | raise AttributeError(e) | |
146 |
|
164 | |||
147 |
|
165 | |||
148 | #----------------------------------------------------------------------------- |
|
166 | #----------------------------------------------------------------------------- | |
149 | # Config loading classes |
|
167 | # Config loading classes | |
150 | #----------------------------------------------------------------------------- |
|
168 | #----------------------------------------------------------------------------- | |
151 |
|
169 | |||
152 |
|
170 | |||
153 | class ConfigLoader(object): |
|
171 | class ConfigLoader(object): | |
154 | """A object for loading configurations from just about anywhere. |
|
172 | """A object for loading configurations from just about anywhere. | |
155 |
|
173 | |||
156 | The resulting configuration is packaged as a :class:`Struct`. |
|
174 | The resulting configuration is packaged as a :class:`Struct`. | |
157 |
|
175 | |||
158 | Notes |
|
176 | Notes | |
159 | ----- |
|
177 | ----- | |
160 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
178 | A :class:`ConfigLoader` does one thing: load a config from a source | |
161 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
179 | (file, command line arguments) and returns the data as a :class:`Struct`. | |
162 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
180 | There are lots of things that :class:`ConfigLoader` does not do. It does | |
163 | not implement complex logic for finding config files. It does not handle |
|
181 | not implement complex logic for finding config files. It does not handle | |
164 | default values or merge multiple configs. These things need to be |
|
182 | default values or merge multiple configs. These things need to be | |
165 | handled elsewhere. |
|
183 | handled elsewhere. | |
166 | """ |
|
184 | """ | |
167 |
|
185 | |||
168 | def __init__(self): |
|
186 | def __init__(self): | |
169 | """A base class for config loaders. |
|
187 | """A base class for config loaders. | |
170 |
|
188 | |||
171 | Examples |
|
189 | Examples | |
172 | -------- |
|
190 | -------- | |
173 |
|
191 | |||
174 | >>> cl = ConfigLoader() |
|
192 | >>> cl = ConfigLoader() | |
175 | >>> config = cl.load_config() |
|
193 | >>> config = cl.load_config() | |
176 | >>> config |
|
194 | >>> config | |
177 | {} |
|
195 | {} | |
178 | """ |
|
196 | """ | |
179 | self.clear() |
|
197 | self.clear() | |
180 |
|
198 | |||
181 | def clear(self): |
|
199 | def clear(self): | |
182 | self.config = Config() |
|
200 | self.config = Config() | |
183 |
|
201 | |||
184 | def load_config(self): |
|
202 | def load_config(self): | |
185 | """Load a config from somewhere, return a Struct. |
|
203 | """Load a config from somewhere, return a Struct. | |
186 |
|
204 | |||
187 | Usually, this will cause self.config to be set and then returned. |
|
205 | Usually, this will cause self.config to be set and then returned. | |
188 | """ |
|
206 | """ | |
189 | return self.config |
|
207 | return self.config | |
190 |
|
208 | |||
191 |
|
209 | |||
192 | class FileConfigLoader(ConfigLoader): |
|
210 | class FileConfigLoader(ConfigLoader): | |
193 | """A base class for file based configurations. |
|
211 | """A base class for file based configurations. | |
194 |
|
212 | |||
195 | As we add more file based config loaders, the common logic should go |
|
213 | As we add more file based config loaders, the common logic should go | |
196 | here. |
|
214 | here. | |
197 | """ |
|
215 | """ | |
198 | pass |
|
216 | pass | |
199 |
|
217 | |||
200 |
|
218 | |||
201 | class PyFileConfigLoader(FileConfigLoader): |
|
219 | class PyFileConfigLoader(FileConfigLoader): | |
202 | """A config loader for pure python files. |
|
220 | """A config loader for pure python files. | |
203 |
|
221 | |||
204 | This calls execfile on a plain python file and looks for attributes |
|
222 | This calls execfile on a plain python file and looks for attributes | |
205 | that are all caps. These attribute are added to the config Struct. |
|
223 | that are all caps. These attribute are added to the config Struct. | |
206 | """ |
|
224 | """ | |
207 |
|
225 | |||
208 | def __init__(self, filename, path=None): |
|
226 | def __init__(self, filename, path=None): | |
209 | """Build a config loader for a filename and path. |
|
227 | """Build a config loader for a filename and path. | |
210 |
|
228 | |||
211 | Parameters |
|
229 | Parameters | |
212 | ---------- |
|
230 | ---------- | |
213 | filename : str |
|
231 | filename : str | |
214 | The file name of the config file. |
|
232 | The file name of the config file. | |
215 | path : str, list, tuple |
|
233 | path : str, list, tuple | |
216 | The path to search for the config file on, or a sequence of |
|
234 | The path to search for the config file on, or a sequence of | |
217 | paths to try in order. |
|
235 | paths to try in order. | |
218 | """ |
|
236 | """ | |
219 | super(PyFileConfigLoader, self).__init__() |
|
237 | super(PyFileConfigLoader, self).__init__() | |
220 | self.filename = filename |
|
238 | self.filename = filename | |
221 | self.path = path |
|
239 | self.path = path | |
222 | self.full_filename = '' |
|
240 | self.full_filename = '' | |
223 | self.data = None |
|
241 | self.data = None | |
224 |
|
242 | |||
225 | def load_config(self): |
|
243 | def load_config(self): | |
226 | """Load the config from a file and return it as a Struct.""" |
|
244 | """Load the config from a file and return it as a Struct.""" | |
227 | self._find_file() |
|
245 | self._find_file() | |
228 | self._read_file_as_dict() |
|
246 | self._read_file_as_dict() | |
229 | self._convert_to_config() |
|
247 | self._convert_to_config() | |
230 | return self.config |
|
248 | return self.config | |
231 |
|
249 | |||
232 | def _find_file(self): |
|
250 | def _find_file(self): | |
233 | """Try to find the file by searching the paths.""" |
|
251 | """Try to find the file by searching the paths.""" | |
234 | self.full_filename = filefind(self.filename, self.path) |
|
252 | self.full_filename = filefind(self.filename, self.path) | |
235 |
|
253 | |||
236 | def _read_file_as_dict(self): |
|
254 | def _read_file_as_dict(self): | |
237 | """Load the config file into self.config, with recursive loading.""" |
|
255 | """Load the config file into self.config, with recursive loading.""" | |
238 | # This closure is made available in the namespace that is used |
|
256 | # This closure is made available in the namespace that is used | |
239 | # to exec the config file. This allows users to call |
|
257 | # to exec the config file. This allows users to call | |
240 | # load_subconfig('myconfig.py') to load config files recursively. |
|
258 | # load_subconfig('myconfig.py') to load config files recursively. | |
241 | # It needs to be a closure because it has references to self.path |
|
259 | # It needs to be a closure because it has references to self.path | |
242 | # and self.config. The sub-config is loaded with the same path |
|
260 | # and self.config. The sub-config is loaded with the same path | |
243 | # as the parent, but it uses an empty config which is then merged |
|
261 | # as the parent, but it uses an empty config which is then merged | |
244 | # with the parents. |
|
262 | # with the parents. | |
245 | def load_subconfig(fname): |
|
263 | def load_subconfig(fname): | |
246 | loader = PyFileConfigLoader(fname, self.path) |
|
264 | loader = PyFileConfigLoader(fname, self.path) | |
247 | sub_config = loader.load_config() |
|
265 | try: | |
248 | self.config._merge(sub_config) |
|
266 | sub_config = loader.load_config() | |
|
267 | except IOError: | |||
|
268 | # Pass silently if the sub config is not there. This happens | |||
|
269 | # when a user us using a profile, but not the default config. | |||
|
270 | pass | |||
|
271 | else: | |||
|
272 | self.config._merge(sub_config) | |||
249 |
|
273 | |||
250 | # Again, this needs to be a closure and should be used in config |
|
274 | # Again, this needs to be a closure and should be used in config | |
251 | # files to get the config being loaded. |
|
275 | # files to get the config being loaded. | |
252 | def get_config(): |
|
276 | def get_config(): | |
253 | return self.config |
|
277 | return self.config | |
254 |
|
278 | |||
255 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) |
|
279 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) | |
256 | execfile(self.full_filename, namespace) |
|
280 | execfile(self.full_filename, namespace) | |
257 |
|
281 | |||
258 | def _convert_to_config(self): |
|
282 | def _convert_to_config(self): | |
259 | if self.data is None: |
|
283 | if self.data is None: | |
260 | ConfigLoaderError('self.data does not exist') |
|
284 | ConfigLoaderError('self.data does not exist') | |
261 |
|
285 | |||
262 |
|
286 | |||
263 | class CommandLineConfigLoader(ConfigLoader): |
|
287 | class CommandLineConfigLoader(ConfigLoader): | |
264 | """A config loader for command line arguments. |
|
288 | """A config loader for command line arguments. | |
265 |
|
289 | |||
266 | As we add more command line based loaders, the common logic should go |
|
290 | As we add more command line based loaders, the common logic should go | |
267 | here. |
|
291 | here. | |
268 | """ |
|
292 | """ | |
269 |
|
293 | |||
270 |
|
294 | |||
271 | class NoConfigDefault(object): pass |
|
295 | class __NoConfigDefault(object): pass | |
272 | NoConfigDefault = NoConfigDefault() |
|
296 | NoConfigDefault = __NoConfigDefault() | |
|
297 | ||||
273 |
|
298 | |||
274 | class ArgParseConfigLoader(CommandLineConfigLoader): |
|
299 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
|
300 | #: Global default for arguments (see argparse docs for details) | |||
|
301 | argument_default = NoConfigDefault | |||
275 |
|
302 | |||
276 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] |
|
303 | def __init__(self, argv=None, arguments=(), *args, **kw): | |
277 | arguments = () |
|
|||
278 |
|
||||
279 | def __init__(self, *args, **kw): |
|
|||
280 | """Create a config loader for use with argparse. |
|
304 | """Create a config loader for use with argparse. | |
281 |
|
305 | |||
282 | The args and kwargs arguments here are passed onto the constructor |
|
306 | With the exception of ``argv`` and ``arguments``, other args and kwargs | |
283 | of :class:`argparse.ArgumentParser`. |
|
307 | arguments here are passed onto the constructor of | |
|
308 | :class:`argparse.ArgumentParser`. | |||
|
309 | ||||
|
310 | Parameters | |||
|
311 | ---------- | |||
|
312 | ||||
|
313 | argv : optional, list | |||
|
314 | If given, used to read command-line arguments from, otherwise | |||
|
315 | sys.argv[1:] is used. | |||
|
316 | ||||
|
317 | arguments : optional, tuple | |||
|
318 | Description of valid command-line arguments, to be called in sequence | |||
|
319 | with parser.add_argument() to configure the parser. | |||
284 | """ |
|
320 | """ | |
285 | super(CommandLineConfigLoader, self).__init__() |
|
321 | super(CommandLineConfigLoader, self).__init__() | |
|
322 | if argv == None: | |||
|
323 | argv = sys.argv[1:] | |||
|
324 | self.argv = argv | |||
|
325 | self.arguments = arguments | |||
286 | self.args = args |
|
326 | self.args = args | |
287 | self.kw = kw |
|
327 | kwargs = dict(argument_default=self.argument_default) | |
|
328 | kwargs.update(kw) | |||
|
329 | self.kw = kwargs | |||
288 |
|
330 | |||
289 | def load_config(self, args=None): |
|
331 | def load_config(self, args=None): | |
290 |
"""Parse command line arguments and return as a Struct. |
|
332 | """Parse command line arguments and return as a Struct. | |
|
333 | ||||
|
334 | Parameters | |||
|
335 | ---------- | |||
|
336 | ||||
|
337 | args : optional, list | |||
|
338 | If given, a list with the structure of sys.argv[1:] to parse arguments | |||
|
339 | from. If not given, the instance's self.argv attribute (given at | |||
|
340 | construction time) is used.""" | |||
|
341 | ||||
|
342 | if args is None: | |||
|
343 | args = self.argv | |||
291 | self._create_parser() |
|
344 | self._create_parser() | |
292 | self._parse_args(args) |
|
345 | self._parse_args(args) | |
293 | self._convert_to_config() |
|
346 | self._convert_to_config() | |
294 | return self.config |
|
347 | return self.config | |
295 |
|
348 | |||
296 | def get_extra_args(self): |
|
349 | def get_extra_args(self): | |
297 | if hasattr(self, 'extra_args'): |
|
350 | if hasattr(self, 'extra_args'): | |
298 | return self.extra_args |
|
351 | return self.extra_args | |
299 | else: |
|
352 | else: | |
300 | return [] |
|
353 | return [] | |
301 |
|
354 | |||
302 | def _create_parser(self): |
|
355 | def _create_parser(self): | |
303 |
self.parser = |
|
356 | self.parser = ArgumentParser(*self.args, **self.kw) | |
304 | self._add_arguments() |
|
357 | self._add_arguments() | |
305 | self._add_other_arguments() |
|
358 | self._add_other_arguments() | |
306 |
|
359 | |||
307 | def _add_other_arguments(self): |
|
|||
308 | pass |
|
|||
309 |
|
||||
310 | def _add_arguments(self): |
|
360 | def _add_arguments(self): | |
311 | for argument in self.arguments: |
|
361 | for argument in self.arguments: | |
312 | if not argument[1].has_key('default'): |
|
|||
313 | argument[1]['default'] = NoConfigDefault |
|
|||
314 | self.parser.add_argument(*argument[0],**argument[1]) |
|
362 | self.parser.add_argument(*argument[0],**argument[1]) | |
315 |
|
363 | |||
316 |
def _ |
|
364 | def _add_other_arguments(self): | |
317 | """self.parser->self.parsed_data""" |
|
365 | """Meant for subclasses to add their own arguments.""" | |
318 |
|
|
366 | pass | |
319 | self.parsed_data, self.extra_args = self.parser.parse_known_args() |
|
367 | ||
320 | else: |
|
368 | def _parse_args(self, args): | |
321 | self.parsed_data, self.extra_args = self.parser.parse_known_args(args) |
|
369 | """self.parser->self.parsed_data""" | |
|
370 | self.parsed_data, self.extra_args = self.parser.parse_known_args(args) | |||
322 |
|
371 | |||
323 | def _convert_to_config(self): |
|
372 | def _convert_to_config(self): | |
324 | """self.parsed_data->self.config""" |
|
373 | """self.parsed_data->self.config""" | |
325 | for k, v in vars(self.parsed_data).items(): |
|
374 | for k, v in vars(self.parsed_data).items(): | |
326 | if v is not NoConfigDefault: |
|
375 | if v is not NoConfigDefault: | |
327 | exec_str = 'self.config.' + k + '= v' |
|
376 | exec_str = 'self.config.' + k + '= v' | |
328 | exec exec_str in locals(), globals() |
|
377 | exec exec_str in locals(), globals() | |
329 |
|
1 | NO CONTENT: file renamed from IPython/config/profile/__init_.py to IPython/config/profile/__init__.py |
|
NO CONTENT: file renamed from IPython/config/profile/__init_.py to IPython/config/profile/__init__.py |
@@ -1,163 +1,162 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | Tests for IPython.config.loader |
|
4 | Tests for IPython.config.loader | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez (design help) |
|
9 | * Fernando Perez (design help) | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | import os |
|
23 | import os | |
24 | from tempfile import mkstemp |
|
24 | from tempfile import mkstemp | |
25 | from unittest import TestCase |
|
25 | from unittest import TestCase | |
26 |
|
26 | |||
27 | from IPython.config.loader import ( |
|
27 | from IPython.config.loader import ( | |
28 | Config, |
|
28 | Config, | |
29 | PyFileConfigLoader, |
|
29 | PyFileConfigLoader, | |
30 | ArgParseConfigLoader, |
|
30 | ArgParseConfigLoader, | |
31 | ConfigError |
|
31 | ConfigError | |
32 | ) |
|
32 | ) | |
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Actual tests |
|
35 | # Actual tests | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | pyfile = """ |
|
39 | pyfile = """ | |
40 | a = 10 |
|
40 | c = get_config() | |
41 | b = 20 |
|
41 | c.a = 10 | |
42 | Foo.Bar.value = 10 |
|
42 | c.b = 20 | |
43 |
Foo.Ba |
|
43 | c.Foo.Bar.value = 10 | |
44 | D.C.value = 'hi there' |
|
44 | c.Foo.Bam.value = range(10) | |
|
45 | c.D.C.value = 'hi there' | |||
45 | """ |
|
46 | """ | |
46 |
|
47 | |||
47 | class TestPyFileCL(TestCase): |
|
48 | class TestPyFileCL(TestCase): | |
48 |
|
49 | |||
49 | def test_basic(self): |
|
50 | def test_basic(self): | |
50 | fd, fname = mkstemp() |
|
51 | fd, fname = mkstemp('.py') | |
51 | f = os.fdopen(fd, 'w') |
|
52 | f = os.fdopen(fd, 'w') | |
52 | f.write(pyfile) |
|
53 | f.write(pyfile) | |
53 | f.close() |
|
54 | f.close() | |
54 | # Unlink the file |
|
55 | # Unlink the file | |
55 | cl = PyFileConfigLoader(fname) |
|
56 | cl = PyFileConfigLoader(fname) | |
56 | config = cl.load_config() |
|
57 | config = cl.load_config() | |
57 | self.assertEquals(config.a, 10) |
|
58 | self.assertEquals(config.a, 10) | |
58 | self.assertEquals(config.b, 20) |
|
59 | self.assertEquals(config.b, 20) | |
59 | self.assertEquals(config.Foo.Bar.value, 10) |
|
60 | self.assertEquals(config.Foo.Bar.value, 10) | |
60 | self.assertEquals(config.Foo.Bam.value, range(10)) |
|
61 | self.assertEquals(config.Foo.Bam.value, range(10)) | |
61 | self.assertEquals(config.D.C.value, 'hi there') |
|
62 | self.assertEquals(config.D.C.value, 'hi there') | |
62 |
|
63 | |||
63 |
|
64 | |||
64 | class TestArgParseCL(TestCase): |
|
65 | class TestArgParseCL(TestCase): | |
65 |
|
66 | |||
66 | def test_basic(self): |
|
67 | def test_basic(self): | |
67 |
|
68 | |||
68 | class MyLoader(ArgParseConfigLoader): |
|
69 | arguments = ( | |
69 | arguments = ( |
|
|||
70 | (('-f','--foo'), dict(dest='Global.foo', type=str)), |
|
70 | (('-f','--foo'), dict(dest='Global.foo', type=str)), | |
71 | (('-b',), dict(dest='MyClass.bar', type=int)), |
|
71 | (('-b',), dict(dest='MyClass.bar', type=int)), | |
72 | (('-n',), dict(dest='n', action='store_true')), |
|
72 | (('-n',), dict(dest='n', action='store_true')), | |
73 | (('Global.bam',), dict(type=str)) |
|
73 | (('Global.bam',), dict(type=str)) | |
74 | ) |
|
74 | ) | |
75 |
|
75 | cl = ArgParseConfigLoader(arguments=arguments) | ||
76 | cl = MyLoader() |
|
|||
77 | config = cl.load_config('-f hi -b 10 -n wow'.split()) |
|
76 | config = cl.load_config('-f hi -b 10 -n wow'.split()) | |
78 | self.assertEquals(config.Global.foo, 'hi') |
|
77 | self.assertEquals(config.Global.foo, 'hi') | |
79 | self.assertEquals(config.MyClass.bar, 10) |
|
78 | self.assertEquals(config.MyClass.bar, 10) | |
80 | self.assertEquals(config.n, True) |
|
79 | self.assertEquals(config.n, True) | |
81 | self.assertEquals(config.Global.bam, 'wow') |
|
80 | self.assertEquals(config.Global.bam, 'wow') | |
82 |
|
81 | |||
83 | def test_add_arguments(self): |
|
82 | def test_add_arguments(self): | |
84 |
|
83 | |||
85 | class MyLoader(ArgParseConfigLoader): |
|
84 | class MyLoader(ArgParseConfigLoader): | |
86 | def _add_arguments(self): |
|
85 | def _add_arguments(self): | |
87 | subparsers = self.parser.add_subparsers(dest='subparser_name') |
|
86 | subparsers = self.parser.add_subparsers(dest='subparser_name') | |
88 | subparser1 = subparsers.add_parser('1') |
|
87 | subparser1 = subparsers.add_parser('1') | |
89 | subparser1.add_argument('-x',dest='Global.x') |
|
88 | subparser1.add_argument('-x',dest='Global.x') | |
90 | subparser2 = subparsers.add_parser('2') |
|
89 | subparser2 = subparsers.add_parser('2') | |
91 | subparser2.add_argument('y') |
|
90 | subparser2.add_argument('y') | |
92 |
|
91 | |||
93 | cl = MyLoader() |
|
92 | cl = MyLoader() | |
94 | config = cl.load_config('2 frobble'.split()) |
|
93 | config = cl.load_config('2 frobble'.split()) | |
95 | self.assertEquals(config.subparser_name, '2') |
|
94 | self.assertEquals(config.subparser_name, '2') | |
96 | self.assertEquals(config.y, 'frobble') |
|
95 | self.assertEquals(config.y, 'frobble') | |
97 | config = cl.load_config('1 -x frobble'.split()) |
|
96 | config = cl.load_config('1 -x frobble'.split()) | |
98 | self.assertEquals(config.subparser_name, '1') |
|
97 | self.assertEquals(config.subparser_name, '1') | |
99 | self.assertEquals(config.Global.x, 'frobble') |
|
98 | self.assertEquals(config.Global.x, 'frobble') | |
100 |
|
99 | |||
101 | class TestConfig(TestCase): |
|
100 | class TestConfig(TestCase): | |
102 |
|
101 | |||
103 | def test_setget(self): |
|
102 | def test_setget(self): | |
104 | c = Config() |
|
103 | c = Config() | |
105 | c.a = 10 |
|
104 | c.a = 10 | |
106 | self.assertEquals(c.a, 10) |
|
105 | self.assertEquals(c.a, 10) | |
107 | self.assertEquals(c.has_key('b'), False) |
|
106 | self.assertEquals(c.has_key('b'), False) | |
108 |
|
107 | |||
109 | def test_auto_section(self): |
|
108 | def test_auto_section(self): | |
110 | c = Config() |
|
109 | c = Config() | |
111 | self.assertEquals(c.has_key('A'), True) |
|
110 | self.assertEquals(c.has_key('A'), True) | |
112 | self.assertEquals(c._has_section('A'), False) |
|
111 | self.assertEquals(c._has_section('A'), False) | |
113 | A = c.A |
|
112 | A = c.A | |
114 | A.foo = 'hi there' |
|
113 | A.foo = 'hi there' | |
115 | self.assertEquals(c._has_section('A'), True) |
|
114 | self.assertEquals(c._has_section('A'), True) | |
116 | self.assertEquals(c.A.foo, 'hi there') |
|
115 | self.assertEquals(c.A.foo, 'hi there') | |
117 | del c.A |
|
116 | del c.A | |
118 | self.assertEquals(len(c.A.keys()),0) |
|
117 | self.assertEquals(len(c.A.keys()),0) | |
119 |
|
118 | |||
120 | def test_merge_doesnt_exist(self): |
|
119 | def test_merge_doesnt_exist(self): | |
121 | c1 = Config() |
|
120 | c1 = Config() | |
122 | c2 = Config() |
|
121 | c2 = Config() | |
123 | c2.bar = 10 |
|
122 | c2.bar = 10 | |
124 | c2.Foo.bar = 10 |
|
123 | c2.Foo.bar = 10 | |
125 | c1._merge(c2) |
|
124 | c1._merge(c2) | |
126 | self.assertEquals(c1.Foo.bar, 10) |
|
125 | self.assertEquals(c1.Foo.bar, 10) | |
127 | self.assertEquals(c1.bar, 10) |
|
126 | self.assertEquals(c1.bar, 10) | |
128 | c2.Bar.bar = 10 |
|
127 | c2.Bar.bar = 10 | |
129 | c1._merge(c2) |
|
128 | c1._merge(c2) | |
130 | self.assertEquals(c1.Bar.bar, 10) |
|
129 | self.assertEquals(c1.Bar.bar, 10) | |
131 |
|
130 | |||
132 | def test_merge_exists(self): |
|
131 | def test_merge_exists(self): | |
133 | c1 = Config() |
|
132 | c1 = Config() | |
134 | c2 = Config() |
|
133 | c2 = Config() | |
135 | c1.Foo.bar = 10 |
|
134 | c1.Foo.bar = 10 | |
136 | c1.Foo.bam = 30 |
|
135 | c1.Foo.bam = 30 | |
137 | c2.Foo.bar = 20 |
|
136 | c2.Foo.bar = 20 | |
138 | c2.Foo.wow = 40 |
|
137 | c2.Foo.wow = 40 | |
139 | c1._merge(c2) |
|
138 | c1._merge(c2) | |
140 | self.assertEquals(c1.Foo.bam, 30) |
|
139 | self.assertEquals(c1.Foo.bam, 30) | |
141 | self.assertEquals(c1.Foo.bar, 20) |
|
140 | self.assertEquals(c1.Foo.bar, 20) | |
142 | self.assertEquals(c1.Foo.wow, 40) |
|
141 | self.assertEquals(c1.Foo.wow, 40) | |
143 | c2.Foo.Bam.bam = 10 |
|
142 | c2.Foo.Bam.bam = 10 | |
144 | c1._merge(c2) |
|
143 | c1._merge(c2) | |
145 | self.assertEquals(c1.Foo.Bam.bam, 10) |
|
144 | self.assertEquals(c1.Foo.Bam.bam, 10) | |
146 |
|
145 | |||
147 | def test_deepcopy(self): |
|
146 | def test_deepcopy(self): | |
148 | c1 = Config() |
|
147 | c1 = Config() | |
149 | c1.Foo.bar = 10 |
|
148 | c1.Foo.bar = 10 | |
150 | c1.Foo.bam = 30 |
|
149 | c1.Foo.bam = 30 | |
151 | c1.a = 'asdf' |
|
150 | c1.a = 'asdf' | |
152 | c1.b = range(10) |
|
151 | c1.b = range(10) | |
153 | import copy |
|
152 | import copy | |
154 | c2 = copy.deepcopy(c1) |
|
153 | c2 = copy.deepcopy(c1) | |
155 | self.assertEquals(c1, c2) |
|
154 | self.assertEquals(c1, c2) | |
156 | self.assert_(c1 is not c2) |
|
155 | self.assert_(c1 is not c2) | |
157 | self.assert_(c1.Foo is not c2.Foo) |
|
156 | self.assert_(c1.Foo is not c2.Foo) | |
158 |
|
157 | |||
159 | def test_builtin(self): |
|
158 | def test_builtin(self): | |
160 | c1 = Config() |
|
159 | c1 = Config() | |
161 | exec 'foo = True' in c1 |
|
160 | exec 'foo = True' in c1 | |
162 | self.assertEquals(c1.foo, True) |
|
161 | self.assertEquals(c1.foo, True) | |
163 | self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10) |
|
162 | self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10) |
@@ -1,300 +1,488 b'' | |||||
1 | #!/usr/bin/env python |
|
|||
2 |
|
|
1 | # encoding: utf-8 | |
3 | """ |
|
2 | """ | |
4 | An application for IPython |
|
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. | |||
5 |
|
10 | |||
6 | Authors: |
|
11 | Authors: | |
7 |
|
12 | |||
8 | * Brian Granger |
|
13 | * Brian Granger | |
9 | * Fernando Perez |
|
14 | * Fernando Perez | |
10 |
|
15 | |||
11 | Notes |
|
16 | Notes | |
12 | ----- |
|
17 | ----- | |
13 | """ |
|
18 | """ | |
14 |
|
19 | |||
15 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
21 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
22 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
23 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
24 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
21 |
|
26 | |||
22 | #----------------------------------------------------------------------------- |
|
27 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
28 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
25 |
|
30 | |||
26 | import logging |
|
31 | import logging | |
27 | import os |
|
32 | import os | |
28 | import sys |
|
33 | import sys | |
29 | import traceback |
|
|||
30 | from copy import deepcopy |
|
|||
31 |
|
34 | |||
32 | from IPython.utils.genutils import get_ipython_dir, filefind |
|
35 | from IPython.core import release, crashhandler | |
|
36 | from IPython.utils.genutils import get_ipython_dir, get_ipython_package_dir | |||
33 | from IPython.config.loader import ( |
|
37 | from IPython.config.loader import ( | |
34 | PyFileConfigLoader, |
|
38 | PyFileConfigLoader, | |
35 | ArgParseConfigLoader, |
|
39 | ArgParseConfigLoader, | |
36 | Config, |
|
40 | Config, | |
37 | NoConfigDefault |
|
|||
38 | ) |
|
41 | ) | |
39 |
|
42 | |||
40 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
41 | # Classes and functions |
|
44 | # Classes and functions | |
42 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
43 |
|
46 | |||
44 |
|
||||
45 | class IPythonArgParseConfigLoader(ArgParseConfigLoader): |
|
|||
46 | """Default command line options for IPython based applications.""" |
|
|||
47 |
|
||||
48 | def _add_other_arguments(self): |
|
|||
49 | self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str, |
|
|||
50 | help='Set to override default location of Global.ipythondir.', |
|
|||
51 | default=NoConfigDefault, |
|
|||
52 | metavar='Global.ipythondir') |
|
|||
53 | self.parser.add_argument('-p','-profile',dest='Global.profile',type=str, |
|
|||
54 | help='The string name of the ipython profile to be used.', |
|
|||
55 | default=NoConfigDefault, |
|
|||
56 | metavar='Global.profile') |
|
|||
57 | self.parser.add_argument('-log_level',dest="Global.log_level",type=int, |
|
|||
58 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
|||
59 | default=NoConfigDefault) |
|
|||
60 | self.parser.add_argument('-config_file',dest='Global.config_file',type=str, |
|
|||
61 | help='Set the config file name to override default.', |
|
|||
62 | default=NoConfigDefault, |
|
|||
63 | metavar='Global.config_file') |
|
|||
64 |
|
||||
65 |
|
||||
66 | class ApplicationError(Exception): |
|
47 | class ApplicationError(Exception): | |
67 | pass |
|
48 | pass | |
68 |
|
49 | |||
69 |
|
50 | |||
|
51 | app_cl_args = ( | |||
|
52 | (('--ipython-dir', ), dict( | |||
|
53 | dest='Global.ipython_dir',type=unicode, | |||
|
54 | help= | |||
|
55 | """Set to override default location of the IPython directory | |||
|
56 | IPYTHON_DIR, stored as Global.ipython_dir. This can also be specified | |||
|
57 | through the environment variable IPYTHON_DIR.""", | |||
|
58 | metavar='Global.ipython_dir') ), | |||
|
59 | (('-p', '--profile',), dict( | |||
|
60 | dest='Global.profile',type=unicode, | |||
|
61 | help= | |||
|
62 | """The string name of the ipython profile to be used. Assume that your | |||
|
63 | config file is ipython_config-<name>.py (looks in current dir first, | |||
|
64 | then in IPYTHON_DIR). This is a quick way to keep and load multiple | |||
|
65 | config files for different tasks, especially if include your basic one | |||
|
66 | in your more specialized ones. You can keep a basic | |||
|
67 | IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which | |||
|
68 | include this one and load extra things for particular tasks.""", | |||
|
69 | metavar='Global.profile') ), | |||
|
70 | (('--log-level',), dict( | |||
|
71 | dest="Global.log_level",type=int, | |||
|
72 | help='Set the log level (0,10,20,30,40,50). Default is 30.', | |||
|
73 | metavar='Global.log_level')), | |||
|
74 | (('--config-file',), dict( | |||
|
75 | dest='Global.config_file',type=unicode, | |||
|
76 | help= | |||
|
77 | """Set the config file name to override default. Normally IPython | |||
|
78 | loads ipython_config.py (from current directory) or | |||
|
79 | IPYTHON_DIR/ipython_config.py. If the loading of your config file | |||
|
80 | fails, IPython starts with a bare bones configuration (no modules | |||
|
81 | loaded at all).""", | |||
|
82 | metavar='Global.config_file')), | |||
|
83 | ) | |||
|
84 | ||||
70 | class Application(object): |
|
85 | class Application(object): | |
71 |
"""Load a config, construct |
|
86 | """Load a config, construct components and set them running. | |
|
87 | ||||
|
88 | The configuration of an application can be done via four different Config | |||
|
89 | objects, which are loaded and ultimately merged into a single one used from | |||
|
90 | that point on by the app. These are: | |||
|
91 | ||||
|
92 | 1. default_config: internal defaults, implemented in code. | |||
|
93 | 2. file_config: read from the filesystem. | |||
|
94 | 3. command_line_config: read from the system's command line flags. | |||
|
95 | 4. constructor_config: passed parametrically to the constructor. | |||
|
96 | ||||
|
97 | During initialization, 3 is actually read before 2, since at the | |||
|
98 | command-line one may override the location of the file to be read. But the | |||
|
99 | above is the order in which the merge is made. | |||
|
100 | ||||
|
101 | There is a final config object can be created and passed to the | |||
|
102 | constructor: override_config. If it exists, this completely overrides the | |||
|
103 | configs 2-4 above (the default is still used to ensure that all needed | |||
|
104 | fields at least are created). This makes it easier to create | |||
|
105 | parametrically (e.g. in testing or sphinx plugins) objects with a known | |||
|
106 | configuration, that are unaffected by whatever arguments may be present in | |||
|
107 | sys.argv or files in the user's various directories. | |||
72 | """ |
|
108 | """ | |
73 |
|
109 | |||
74 |
|
|
110 | name = u'ipython' | |
75 | name = 'ipython' |
|
111 | description = 'IPython: an enhanced interactive Python shell.' | |
76 |
|
112 | #: usage message printed by argparse. If None, auto-generate | ||
77 | def __init__(self): |
|
113 | usage = None | |
|
114 | config_file_name = u'ipython_config.py' | |||
|
115 | #: Track the default and actual separately because some messages are | |||
|
116 | #: only printed if we aren't using the default. | |||
|
117 | default_config_file_name = config_file_name | |||
|
118 | default_log_level = logging.WARN | |||
|
119 | #: Set by --profile option | |||
|
120 | profile_name = None | |||
|
121 | #: User's ipython directory, typically ~/.ipython/ | |||
|
122 | ipython_dir = None | |||
|
123 | #: internal defaults, implemented in code. | |||
|
124 | default_config = None | |||
|
125 | #: read from the filesystem | |||
|
126 | file_config = None | |||
|
127 | #: read from the system's command line flags | |||
|
128 | command_line_config = None | |||
|
129 | #: passed parametrically to the constructor. | |||
|
130 | constructor_config = None | |||
|
131 | #: final override, if given supercedes file/command/constructor configs | |||
|
132 | override_config = None | |||
|
133 | #: A reference to the argv to be used (typically ends up being sys.argv[1:]) | |||
|
134 | argv = None | |||
|
135 | #: Default command line arguments. Subclasses should create a new tuple | |||
|
136 | #: that *includes* these. | |||
|
137 | cl_arguments = app_cl_args | |||
|
138 | ||||
|
139 | #: extra arguments computed by the command-line loader | |||
|
140 | extra_args = None | |||
|
141 | ||||
|
142 | # Private attributes | |||
|
143 | _exiting = False | |||
|
144 | _initialized = False | |||
|
145 | ||||
|
146 | # Class choices for things that will be instantiated at runtime. | |||
|
147 | _CrashHandler = crashhandler.CrashHandler | |||
|
148 | ||||
|
149 | def __init__(self, argv=None, constructor_config=None, override_config=None): | |||
|
150 | self.argv = sys.argv[1:] if argv is None else argv | |||
|
151 | self.constructor_config = constructor_config | |||
|
152 | self.override_config = override_config | |||
78 | self.init_logger() |
|
153 | self.init_logger() | |
79 | self.default_config_file_name = self.config_file_name |
|
|||
80 |
|
154 | |||
81 | def init_logger(self): |
|
155 | def init_logger(self): | |
82 | self.log = logging.getLogger(self.__class__.__name__) |
|
156 | self.log = logging.getLogger(self.__class__.__name__) | |
83 | # This is used as the default until the command line arguments are read. |
|
157 | # This is used as the default until the command line arguments are read. | |
84 |
self.log.setLevel( |
|
158 | self.log.setLevel(self.default_log_level) | |
85 | self._log_handler = logging.StreamHandler() |
|
159 | self._log_handler = logging.StreamHandler() | |
86 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
160 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") | |
87 | self._log_handler.setFormatter(self._log_formatter) |
|
161 | self._log_handler.setFormatter(self._log_formatter) | |
88 | self.log.addHandler(self._log_handler) |
|
162 | self.log.addHandler(self._log_handler) | |
89 |
|
163 | |||
90 | def _set_log_level(self, level): |
|
164 | def _set_log_level(self, level): | |
91 | self.log.setLevel(level) |
|
165 | self.log.setLevel(level) | |
92 |
|
166 | |||
93 | def _get_log_level(self): |
|
167 | def _get_log_level(self): | |
94 | return self.log.level |
|
168 | return self.log.level | |
95 |
|
169 | |||
96 | log_level = property(_get_log_level, _set_log_level) |
|
170 | log_level = property(_get_log_level, _set_log_level) | |
97 |
|
171 | |||
|
172 | def initialize(self): | |||
|
173 | """Initialize the application. | |||
|
174 | ||||
|
175 | Loads all configuration information and sets all application state, but | |||
|
176 | does not start any relevant processing (typically some kind of event | |||
|
177 | loop). | |||
|
178 | ||||
|
179 | Once this method has been called, the application is flagged as | |||
|
180 | initialized and the method becomes a no-op.""" | |||
|
181 | ||||
|
182 | if self._initialized: | |||
|
183 | return | |||
|
184 | ||||
|
185 | # The first part is protected with an 'attempt' wrapper, that will log | |||
|
186 | # failures with the basic system traceback machinery. Once our crash | |||
|
187 | # handler is in place, we can let any subsequent exception propagate, | |||
|
188 | # as our handler will log it with much better detail than the default. | |||
|
189 | self.attempt(self.create_crash_handler) | |||
|
190 | ||||
|
191 | # Configuration phase | |||
|
192 | # Default config (internally hardwired in application code) | |||
|
193 | self.create_default_config() | |||
|
194 | self.log_default_config() | |||
|
195 | self.set_default_config_log_level() | |||
|
196 | ||||
|
197 | if self.override_config is None: | |||
|
198 | # Command-line config | |||
|
199 | self.pre_load_command_line_config() | |||
|
200 | self.load_command_line_config() | |||
|
201 | self.set_command_line_config_log_level() | |||
|
202 | self.post_load_command_line_config() | |||
|
203 | self.log_command_line_config() | |||
|
204 | ||||
|
205 | # Find resources needed for filesystem access, using information from | |||
|
206 | # the above two | |||
|
207 | self.find_ipython_dir() | |||
|
208 | self.find_resources() | |||
|
209 | self.find_config_file_name() | |||
|
210 | self.find_config_file_paths() | |||
|
211 | ||||
|
212 | if self.override_config is None: | |||
|
213 | # File-based config | |||
|
214 | self.pre_load_file_config() | |||
|
215 | self.load_file_config() | |||
|
216 | self.set_file_config_log_level() | |||
|
217 | self.post_load_file_config() | |||
|
218 | self.log_file_config() | |||
|
219 | ||||
|
220 | # Merge all config objects into a single one the app can then use | |||
|
221 | self.merge_configs() | |||
|
222 | self.log_master_config() | |||
|
223 | ||||
|
224 | # Construction phase | |||
|
225 | self.pre_construct() | |||
|
226 | self.construct() | |||
|
227 | self.post_construct() | |||
|
228 | ||||
|
229 | # Done, flag as such and | |||
|
230 | self._initialized = True | |||
|
231 | ||||
98 | def start(self): |
|
232 | def start(self): | |
99 | """Start the application.""" |
|
233 | """Start the application.""" | |
100 | self.attempt(self.create_default_config) |
|
234 | self.initialize() | |
101 | self.attempt(self.pre_load_command_line_config) |
|
235 | self.start_app() | |
102 | self.attempt(self.load_command_line_config, action='abort') |
|
|||
103 | self.attempt(self.post_load_command_line_config) |
|
|||
104 | self.attempt(self.find_ipythondir) |
|
|||
105 | self.attempt(self.find_config_file_name) |
|
|||
106 | self.attempt(self.find_config_file_paths) |
|
|||
107 | self.attempt(self.pre_load_file_config) |
|
|||
108 | self.attempt(self.load_file_config) |
|
|||
109 | self.attempt(self.post_load_file_config) |
|
|||
110 | self.attempt(self.merge_configs) |
|
|||
111 | self.attempt(self.pre_construct) |
|
|||
112 | self.attempt(self.construct) |
|
|||
113 | self.attempt(self.post_construct) |
|
|||
114 | self.attempt(self.start_app) |
|
|||
115 |
|
236 | |||
116 | #------------------------------------------------------------------------- |
|
237 | #------------------------------------------------------------------------- | |
117 | # Various stages of Application creation |
|
238 | # Various stages of Application creation | |
118 | #------------------------------------------------------------------------- |
|
239 | #------------------------------------------------------------------------- | |
119 |
|
240 | |||
|
241 | def create_crash_handler(self): | |||
|
242 | """Create a crash handler, typically setting sys.excepthook to it.""" | |||
|
243 | self.crash_handler = self._CrashHandler(self, self.name) | |||
|
244 | sys.excepthook = self.crash_handler | |||
|
245 | ||||
120 | def create_default_config(self): |
|
246 | def create_default_config(self): | |
121 | """Create defaults that can't be set elsewhere. |
|
247 | """Create defaults that can't be set elsewhere. | |
122 |
|
248 | |||
123 | For the most part, we try to set default in the class attributes |
|
249 | For the most part, we try to set default in the class attributes | |
124 | of Components. But, defaults the top-level Application (which is |
|
250 | of Components. But, defaults the top-level Application (which is | |
125 | not a HasTraits or Component) are not set in this way. Instead |
|
251 | not a HasTraits or Component) are not set in this way. Instead | |
126 | we set them here. The Global section is for variables like this that |
|
252 | we set them here. The Global section is for variables like this that | |
127 | don't belong to a particular component. |
|
253 | don't belong to a particular component. | |
128 | """ |
|
254 | """ | |
129 |
|
|
255 | c = Config() | |
130 |
|
|
256 | c.Global.ipython_dir = get_ipython_dir() | |
|
257 | c.Global.log_level = self.log_level | |||
|
258 | self.default_config = c | |||
|
259 | ||||
|
260 | def log_default_config(self): | |||
131 | self.log.debug('Default config loaded:') |
|
261 | self.log.debug('Default config loaded:') | |
132 | self.log.debug(repr(self.default_config)) |
|
262 | self.log.debug(repr(self.default_config)) | |
133 |
|
263 | |||
|
264 | def set_default_config_log_level(self): | |||
|
265 | try: | |||
|
266 | self.log_level = self.default_config.Global.log_level | |||
|
267 | except AttributeError: | |||
|
268 | # Fallback to the default_log_level class attribute | |||
|
269 | pass | |||
|
270 | ||||
134 | def create_command_line_config(self): |
|
271 | def create_command_line_config(self): | |
135 | """Create and return a command line config loader.""" |
|
272 | """Create and return a command line config loader.""" | |
136 |
return |
|
273 | return ArgParseConfigLoader(self.argv, self.cl_arguments, | |
|
274 | description=self.description, | |||
|
275 | version=release.version, | |||
|
276 | usage=self.usage, | |||
|
277 | ) | |||
137 |
|
278 | |||
138 | def pre_load_command_line_config(self): |
|
279 | def pre_load_command_line_config(self): | |
139 | """Do actions just before loading the command line config.""" |
|
280 | """Do actions just before loading the command line config.""" | |
140 | pass |
|
281 | pass | |
141 |
|
282 | |||
142 | def load_command_line_config(self): |
|
283 | def load_command_line_config(self): | |
143 | """Load the command line config. |
|
284 | """Load the command line config.""" | |
144 |
|
||||
145 | This method also sets ``self.debug``. |
|
|||
146 | """ |
|
|||
147 |
|
||||
148 | loader = self.create_command_line_config() |
|
285 | loader = self.create_command_line_config() | |
149 | self.command_line_config = loader.load_config() |
|
286 | self.command_line_config = loader.load_config() | |
150 | self.extra_args = loader.get_extra_args() |
|
287 | self.extra_args = loader.get_extra_args() | |
151 |
|
288 | |||
|
289 | def set_command_line_config_log_level(self): | |||
152 | try: |
|
290 | try: | |
153 | self.log_level = self.command_line_config.Global.log_level |
|
291 | self.log_level = self.command_line_config.Global.log_level | |
154 | except AttributeError: |
|
292 | except AttributeError: | |
155 | pass # Use existing value which is set in Application.init_logger. |
|
293 | pass | |
156 | self.log.debug("Command line config loaded:") |
|
|||
157 | self.log.debug(repr(self.command_line_config)) |
|
|||
158 |
|
294 | |||
159 | def post_load_command_line_config(self): |
|
295 | def post_load_command_line_config(self): | |
160 | """Do actions just after loading the command line config.""" |
|
296 | """Do actions just after loading the command line config.""" | |
161 | pass |
|
297 | pass | |
162 |
|
298 | |||
163 |
def |
|
299 | def log_command_line_config(self): | |
|
300 | self.log.debug("Command line config loaded:") | |||
|
301 | self.log.debug(repr(self.command_line_config)) | |||
|
302 | ||||
|
303 | def find_ipython_dir(self): | |||
164 | """Set the IPython directory. |
|
304 | """Set the IPython directory. | |
165 |
|
305 | |||
166 | This sets ``self.ipythondir``, but the actual value that is passed |
|
306 | This sets ``self.ipython_dir``, but the actual value that is passed to | |
167 |
t |
|
307 | the application is kept in either ``self.default_config`` or | |
168 |
``self.command_line_config``. This also add |
|
308 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to | |
169 |
``sys.path`` so config files there can be reference |
|
309 | ``sys.path`` so config files there can be referenced by other config | |
170 | files. |
|
310 | files. | |
171 | """ |
|
311 | """ | |
172 |
|
312 | |||
173 | try: |
|
313 | try: | |
174 | self.ipythondir = self.command_line_config.Global.ipythondir |
|
314 | self.ipython_dir = self.command_line_config.Global.ipython_dir | |
175 | except AttributeError: |
|
315 | except AttributeError: | |
176 | self.ipythondir = self.default_config.Global.ipythondir |
|
316 | self.ipython_dir = self.default_config.Global.ipython_dir | |
177 | sys.path.append(os.path.abspath(self.ipythondir)) |
|
317 | sys.path.append(os.path.abspath(self.ipython_dir)) | |
178 | if not os.path.isdir(self.ipythondir): |
|
318 | if not os.path.isdir(self.ipython_dir): | |
179 |
os.makedirs(self.ipythondir, mode |
|
319 | os.makedirs(self.ipython_dir, mode=0777) | |
180 | self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir) |
|
320 | self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir) | |
|
321 | ||||
|
322 | def find_resources(self): | |||
|
323 | """Find other resources that need to be in place. | |||
|
324 | ||||
|
325 | Things like cluster directories need to be in place to find the | |||
|
326 | config file. These happen right after the IPython directory has | |||
|
327 | been set. | |||
|
328 | """ | |||
|
329 | pass | |||
181 |
|
330 | |||
182 | def find_config_file_name(self): |
|
331 | def find_config_file_name(self): | |
183 | """Find the config file name for this application. |
|
332 | """Find the config file name for this application. | |
184 |
|
333 | |||
185 | If a profile has been set at the command line, this will resolve |
|
334 | This must set ``self.config_file_name`` to the filename of the | |
186 | it. The search paths for the config file are set in |
|
335 | config file to use (just the filename). The search paths for the | |
187 |
:meth:`find_config_file_paths` and then passed |
|
336 | config file are set in :meth:`find_config_file_paths` and then passed | |
188 | loader where they are resolved to an absolute path. |
|
337 | to the config file loader where they are resolved to an absolute path. | |
|
338 | ||||
|
339 | If a profile has been set at the command line, this will resolve it. | |||
189 | """ |
|
340 | """ | |
190 |
|
341 | |||
191 | try: |
|
342 | try: | |
192 | self.config_file_name = self.command_line_config.Global.config_file |
|
343 | self.config_file_name = self.command_line_config.Global.config_file | |
193 | except AttributeError: |
|
344 | except AttributeError: | |
194 | pass |
|
345 | pass | |
195 |
|
346 | |||
196 | try: |
|
347 | try: | |
197 | self.profile_name = self.command_line_config.Global.profile |
|
348 | self.profile_name = self.command_line_config.Global.profile | |
198 | name_parts = self.config_file_name.split('.') |
|
|||
199 | name_parts.insert(1, '_' + self.profile_name + '.') |
|
|||
200 | self.config_file_name = ''.join(name_parts) |
|
|||
201 | except AttributeError: |
|
349 | except AttributeError: | |
202 | pass |
|
350 | pass | |
|
351 | else: | |||
|
352 | name_parts = self.config_file_name.split('.') | |||
|
353 | name_parts.insert(1, u'_' + self.profile_name + u'.') | |||
|
354 | self.config_file_name = ''.join(name_parts) | |||
203 |
|
355 | |||
204 | def find_config_file_paths(self): |
|
356 | def find_config_file_paths(self): | |
205 |
"""Set the search paths for resolving the config file. |
|
357 | """Set the search paths for resolving the config file. | |
206 | self.config_file_paths = (os.getcwd(), self.ipythondir) |
|
358 | ||
|
359 | This must set ``self.config_file_paths`` to a sequence of search | |||
|
360 | paths to pass to the config file loader. | |||
|
361 | """ | |||
|
362 | # Include our own profiles directory last, so that users can still find | |||
|
363 | # our shipped copies of builtin profiles even if they don't have them | |||
|
364 | # in their local ipython directory. | |||
|
365 | prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile') | |||
|
366 | self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir) | |||
207 |
|
367 | |||
208 | def pre_load_file_config(self): |
|
368 | def pre_load_file_config(self): | |
209 | """Do actions before the config file is loaded.""" |
|
369 | """Do actions before the config file is loaded.""" | |
210 | pass |
|
370 | pass | |
211 |
|
371 | |||
212 | def load_file_config(self): |
|
372 | def load_file_config(self): | |
213 | """Load the config file. |
|
373 | """Load the config file. | |
214 |
|
374 | |||
215 | This tries to load the config file from disk. If successful, the |
|
375 | This tries to load the config file from disk. If successful, the | |
216 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
376 | ``CONFIG_FILE`` config variable is set to the resolved config file | |
217 | location. If not successful, an empty config is used. |
|
377 | location. If not successful, an empty config is used. | |
218 | """ |
|
378 | """ | |
219 |
self.log.debug("Attempting to load config file: |
|
379 | self.log.debug("Attempting to load config file: %s" % | |
|
380 | self.config_file_name) | |||
220 | loader = PyFileConfigLoader(self.config_file_name, |
|
381 | loader = PyFileConfigLoader(self.config_file_name, | |
221 | path=self.config_file_paths) |
|
382 | path=self.config_file_paths) | |
222 | try: |
|
383 | try: | |
223 | self.file_config = loader.load_config() |
|
384 | self.file_config = loader.load_config() | |
224 | self.file_config.Global.config_file = loader.full_filename |
|
385 | self.file_config.Global.config_file = loader.full_filename | |
225 | except IOError: |
|
386 | except IOError: | |
226 | # Only warn if the default config file was NOT being used. |
|
387 | # Only warn if the default config file was NOT being used. | |
227 | if not self.config_file_name==self.default_config_file_name: |
|
388 | if not self.config_file_name==self.default_config_file_name: | |
228 |
self.log.warn("Config file not found, skipping: |
|
389 | self.log.warn("Config file not found, skipping: %s" % | |
229 | self.config_file_name, exc_info=True) |
|
390 | self.config_file_name, exc_info=True) | |
230 | self.file_config = Config() |
|
391 | self.file_config = Config() | |
231 | except: |
|
392 | except: | |
232 |
self.log.warn("Error loading config file: |
|
393 | self.log.warn("Error loading config file: %s" % | |
233 |
|
|
394 | self.config_file_name, exc_info=True) | |
234 | self.file_config = Config() |
|
395 | self.file_config = Config() | |
235 | else: |
|
396 | ||
236 | self.log.debug("Config file loaded: <%s>" % loader.full_filename) |
|
397 | def set_file_config_log_level(self): | |
237 | self.log.debug(repr(self.file_config)) |
|
|||
238 | # We need to keeep self.log_level updated. But we only use the value |
|
398 | # We need to keeep self.log_level updated. But we only use the value | |
239 | # of the file_config if a value was not specified at the command |
|
399 | # of the file_config if a value was not specified at the command | |
240 | # line. |
|
400 | # line, because the command line overrides everything. | |
241 | if not hasattr(self.command_line_config.Global, 'log_level'): |
|
401 | if not hasattr(self.command_line_config.Global, 'log_level'): | |
242 | try: |
|
402 | try: | |
243 | self.log_level = self.file_config.Global.log_level |
|
403 | self.log_level = self.file_config.Global.log_level | |
244 | except AttributeError: |
|
404 | except AttributeError: | |
245 | pass # Use existing value |
|
405 | pass # Use existing value | |
246 |
|
406 | |||
247 | def post_load_file_config(self): |
|
407 | def post_load_file_config(self): | |
248 | """Do actions after the config file is loaded.""" |
|
408 | """Do actions after the config file is loaded.""" | |
249 | pass |
|
409 | pass | |
250 |
|
410 | |||
|
411 | def log_file_config(self): | |||
|
412 | if hasattr(self.file_config.Global, 'config_file'): | |||
|
413 | self.log.debug("Config file loaded: %s" % | |||
|
414 | self.file_config.Global.config_file) | |||
|
415 | self.log.debug(repr(self.file_config)) | |||
|
416 | ||||
251 | def merge_configs(self): |
|
417 | def merge_configs(self): | |
252 | """Merge the default, command line and file config objects.""" |
|
418 | """Merge the default, command line and file config objects.""" | |
253 | config = Config() |
|
419 | config = Config() | |
254 | config._merge(self.default_config) |
|
420 | config._merge(self.default_config) | |
255 | config._merge(self.file_config) |
|
421 | if self.override_config is None: | |
256 |
config._merge(self. |
|
422 | config._merge(self.file_config) | |
|
423 | config._merge(self.command_line_config) | |||
|
424 | if self.constructor_config is not None: | |||
|
425 | config._merge(self.constructor_config) | |||
|
426 | else: | |||
|
427 | config._merge(self.override_config) | |||
|
428 | # XXX fperez - propose to Brian we rename master_config to simply | |||
|
429 | # config, I think this is going to be heavily used in examples and | |||
|
430 | # application code and the name is shorter/easier to find/remember. | |||
|
431 | # For now, just alias it... | |||
257 | self.master_config = config |
|
432 | self.master_config = config | |
|
433 | self.config = config | |||
|
434 | ||||
|
435 | def log_master_config(self): | |||
258 | self.log.debug("Master config created:") |
|
436 | self.log.debug("Master config created:") | |
259 | self.log.debug(repr(self.master_config)) |
|
437 | self.log.debug(repr(self.master_config)) | |
260 |
|
438 | |||
261 | def pre_construct(self): |
|
439 | def pre_construct(self): | |
262 | """Do actions after the config has been built, but before construct.""" |
|
440 | """Do actions after the config has been built, but before construct.""" | |
263 | pass |
|
441 | pass | |
264 |
|
442 | |||
265 | def construct(self): |
|
443 | def construct(self): | |
266 | """Construct the main components that make up this app.""" |
|
444 | """Construct the main components that make up this app.""" | |
267 | self.log.debug("Constructing components for application") |
|
445 | self.log.debug("Constructing components for application") | |
268 |
|
446 | |||
269 | def post_construct(self): |
|
447 | def post_construct(self): | |
270 | """Do actions after construct, but before starting the app.""" |
|
448 | """Do actions after construct, but before starting the app.""" | |
271 | pass |
|
449 | pass | |
272 |
|
450 | |||
273 | def start_app(self): |
|
451 | def start_app(self): | |
274 | """Actually start the app.""" |
|
452 | """Actually start the app.""" | |
275 | self.log.debug("Starting application") |
|
453 | self.log.debug("Starting application") | |
276 |
|
454 | |||
277 | #------------------------------------------------------------------------- |
|
455 | #------------------------------------------------------------------------- | |
278 | # Utility methods |
|
456 | # Utility methods | |
279 | #------------------------------------------------------------------------- |
|
457 | #------------------------------------------------------------------------- | |
280 |
|
458 | |||
281 | def abort(self): |
|
459 | def abort(self): | |
282 | """Abort the starting of the application.""" |
|
460 | """Abort the starting of the application.""" | |
283 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) |
|
461 | if self._exiting: | |
284 | sys.exit(1) |
|
462 | pass | |
|
463 | else: | |||
|
464 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) | |||
|
465 | self._exiting = True | |||
|
466 | sys.exit(1) | |||
285 |
|
467 | |||
286 | def exit(self): |
|
468 | def exit(self, exit_status=0): | |
287 | self.log.critical("Aborting application: %s" % self.name) |
|
469 | if self._exiting: | |
288 | sys.exit(1) |
|
470 | pass | |
|
471 | else: | |||
|
472 | self.log.debug("Exiting application: %s" % self.name) | |||
|
473 | self._exiting = True | |||
|
474 | sys.exit(exit_status) | |||
289 |
|
475 | |||
290 | def attempt(self, func, action='abort'): |
|
476 | def attempt(self, func, action='abort'): | |
291 | try: |
|
477 | try: | |
292 | func() |
|
478 | func() | |
293 | except SystemExit: |
|
479 | except SystemExit: | |
294 |
se |
|
480 | raise | |
295 | except: |
|
481 | except: | |
296 | if action == 'abort': |
|
482 | if action == 'abort': | |
|
483 | self.log.critical("Aborting application: %s" % self.name, | |||
|
484 | exc_info=True) | |||
297 | self.abort() |
|
485 | self.abort() | |
|
486 | raise | |||
298 | elif action == 'exit': |
|
487 | elif action == 'exit': | |
299 | self.exit() |
|
488 | self.exit(0) | |
300 |
|
@@ -1,117 +1,118 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A context manager for managing things injected into :mod:`__builtin__`. |
|
4 | A context manager for managing things injected into :mod:`__builtin__`. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | # Copyright (C) 2008-2009 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | import __builtin__ |
|
22 | import __builtin__ | |
23 |
|
23 | |||
24 | from IPython.core.component import Component |
|
24 | from IPython.core.component import Component | |
25 | from IPython.core.quitter import Quitter |
|
25 | from IPython.core.quitter import Quitter | |
26 |
|
26 | |||
27 | from IPython.utils.autoattr import auto_attr |
|
27 | from IPython.utils.autoattr import auto_attr | |
28 |
|
28 | |||
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 | # Classes and functions |
|
30 | # Classes and functions | |
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | class BuiltinUndefined(object): pass |
|
34 | class __BuiltinUndefined(object): pass | |
35 | BuiltinUndefined = BuiltinUndefined() |
|
35 | BuiltinUndefined = __BuiltinUndefined() | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | class BuiltinTrap(Component): |
|
38 | class BuiltinTrap(Component): | |
39 |
|
39 | |||
40 | def __init__(self, parent): |
|
40 | def __init__(self, parent): | |
41 | super(BuiltinTrap, self).__init__(parent, None, None) |
|
41 | super(BuiltinTrap, self).__init__(parent, None, None) | |
42 | self._orig_builtins = {} |
|
42 | self._orig_builtins = {} | |
43 | # We define this to track if a single BuiltinTrap is nested. |
|
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. |
|
44 | # Only turn off the trap when the outermost call to __exit__ is made. | |
45 | self._nested_level = 0 |
|
45 | self._nested_level = 0 | |
46 |
|
46 | |||
47 | @auto_attr |
|
47 | @auto_attr | |
48 | def shell(self): |
|
48 | def shell(self): | |
49 | return Component.get_instances( |
|
49 | return Component.get_instances( | |
50 | root=self.root, |
|
50 | root=self.root, | |
51 | klass='IPython.core.iplib.InteractiveShell')[0] |
|
51 | klass='IPython.core.iplib.InteractiveShell')[0] | |
52 |
|
52 | |||
53 | def __enter__(self): |
|
53 | def __enter__(self): | |
54 | if self._nested_level == 0: |
|
54 | if self._nested_level == 0: | |
55 | self.set() |
|
55 | self.set() | |
56 | self._nested_level += 1 |
|
56 | self._nested_level += 1 | |
57 | # I return self, so callers can use add_builtin in a with clause. |
|
57 | # I return self, so callers can use add_builtin in a with clause. | |
58 | return self |
|
58 | return self | |
59 |
|
59 | |||
60 | def __exit__(self, type, value, traceback): |
|
60 | def __exit__(self, type, value, traceback): | |
61 | if self._nested_level == 1: |
|
61 | if self._nested_level == 1: | |
62 | self.unset() |
|
62 | self.unset() | |
63 | self._nested_level -= 1 |
|
63 | self._nested_level -= 1 | |
64 | # Returning False will cause exceptions to propagate |
|
64 | # Returning False will cause exceptions to propagate | |
65 | return False |
|
65 | return False | |
66 |
|
66 | |||
67 | def add_builtin(self, key, value): |
|
67 | def add_builtin(self, key, value): | |
68 | """Add a builtin and save the original.""" |
|
68 | """Add a builtin and save the original.""" | |
69 | orig = __builtin__.__dict__.get(key, BuiltinUndefined) |
|
69 | orig = __builtin__.__dict__.get(key, BuiltinUndefined) | |
70 | self._orig_builtins[key] = orig |
|
70 | self._orig_builtins[key] = orig | |
71 | __builtin__.__dict__[key] = value |
|
71 | __builtin__.__dict__[key] = value | |
72 |
|
72 | |||
73 | def remove_builtin(self, key): |
|
73 | def remove_builtin(self, key): | |
74 | """Remove an added builtin and re-set the original.""" |
|
74 | """Remove an added builtin and re-set the original.""" | |
75 | try: |
|
75 | try: | |
76 | orig = self._orig_builtins.pop(key) |
|
76 | orig = self._orig_builtins.pop(key) | |
77 | except KeyError: |
|
77 | except KeyError: | |
78 | pass |
|
78 | pass | |
79 | else: |
|
79 | else: | |
80 | if orig is BuiltinUndefined: |
|
80 | if orig is BuiltinUndefined: | |
81 | del __builtin__.__dict__[key] |
|
81 | del __builtin__.__dict__[key] | |
82 | else: |
|
82 | else: | |
83 | __builtin__.__dict__[key] = orig |
|
83 | __builtin__.__dict__[key] = orig | |
84 |
|
84 | |||
85 | def set(self): |
|
85 | def set(self): | |
86 | """Store ipython references in the __builtin__ namespace.""" |
|
86 | """Store ipython references in the __builtin__ namespace.""" | |
87 | self.add_builtin('exit', Quitter(self.shell, 'exit')) |
|
87 | self.add_builtin('exit', Quitter(self.shell, 'exit')) | |
88 | self.add_builtin('quit', Quitter(self.shell, 'quit')) |
|
88 | self.add_builtin('quit', Quitter(self.shell, 'quit')) | |
|
89 | self.add_builtin('get_ipython', self.shell.get_ipython) | |||
89 |
|
90 | |||
90 | # Recursive reload function |
|
91 | # Recursive reload function | |
91 | try: |
|
92 | try: | |
92 | from IPython.lib import deepreload |
|
93 | from IPython.lib import deepreload | |
93 | if self.shell.deep_reload: |
|
94 | if self.shell.deep_reload: | |
94 | self.add_builtin('reload', deepreload.reload) |
|
95 | self.add_builtin('reload', deepreload.reload) | |
95 | else: |
|
96 | else: | |
96 | self.add_builtin('dreload', deepreload.reload) |
|
97 | self.add_builtin('dreload', deepreload.reload) | |
97 | del deepreload |
|
98 | del deepreload | |
98 | except ImportError: |
|
99 | except ImportError: | |
99 | pass |
|
100 | pass | |
100 |
|
101 | |||
101 | # Keep in the builtins a flag for when IPython is active. We set it |
|
102 | # Keep in the builtins a flag for when IPython is active. We set it | |
102 | # with setdefault so that multiple nested IPythons don't clobber one |
|
103 | # with setdefault so that multiple nested IPythons don't clobber one | |
103 | # another. Each will increase its value by one upon being activated, |
|
104 | # another. Each will increase its value by one upon being activated, | |
104 | # which also gives us a way to determine the nesting level. |
|
105 | # which also gives us a way to determine the nesting level. | |
105 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
106 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
106 |
|
107 | |||
107 | def unset(self): |
|
108 | def unset(self): | |
108 | """Remove any builtins which might have been added by add_builtins, or |
|
109 | """Remove any builtins which might have been added by add_builtins, or | |
109 | restore overwritten ones to their previous values.""" |
|
110 | restore overwritten ones to their previous values.""" | |
110 | for key in self._orig_builtins.keys(): |
|
111 | for key in self._orig_builtins.keys(): | |
111 | self.remove_builtin(key) |
|
112 | self.remove_builtin(key) | |
112 | self._orig_builtins.clear() |
|
113 | self._orig_builtins.clear() | |
113 | self._builtins_added = False |
|
114 | self._builtins_added = False | |
114 | try: |
|
115 | try: | |
115 | del __builtin__.__dict__['__IPYTHON__active'] |
|
116 | del __builtin__.__dict__['__IPYTHON__active'] | |
116 | except KeyError: |
|
117 | except KeyError: | |
117 | pass |
|
118 | pass |
@@ -1,642 +1,658 b'' | |||||
1 | """Word completion for IPython. |
|
1 | """Word completion for IPython. | |
2 |
|
2 | |||
3 | This module is a fork of the rlcompleter module in the Python standard |
|
3 | This module is a fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
5 | upstream and were accepted as of Python 2.3, but we need a lot more | |
6 | functionality specific to IPython, so this module will continue to live as an |
|
6 | functionality specific to IPython, so this module will continue to live as an | |
7 | IPython-specific utility. |
|
7 | IPython-specific utility. | |
8 |
|
8 | |||
9 | Original rlcompleter documentation: |
|
9 | Original rlcompleter documentation: | |
10 |
|
10 | |||
11 | This requires the latest extension to the readline module (the |
|
11 | This requires the latest extension to the readline module (the | |
12 | completes keywords, built-ins and globals in __main__; when completing |
|
12 | completes keywords, built-ins and globals in __main__; when completing | |
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
14 | completes its attributes. |
|
14 | completes its attributes. | |
15 |
|
15 | |||
16 | It's very cool to do "import string" type "string.", hit the |
|
16 | It's very cool to do "import string" type "string.", hit the | |
17 | completion key (twice), and see the list of names defined by the |
|
17 | completion key (twice), and see the list of names defined by the | |
18 | string module! |
|
18 | string module! | |
19 |
|
19 | |||
20 | Tip: to use the tab key as the completion key, call |
|
20 | Tip: to use the tab key as the completion key, call | |
21 |
|
21 | |||
22 | readline.parse_and_bind("tab: complete") |
|
22 | readline.parse_and_bind("tab: complete") | |
23 |
|
23 | |||
24 | Notes: |
|
24 | Notes: | |
25 |
|
25 | |||
26 | - Exceptions raised by the completer function are *ignored* (and |
|
26 | - Exceptions raised by the completer function are *ignored* (and | |
27 | generally cause the completion to fail). This is a feature -- since |
|
27 | generally cause the completion to fail). This is a feature -- since | |
28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
28 | readline sets the tty device in raw (or cbreak) mode, printing a | |
29 | traceback wouldn't work well without some complicated hoopla to save, |
|
29 | traceback wouldn't work well without some complicated hoopla to save, | |
30 | reset and restore the tty state. |
|
30 | reset and restore the tty state. | |
31 |
|
31 | |||
32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
32 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
33 | application defined code to be executed if an object with a |
|
33 | application defined code to be executed if an object with a | |
34 | __getattr__ hook is found. Since it is the responsibility of the |
|
34 | __getattr__ hook is found. Since it is the responsibility of the | |
35 | application (or the user) to enable this feature, I consider this an |
|
35 | application (or the user) to enable this feature, I consider this an | |
36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
36 | acceptable risk. More complicated expressions (e.g. function calls or | |
37 | indexing operations) are *not* evaluated. |
|
37 | indexing operations) are *not* evaluated. | |
38 |
|
38 | |||
39 | - GNU readline is also used by the built-in functions input() and |
|
39 | - GNU readline is also used by the built-in functions input() and | |
40 | raw_input(), and thus these also benefit/suffer from the completer |
|
40 | raw_input(), and thus these also benefit/suffer from the completer | |
41 | features. Clearly an interactive application can benefit by |
|
41 | features. Clearly an interactive application can benefit by | |
42 | specifying its own completer function and using raw_input() for all |
|
42 | specifying its own completer function and using raw_input() for all | |
43 | its input. |
|
43 | 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 | #***************************************************************************** | |
51 | # |
|
50 | # | |
52 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
51 | # Since this file is essentially a minimally modified copy of the rlcompleter | |
53 | # module which is part of the standard Python distribution, I assume that the |
|
52 | # module which is part of the standard Python distribution, I assume that the | |
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 | |
68 | import itertools |
|
72 | import itertools | |
69 | import keyword |
|
73 | import keyword | |
70 | import os |
|
74 | import os | |
71 | import re |
|
75 | import re | |
72 | import shlex |
|
76 | import shlex | |
73 | import sys |
|
77 | import sys | |
74 | import types |
|
78 | import types | |
75 |
|
79 | |||
|
80 | import IPython.utils.rlineimpl as readline | |||
76 | from IPython.core.error import TryNext |
|
81 | from IPython.core.error import TryNext | |
77 | from IPython.core.prefilter import ESC_MAGIC |
|
82 | from IPython.core.prefilter import ESC_MAGIC | |
78 |
|
||||
79 | import IPython.utils.rlineimpl as readline |
|
|||
80 | from IPython.utils.ipstruct import Struct |
|
|||
81 | from IPython.utils import generics |
|
83 | from IPython.utils import generics | |
82 |
|
||||
83 | # Python 2.4 offers sets as a builtin |
|
|||
84 | try: |
|
|||
85 | set() |
|
|||
86 | except NameError: |
|
|||
87 | from sets import Set as set |
|
|||
88 |
|
||||
89 | from IPython.utils.genutils import debugx, dir2 |
|
84 | from IPython.utils.genutils import debugx, dir2 | |
90 |
|
85 | |||
|
86 | #----------------------------------------------------------------------------- | |||
|
87 | # Globals | |||
|
88 | #----------------------------------------------------------------------------- | |||
|
89 | ||||
|
90 | # Public API | |||
91 | __all__ = ['Completer','IPCompleter'] |
|
91 | __all__ = ['Completer','IPCompleter'] | |
92 |
|
92 | |||
|
93 | if sys.platform == 'win32': | |||
|
94 | PROTECTABLES = ' ' | |||
|
95 | else: | |||
|
96 | PROTECTABLES = ' ()' | |||
|
97 | ||||
|
98 | #----------------------------------------------------------------------------- | |||
|
99 | # Main functions and classes | |||
|
100 | #----------------------------------------------------------------------------- | |||
|
101 | ||||
|
102 | def protect_filename(s): | |||
|
103 | """Escape a string to protect certain characters.""" | |||
|
104 | ||||
|
105 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) | |||
|
106 | for ch in s]) | |||
|
107 | ||||
|
108 | ||||
|
109 | def single_dir_expand(matches): | |||
|
110 | "Recursively expand match lists containing a single dir." | |||
|
111 | ||||
|
112 | if len(matches) == 1 and os.path.isdir(matches[0]): | |||
|
113 | # Takes care of links to directories also. Use '/' | |||
|
114 | # explicitly, even under Windows, so that name completions | |||
|
115 | # don't end up escaped. | |||
|
116 | d = matches[0] | |||
|
117 | if d[-1] in ['/','\\']: | |||
|
118 | d = d[:-1] | |||
|
119 | ||||
|
120 | subdirs = os.listdir(d) | |||
|
121 | if subdirs: | |||
|
122 | matches = [ (d + '/' + p) for p in subdirs] | |||
|
123 | return single_dir_expand(matches) | |||
|
124 | else: | |||
|
125 | return matches | |||
|
126 | else: | |||
|
127 | return matches | |||
|
128 | ||||
|
129 | class Bunch: pass | |||
|
130 | ||||
93 | class Completer: |
|
131 | class Completer: | |
94 | def __init__(self,namespace=None,global_namespace=None): |
|
132 | def __init__(self,namespace=None,global_namespace=None): | |
95 | """Create a new completer for the command line. |
|
133 | """Create a new completer for the command line. | |
96 |
|
134 | |||
97 | Completer([namespace,global_namespace]) -> completer instance. |
|
135 | Completer([namespace,global_namespace]) -> completer instance. | |
98 |
|
136 | |||
99 | If unspecified, the default namespace where completions are performed |
|
137 | If unspecified, the default namespace where completions are performed | |
100 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
138 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
101 | given as dictionaries. |
|
139 | given as dictionaries. | |
102 |
|
140 | |||
103 | An optional second namespace can be given. This allows the completer |
|
141 | An optional second namespace can be given. This allows the completer | |
104 | to handle cases where both the local and global scopes need to be |
|
142 | to handle cases where both the local and global scopes need to be | |
105 | distinguished. |
|
143 | distinguished. | |
106 |
|
144 | |||
107 | Completer instances should be used as the completion mechanism of |
|
145 | Completer instances should be used as the completion mechanism of | |
108 | readline via the set_completer() call: |
|
146 | readline via the set_completer() call: | |
109 |
|
147 | |||
110 | readline.set_completer(Completer(my_namespace).complete) |
|
148 | readline.set_completer(Completer(my_namespace).complete) | |
111 | """ |
|
149 | """ | |
112 |
|
150 | |||
113 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
151 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
114 | # specific namespace or to use __main__.__dict__. This will allow us |
|
152 | # specific namespace or to use __main__.__dict__. This will allow us | |
115 | # to bind to __main__.__dict__ at completion time, not now. |
|
153 | # to bind to __main__.__dict__ at completion time, not now. | |
116 | if namespace is None: |
|
154 | if namespace is None: | |
117 | self.use_main_ns = 1 |
|
155 | self.use_main_ns = 1 | |
118 | else: |
|
156 | else: | |
119 | self.use_main_ns = 0 |
|
157 | self.use_main_ns = 0 | |
120 | self.namespace = namespace |
|
158 | self.namespace = namespace | |
121 |
|
159 | |||
122 | # The global namespace, if given, can be bound directly |
|
160 | # The global namespace, if given, can be bound directly | |
123 | if global_namespace is None: |
|
161 | if global_namespace is None: | |
124 | self.global_namespace = {} |
|
162 | self.global_namespace = {} | |
125 | else: |
|
163 | else: | |
126 | self.global_namespace = global_namespace |
|
164 | self.global_namespace = global_namespace | |
127 |
|
165 | |||
128 | def complete(self, text, state): |
|
166 | def complete(self, text, state): | |
129 | """Return the next possible completion for 'text'. |
|
167 | """Return the next possible completion for 'text'. | |
130 |
|
168 | |||
131 | This is called successively with state == 0, 1, 2, ... until it |
|
169 | This is called successively with state == 0, 1, 2, ... until it | |
132 | returns None. The completion should begin with 'text'. |
|
170 | returns None. The completion should begin with 'text'. | |
133 |
|
171 | |||
134 | """ |
|
172 | """ | |
135 | if self.use_main_ns: |
|
173 | if self.use_main_ns: | |
136 | self.namespace = __main__.__dict__ |
|
174 | self.namespace = __main__.__dict__ | |
137 |
|
175 | |||
138 | if state == 0: |
|
176 | if state == 0: | |
139 | if "." in text: |
|
177 | if "." in text: | |
140 | self.matches = self.attr_matches(text) |
|
178 | self.matches = self.attr_matches(text) | |
141 | else: |
|
179 | else: | |
142 | self.matches = self.global_matches(text) |
|
180 | self.matches = self.global_matches(text) | |
143 | try: |
|
181 | try: | |
144 | return self.matches[state] |
|
182 | return self.matches[state] | |
145 | except IndexError: |
|
183 | except IndexError: | |
146 | return None |
|
184 | return None | |
147 |
|
185 | |||
148 | def global_matches(self, text): |
|
186 | def global_matches(self, text): | |
149 | """Compute matches when text is a simple name. |
|
187 | """Compute matches when text is a simple name. | |
150 |
|
188 | |||
151 | Return a list of all keywords, built-in functions and names currently |
|
189 | Return a list of all keywords, built-in functions and names currently | |
152 | defined in self.namespace or self.global_namespace that match. |
|
190 | defined in self.namespace or self.global_namespace that match. | |
153 |
|
191 | |||
154 | """ |
|
192 | """ | |
|
193 | #print 'Completer->global_matches, txt=%r' % text # dbg | |||
155 | matches = [] |
|
194 | matches = [] | |
156 | match_append = matches.append |
|
195 | match_append = matches.append | |
157 | n = len(text) |
|
196 | n = len(text) | |
158 | for lst in [keyword.kwlist, |
|
197 | for lst in [keyword.kwlist, | |
159 | __builtin__.__dict__.keys(), |
|
198 | __builtin__.__dict__.keys(), | |
160 | self.namespace.keys(), |
|
199 | self.namespace.keys(), | |
161 | self.global_namespace.keys()]: |
|
200 | self.global_namespace.keys()]: | |
162 | for word in lst: |
|
201 | for word in lst: | |
163 | if word[:n] == text and word != "__builtins__": |
|
202 | if word[:n] == text and word != "__builtins__": | |
164 | match_append(word) |
|
203 | match_append(word) | |
165 | return matches |
|
204 | return matches | |
166 |
|
205 | |||
167 | def attr_matches(self, text): |
|
206 | def attr_matches(self, text): | |
168 | """Compute matches when text contains a dot. |
|
207 | """Compute matches when text contains a dot. | |
169 |
|
208 | |||
170 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
209 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
171 | evaluatable in self.namespace or self.global_namespace, it will be |
|
210 | evaluatable in self.namespace or self.global_namespace, it will be | |
172 | evaluated and its attributes (as revealed by dir()) are used as |
|
211 | evaluated and its attributes (as revealed by dir()) are used as | |
173 | possible completions. (For class instances, class members are are |
|
212 | possible completions. (For class instances, class members are are | |
174 | also considered.) |
|
213 | also considered.) | |
175 |
|
214 | |||
176 | WARNING: this can still invoke arbitrary C code, if an object |
|
215 | WARNING: this can still invoke arbitrary C code, if an object | |
177 | with a __getattr__ hook is evaluated. |
|
216 | with a __getattr__ hook is evaluated. | |
178 |
|
217 | |||
179 | """ |
|
218 | """ | |
180 | import re |
|
219 | import re | |
181 |
|
220 | |||
|
221 | #print 'Completer->attr_matches, txt=%r' % text # dbg | |||
182 | # Another option, seems to work great. Catches things like ''.<tab> |
|
222 | # Another option, seems to work great. Catches things like ''.<tab> | |
183 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
223 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
184 |
|
224 | |||
185 | if not m: |
|
225 | if not m: | |
186 | return [] |
|
226 | return [] | |
187 |
|
227 | |||
188 | expr, attr = m.group(1, 3) |
|
228 | expr, attr = m.group(1, 3) | |
189 | try: |
|
229 | try: | |
190 | obj = eval(expr, self.namespace) |
|
230 | obj = eval(expr, self.namespace) | |
191 | except: |
|
231 | except: | |
192 | try: |
|
232 | try: | |
193 | obj = eval(expr, self.global_namespace) |
|
233 | obj = eval(expr, self.global_namespace) | |
194 | except: |
|
234 | except: | |
195 | return [] |
|
235 | return [] | |
196 |
|
236 | |||
197 | words = dir2(obj) |
|
237 | words = dir2(obj) | |
198 |
|
238 | |||
199 | try: |
|
239 | try: | |
200 | words = generics.complete_object(obj, words) |
|
240 | words = generics.complete_object(obj, words) | |
201 | except TryNext: |
|
241 | except TryNext: | |
202 | pass |
|
242 | pass | |
203 | # Build match list to return |
|
243 | # Build match list to return | |
204 | n = len(attr) |
|
244 | n = len(attr) | |
205 | 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 ] | |
206 | return res |
|
246 | return res | |
207 |
|
247 | |||
|
248 | ||||
208 | class IPCompleter(Completer): |
|
249 | class IPCompleter(Completer): | |
209 | """Extension of the completer class with IPython-specific features""" |
|
250 | """Extension of the completer class with IPython-specific features""" | |
210 |
|
251 | |||
211 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
252 | def __init__(self,shell,namespace=None,global_namespace=None, | |
212 | omit__names=0,alias_table=None): |
|
253 | omit__names=0,alias_table=None): | |
213 | """IPCompleter() -> completer |
|
254 | """IPCompleter() -> completer | |
214 |
|
255 | |||
215 | Return a completer object suitable for use by the readline library |
|
256 | Return a completer object suitable for use by the readline library | |
216 | via readline.set_completer(). |
|
257 | via readline.set_completer(). | |
217 |
|
258 | |||
218 | Inputs: |
|
259 | Inputs: | |
219 |
|
260 | |||
220 | - shell: a pointer to the ipython shell itself. This is needed |
|
261 | - shell: a pointer to the ipython shell itself. This is needed | |
221 | because this completer knows about magic functions, and those can |
|
262 | because this completer knows about magic functions, and those can | |
222 | only be accessed via the ipython instance. |
|
263 | only be accessed via the ipython instance. | |
223 |
|
264 | |||
224 | - namespace: an optional dict where completions are performed. |
|
265 | - namespace: an optional dict where completions are performed. | |
225 |
|
266 | |||
226 | - global_namespace: secondary optional dict for completions, to |
|
267 | - global_namespace: secondary optional dict for completions, to | |
227 | handle cases (such as IPython embedded inside functions) where |
|
268 | handle cases (such as IPython embedded inside functions) where | |
228 | both Python scopes are visible. |
|
269 | both Python scopes are visible. | |
229 |
|
270 | |||
230 | - The optional omit__names parameter sets the completer to omit the |
|
271 | - The optional omit__names parameter sets the completer to omit the | |
231 | 'magic' names (__magicname__) for python objects unless the text |
|
272 | 'magic' names (__magicname__) for python objects unless the text | |
232 | to be completed explicitly starts with one or more underscores. |
|
273 | to be completed explicitly starts with one or more underscores. | |
233 |
|
274 | |||
234 | - If alias_table is supplied, it should be a dictionary of aliases |
|
275 | - If alias_table is supplied, it should be a dictionary of aliases | |
235 | to complete. """ |
|
276 | to complete. """ | |
236 |
|
277 | |||
237 | Completer.__init__(self,namespace,global_namespace) |
|
278 | Completer.__init__(self,namespace,global_namespace) | |
238 | self.magic_prefix = shell.name+'.magic_' |
|
279 | ||
239 | self.magic_escape = ESC_MAGIC |
|
280 | self.magic_escape = ESC_MAGIC | |
240 | self.readline = readline |
|
281 | self.readline = readline | |
241 | delims = self.readline.get_completer_delims() |
|
282 | delims = self.readline.get_completer_delims() | |
242 | delims = delims.replace(self.magic_escape,'') |
|
283 | delims = delims.replace(self.magic_escape,'') | |
243 | self.readline.set_completer_delims(delims) |
|
284 | self.readline.set_completer_delims(delims) | |
244 | self.get_line_buffer = self.readline.get_line_buffer |
|
285 | self.get_line_buffer = self.readline.get_line_buffer | |
245 | self.get_endidx = self.readline.get_endidx |
|
286 | self.get_endidx = self.readline.get_endidx | |
246 | self.omit__names = omit__names |
|
287 | self.omit__names = omit__names | |
247 |
self.merge_completions = shell.readline_merge_completions |
|
288 | self.merge_completions = shell.readline_merge_completions | |
|
289 | self.shell = shell.shell | |||
248 | if alias_table is None: |
|
290 | if alias_table is None: | |
249 | alias_table = {} |
|
291 | alias_table = {} | |
250 | self.alias_table = alias_table |
|
292 | self.alias_table = alias_table | |
251 | # Regexp to split filenames with spaces in them |
|
293 | # Regexp to split filenames with spaces in them | |
252 | self.space_name_re = re.compile(r'([^\\] )') |
|
294 | self.space_name_re = re.compile(r'([^\\] )') | |
253 | # Hold a local ref. to glob.glob for speed |
|
295 | # Hold a local ref. to glob.glob for speed | |
254 | self.glob = glob.glob |
|
296 | self.glob = glob.glob | |
255 |
|
297 | |||
256 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
298 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
257 | # buffers, to avoid completion problems. |
|
299 | # buffers, to avoid completion problems. | |
258 | term = os.environ.get('TERM','xterm') |
|
300 | term = os.environ.get('TERM','xterm') | |
259 | self.dumb_terminal = term in ['dumb','emacs'] |
|
301 | self.dumb_terminal = term in ['dumb','emacs'] | |
260 |
|
302 | |||
261 | # Special handling of backslashes needed in win32 platforms |
|
303 | # Special handling of backslashes needed in win32 platforms | |
262 | if sys.platform == "win32": |
|
304 | if sys.platform == "win32": | |
263 | self.clean_glob = self._clean_glob_win32 |
|
305 | self.clean_glob = self._clean_glob_win32 | |
264 | else: |
|
306 | else: | |
265 | self.clean_glob = self._clean_glob |
|
307 | self.clean_glob = self._clean_glob | |
|
308 | ||||
|
309 | # All active matcher routines for completion | |||
266 | self.matchers = [self.python_matches, |
|
310 | self.matchers = [self.python_matches, | |
267 | self.file_matches, |
|
311 | self.file_matches, | |
|
312 | self.magic_matches, | |||
268 | self.alias_matches, |
|
313 | self.alias_matches, | |
269 | self.python_func_kw_matches] |
|
314 | self.python_func_kw_matches] | |
270 |
|
||||
271 |
|
315 | |||
272 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
316 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
273 | def all_completions(self, text): |
|
317 | def all_completions(self, text): | |
274 | """Return all possible completions for the benefit of emacs.""" |
|
318 | """Return all possible completions for the benefit of emacs.""" | |
275 |
|
319 | |||
276 | completions = [] |
|
320 | completions = [] | |
277 | comp_append = completions.append |
|
321 | comp_append = completions.append | |
278 | try: |
|
322 | try: | |
279 | for i in xrange(sys.maxint): |
|
323 | for i in xrange(sys.maxint): | |
280 | res = self.complete(text, i) |
|
324 | res = self.complete(text, i) | |
281 |
|
325 | if not res: | ||
282 |
|
|
326 | break | |
283 |
|
||||
284 | comp_append(res) |
|
327 | comp_append(res) | |
285 | #XXX workaround for ``notDefined.<tab>`` |
|
328 | #XXX workaround for ``notDefined.<tab>`` | |
286 | except NameError: |
|
329 | except NameError: | |
287 | pass |
|
330 | pass | |
288 | return completions |
|
331 | return completions | |
289 | # /end Alex Schmolck code. |
|
332 | # /end Alex Schmolck code. | |
290 |
|
333 | |||
291 | def _clean_glob(self,text): |
|
334 | def _clean_glob(self,text): | |
292 | return self.glob("%s*" % text) |
|
335 | return self.glob("%s*" % text) | |
293 |
|
336 | |||
294 | def _clean_glob_win32(self,text): |
|
337 | def _clean_glob_win32(self,text): | |
295 | return [f.replace("\\","/") |
|
338 | return [f.replace("\\","/") | |
296 | for f in self.glob("%s*" % text)] |
|
339 | for f in self.glob("%s*" % text)] | |
297 |
|
340 | |||
298 | def file_matches(self, text): |
|
341 | def file_matches(self, text): | |
299 | """Match filenames, expanding ~USER type strings. |
|
342 | """Match filenames, expanding ~USER type strings. | |
300 |
|
343 | |||
301 | Most of the seemingly convoluted logic in this completer is an |
|
344 | Most of the seemingly convoluted logic in this completer is an | |
302 | attempt to handle filenames with spaces in them. And yet it's not |
|
345 | attempt to handle filenames with spaces in them. And yet it's not | |
303 | quite perfect, because Python's readline doesn't expose all of the |
|
346 | quite perfect, because Python's readline doesn't expose all of the | |
304 | GNU readline details needed for this to be done correctly. |
|
347 | GNU readline details needed for this to be done correctly. | |
305 |
|
348 | |||
306 | For a filename with a space in it, the printed completions will be |
|
349 | For a filename with a space in it, the printed completions will be | |
307 | only the parts after what's already been typed (instead of the |
|
350 | only the parts after what's already been typed (instead of the | |
308 | full completions, as is normally done). I don't think with the |
|
351 | full completions, as is normally done). I don't think with the | |
309 | current (as of Python 2.3) Python readline it's possible to do |
|
352 | current (as of Python 2.3) Python readline it's possible to do | |
310 | better.""" |
|
353 | better.""" | |
311 |
|
354 | |||
312 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
355 | #print 'Completer->file_matches: <%s>' % text # dbg | |
313 |
|
356 | |||
314 | # chars that require escaping with backslash - i.e. chars |
|
357 | # chars that require escaping with backslash - i.e. chars | |
315 | # that readline treats incorrectly as delimiters, but we |
|
358 | # that readline treats incorrectly as delimiters, but we | |
316 | # don't want to treat as delimiters in filename matching |
|
359 | # don't want to treat as delimiters in filename matching | |
317 | # when escaped with backslash |
|
360 | # when escaped with backslash | |
318 |
|
361 | |||
319 | if sys.platform == 'win32': |
|
|||
320 | protectables = ' ' |
|
|||
321 | else: |
|
|||
322 | protectables = ' ()' |
|
|||
323 |
|
||||
324 | if text.startswith('!'): |
|
362 | if text.startswith('!'): | |
325 | text = text[1:] |
|
363 | text = text[1:] | |
326 | text_prefix = '!' |
|
364 | text_prefix = '!' | |
327 | else: |
|
365 | else: | |
328 | text_prefix = '' |
|
366 | text_prefix = '' | |
329 |
|
367 | |||
330 | def protect_filename(s): |
|
|||
331 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
|||
332 | for ch in s]) |
|
|||
333 |
|
||||
334 | def single_dir_expand(matches): |
|
|||
335 | "Recursively expand match lists containing a single dir." |
|
|||
336 |
|
||||
337 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
|||
338 | # Takes care of links to directories also. Use '/' |
|
|||
339 | # explicitly, even under Windows, so that name completions |
|
|||
340 | # don't end up escaped. |
|
|||
341 | d = matches[0] |
|
|||
342 | if d[-1] in ['/','\\']: |
|
|||
343 | d = d[:-1] |
|
|||
344 |
|
||||
345 | subdirs = os.listdir(d) |
|
|||
346 | if subdirs: |
|
|||
347 | matches = [ (d + '/' + p) for p in subdirs] |
|
|||
348 | return single_dir_expand(matches) |
|
|||
349 | else: |
|
|||
350 | return matches |
|
|||
351 | else: |
|
|||
352 | return matches |
|
|||
353 |
|
||||
354 | lbuf = self.lbuf |
|
368 | lbuf = self.lbuf | |
355 | open_quotes = 0 # track strings with open quotes |
|
369 | open_quotes = 0 # track strings with open quotes | |
356 | try: |
|
370 | try: | |
357 | lsplit = shlex.split(lbuf)[-1] |
|
371 | lsplit = shlex.split(lbuf)[-1] | |
358 | except ValueError: |
|
372 | except ValueError: | |
359 | # typically an unmatched ", or backslash without escaped char. |
|
373 | # typically an unmatched ", or backslash without escaped char. | |
360 | if lbuf.count('"')==1: |
|
374 | if lbuf.count('"')==1: | |
361 | open_quotes = 1 |
|
375 | open_quotes = 1 | |
362 | lsplit = lbuf.split('"')[-1] |
|
376 | lsplit = lbuf.split('"')[-1] | |
363 | elif lbuf.count("'")==1: |
|
377 | elif lbuf.count("'")==1: | |
364 | open_quotes = 1 |
|
378 | open_quotes = 1 | |
365 | lsplit = lbuf.split("'")[-1] |
|
379 | lsplit = lbuf.split("'")[-1] | |
366 | else: |
|
380 | else: | |
367 | return [] |
|
381 | return [] | |
368 | except IndexError: |
|
382 | except IndexError: | |
369 | # tab pressed on empty line |
|
383 | # tab pressed on empty line | |
370 | lsplit = "" |
|
384 | lsplit = "" | |
371 |
|
385 | |||
372 | if lsplit != protect_filename(lsplit): |
|
386 | if lsplit != protect_filename(lsplit): | |
373 | # if protectables are found, do matching on the whole escaped |
|
387 | # if protectables are found, do matching on the whole escaped | |
374 | # name |
|
388 | # name | |
375 | has_protectables = 1 |
|
389 | has_protectables = 1 | |
376 | text0,text = text,lsplit |
|
390 | text0,text = text,lsplit | |
377 | else: |
|
391 | else: | |
378 | has_protectables = 0 |
|
392 | has_protectables = 0 | |
379 | text = os.path.expanduser(text) |
|
393 | text = os.path.expanduser(text) | |
380 |
|
394 | |||
381 | if text == "": |
|
395 | if text == "": | |
382 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
396 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
383 |
|
397 | |||
384 | m0 = self.clean_glob(text.replace('\\','')) |
|
398 | m0 = self.clean_glob(text.replace('\\','')) | |
385 | if has_protectables: |
|
399 | if has_protectables: | |
386 | # If we had protectables, we need to revert our changes to the |
|
400 | # If we had protectables, we need to revert our changes to the | |
387 | # beginning of filename so that we don't double-write the part |
|
401 | # beginning of filename so that we don't double-write the part | |
388 | # of the filename we have so far |
|
402 | # of the filename we have so far | |
389 | len_lsplit = len(lsplit) |
|
403 | len_lsplit = len(lsplit) | |
390 | matches = [text_prefix + text0 + |
|
404 | matches = [text_prefix + text0 + | |
391 | protect_filename(f[len_lsplit:]) for f in m0] |
|
405 | protect_filename(f[len_lsplit:]) for f in m0] | |
392 | else: |
|
406 | else: | |
393 | if open_quotes: |
|
407 | if open_quotes: | |
394 | # if we have a string with an open quote, we don't need to |
|
408 | # if we have a string with an open quote, we don't need to | |
395 | # protect the names at all (and we _shouldn't_, as it |
|
409 | # protect the names at all (and we _shouldn't_, as it | |
396 | # would cause bugs when the filesystem call is made). |
|
410 | # would cause bugs when the filesystem call is made). | |
397 | matches = m0 |
|
411 | matches = m0 | |
398 | else: |
|
412 | else: | |
399 | matches = [text_prefix + |
|
413 | matches = [text_prefix + | |
400 | protect_filename(f) for f in m0] |
|
414 | protect_filename(f) for f in m0] | |
401 |
|
415 | |||
402 | #print 'mm',matches # dbg |
|
416 | #print 'mm',matches # dbg | |
403 | return single_dir_expand(matches) |
|
417 | return single_dir_expand(matches) | |
404 |
|
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 | ||||
405 | def alias_matches(self, text): |
|
429 | def alias_matches(self, text): | |
406 | """Match internal system aliases""" |
|
430 | """Match internal system aliases""" | |
407 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
431 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg | |
408 |
|
432 | |||
409 | # if we are not in the first 'item', alias matching |
|
433 | # if we are not in the first 'item', alias matching | |
410 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
434 | # doesn't make sense - unless we are starting with 'sudo' command. | |
411 |
if ' ' in self.lbuf.lstrip() and |
|
435 | if ' ' in self.lbuf.lstrip() and \ | |
|
436 | not self.lbuf.lstrip().startswith('sudo'): | |||
412 | return [] |
|
437 | return [] | |
413 | text = os.path.expanduser(text) |
|
438 | text = os.path.expanduser(text) | |
414 | aliases = self.alias_table.keys() |
|
439 | aliases = self.alias_table.keys() | |
415 | if text == "": |
|
440 | if text == "": | |
416 | return aliases |
|
441 | return aliases | |
417 | else: |
|
442 | else: | |
418 | return [alias for alias in aliases if alias.startswith(text)] |
|
443 | return [alias for alias in aliases if alias.startswith(text)] | |
419 |
|
444 | |||
420 | def python_matches(self,text): |
|
445 | def python_matches(self,text): | |
421 | """Match attributes or global python names""" |
|
446 | """Match attributes or global python names""" | |
422 |
|
447 | |||
423 |
#print 'Completer->python_matches, txt= |
|
448 | #print 'Completer->python_matches, txt=%r' % text # dbg | |
424 | if "." in text: |
|
449 | if "." in text: | |
425 | try: |
|
450 | try: | |
426 | matches = self.attr_matches(text) |
|
451 | matches = self.attr_matches(text) | |
427 | if text.endswith('.') and self.omit__names: |
|
452 | if text.endswith('.') and self.omit__names: | |
428 | if self.omit__names == 1: |
|
453 | if self.omit__names == 1: | |
429 | # true if txt is _not_ a __ name, false otherwise: |
|
454 | # true if txt is _not_ a __ name, false otherwise: | |
430 | no__name = (lambda txt: |
|
455 | no__name = (lambda txt: | |
431 | re.match(r'.*\.__.*?__',txt) is None) |
|
456 | re.match(r'.*\.__.*?__',txt) is None) | |
432 | else: |
|
457 | else: | |
433 | # true if txt is _not_ a _ name, false otherwise: |
|
458 | # true if txt is _not_ a _ name, false otherwise: | |
434 | no__name = (lambda txt: |
|
459 | no__name = (lambda txt: | |
435 | re.match(r'.*\._.*?',txt) is None) |
|
460 | re.match(r'.*\._.*?',txt) is None) | |
436 | matches = filter(no__name, matches) |
|
461 | matches = filter(no__name, matches) | |
437 | except NameError: |
|
462 | except NameError: | |
438 | # catches <undefined attributes>.<tab> |
|
463 | # catches <undefined attributes>.<tab> | |
439 | matches = [] |
|
464 | matches = [] | |
440 | else: |
|
465 | else: | |
441 | matches = self.global_matches(text) |
|
466 | matches = self.global_matches(text) | |
442 | # this is so completion finds magics when automagic is on: |
|
467 | ||
443 | if (matches == [] and |
|
|||
444 | not text.startswith(os.sep) and |
|
|||
445 | not ' ' in self.lbuf): |
|
|||
446 | matches = self.attr_matches(self.magic_prefix+text) |
|
|||
447 | return matches |
|
468 | return matches | |
448 |
|
469 | |||
449 | def _default_arguments(self, obj): |
|
470 | def _default_arguments(self, obj): | |
450 | """Return the list of default arguments of obj if it is callable, |
|
471 | """Return the list of default arguments of obj if it is callable, | |
451 | or empty list otherwise.""" |
|
472 | or empty list otherwise.""" | |
452 |
|
473 | |||
453 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
474 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
454 | # for classes, check for __init__,__new__ |
|
475 | # for classes, check for __init__,__new__ | |
455 | if inspect.isclass(obj): |
|
476 | if inspect.isclass(obj): | |
456 | obj = (getattr(obj,'__init__',None) or |
|
477 | obj = (getattr(obj,'__init__',None) or | |
457 | getattr(obj,'__new__',None)) |
|
478 | getattr(obj,'__new__',None)) | |
458 | # for all others, check if they are __call__able |
|
479 | # for all others, check if they are __call__able | |
459 | elif hasattr(obj, '__call__'): |
|
480 | elif hasattr(obj, '__call__'): | |
460 | obj = obj.__call__ |
|
481 | obj = obj.__call__ | |
461 | # XXX: is there a way to handle the builtins ? |
|
482 | # XXX: is there a way to handle the builtins ? | |
462 | try: |
|
483 | try: | |
463 | args,_,_1,defaults = inspect.getargspec(obj) |
|
484 | args,_,_1,defaults = inspect.getargspec(obj) | |
464 | if defaults: |
|
485 | if defaults: | |
465 | return args[-len(defaults):] |
|
486 | return args[-len(defaults):] | |
466 | except TypeError: pass |
|
487 | except TypeError: pass | |
467 | return [] |
|
488 | return [] | |
468 |
|
489 | |||
469 | def python_func_kw_matches(self,text): |
|
490 | def python_func_kw_matches(self,text): | |
470 | """Match named parameters (kwargs) of the last open function""" |
|
491 | """Match named parameters (kwargs) of the last open function""" | |
471 |
|
492 | |||
472 | if "." in text: # a parameter cannot be dotted |
|
493 | if "." in text: # a parameter cannot be dotted | |
473 | return [] |
|
494 | return [] | |
474 | try: regexp = self.__funcParamsRegex |
|
495 | try: regexp = self.__funcParamsRegex | |
475 | except AttributeError: |
|
496 | except AttributeError: | |
476 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
497 | regexp = self.__funcParamsRegex = re.compile(r''' | |
477 | '.*?' | # single quoted strings or |
|
498 | '.*?' | # single quoted strings or | |
478 | ".*?" | # double quoted strings or |
|
499 | ".*?" | # double quoted strings or | |
479 | \w+ | # identifier |
|
500 | \w+ | # identifier | |
480 | \S # other characters |
|
501 | \S # other characters | |
481 | ''', re.VERBOSE | re.DOTALL) |
|
502 | ''', re.VERBOSE | re.DOTALL) | |
482 | # 1. find the nearest identifier that comes before an unclosed |
|
503 | # 1. find the nearest identifier that comes before an unclosed | |
483 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
504 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
484 | tokens = regexp.findall(self.get_line_buffer()) |
|
505 | tokens = regexp.findall(self.get_line_buffer()) | |
485 | tokens.reverse() |
|
506 | tokens.reverse() | |
486 | iterTokens = iter(tokens); openPar = 0 |
|
507 | iterTokens = iter(tokens); openPar = 0 | |
487 | for token in iterTokens: |
|
508 | for token in iterTokens: | |
488 | if token == ')': |
|
509 | if token == ')': | |
489 | openPar -= 1 |
|
510 | openPar -= 1 | |
490 | elif token == '(': |
|
511 | elif token == '(': | |
491 | openPar += 1 |
|
512 | openPar += 1 | |
492 | if openPar > 0: |
|
513 | if openPar > 0: | |
493 | # found the last unclosed parenthesis |
|
514 | # found the last unclosed parenthesis | |
494 | break |
|
515 | break | |
495 | else: |
|
516 | else: | |
496 | return [] |
|
517 | return [] | |
497 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
518 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
498 | ids = [] |
|
519 | ids = [] | |
499 | isId = re.compile(r'\w+$').match |
|
520 | isId = re.compile(r'\w+$').match | |
500 | while True: |
|
521 | while True: | |
501 | try: |
|
522 | try: | |
502 | ids.append(iterTokens.next()) |
|
523 | ids.append(iterTokens.next()) | |
503 | if not isId(ids[-1]): |
|
524 | if not isId(ids[-1]): | |
504 | ids.pop(); break |
|
525 | ids.pop(); break | |
505 | if not iterTokens.next() == '.': |
|
526 | if not iterTokens.next() == '.': | |
506 | break |
|
527 | break | |
507 | except StopIteration: |
|
528 | except StopIteration: | |
508 | break |
|
529 | break | |
509 | # lookup the candidate callable matches either using global_matches |
|
530 | # lookup the candidate callable matches either using global_matches | |
510 | # or attr_matches for dotted names |
|
531 | # or attr_matches for dotted names | |
511 | if len(ids) == 1: |
|
532 | if len(ids) == 1: | |
512 | callableMatches = self.global_matches(ids[0]) |
|
533 | callableMatches = self.global_matches(ids[0]) | |
513 | else: |
|
534 | else: | |
514 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
535 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
515 | argMatches = [] |
|
536 | argMatches = [] | |
516 | for callableMatch in callableMatches: |
|
537 | for callableMatch in callableMatches: | |
517 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
538 | try: | |
|
539 | namedArgs = self._default_arguments(eval(callableMatch, | |||
518 | self.namespace)) |
|
540 | self.namespace)) | |
519 |
except: |
|
541 | except: | |
|
542 | continue | |||
520 | for namedArg in namedArgs: |
|
543 | for namedArg in namedArgs: | |
521 | if namedArg.startswith(text): |
|
544 | if namedArg.startswith(text): | |
522 | argMatches.append("%s=" %namedArg) |
|
545 | argMatches.append("%s=" %namedArg) | |
523 | return argMatches |
|
546 | return argMatches | |
524 |
|
547 | |||
525 | def dispatch_custom_completer(self,text): |
|
548 | def dispatch_custom_completer(self,text): | |
526 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
549 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg | |
527 | line = self.full_lbuf |
|
550 | line = self.full_lbuf | |
528 | if not line.strip(): |
|
551 | if not line.strip(): | |
529 | return None |
|
552 | return None | |
530 |
|
553 | |||
531 |
event = |
|
554 | event = Bunch() | |
532 | event.line = line |
|
555 | event.line = line | |
533 | event.symbol = text |
|
556 | event.symbol = text | |
534 | cmd = line.split(None,1)[0] |
|
557 | cmd = line.split(None,1)[0] | |
535 | event.command = cmd |
|
558 | event.command = cmd | |
536 | #print "\ncustom:{%s]\n" % event # dbg |
|
559 | #print "\ncustom:{%s]\n" % event # dbg | |
537 |
|
560 | |||
538 | # for foo etc, try also to find completer for %foo |
|
561 | # for foo etc, try also to find completer for %foo | |
539 | if not cmd.startswith(self.magic_escape): |
|
562 | if not cmd.startswith(self.magic_escape): | |
540 | try_magic = self.custom_completers.s_matches( |
|
563 | try_magic = self.custom_completers.s_matches( | |
541 | self.magic_escape + cmd) |
|
564 | self.magic_escape + cmd) | |
542 | else: |
|
565 | else: | |
543 | try_magic = [] |
|
566 | try_magic = [] | |
544 |
|
||||
545 |
|
567 | |||
546 | for c in itertools.chain( |
|
568 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
547 | self.custom_completers.s_matches(cmd), |
|
|||
548 | try_magic, |
|
569 | try_magic, | |
549 | self.custom_completers.flat_matches(self.lbuf)): |
|
570 | self.custom_completers.flat_matches(self.lbuf)): | |
550 | #print "try",c # dbg |
|
571 | #print "try",c # dbg | |
551 | try: |
|
572 | try: | |
552 | res = c(event) |
|
573 | res = c(event) | |
553 | # first, try case sensitive match |
|
574 | # first, try case sensitive match | |
554 | withcase = [r for r in res if r.startswith(text)] |
|
575 | withcase = [r for r in res if r.startswith(text)] | |
555 | if withcase: |
|
576 | if withcase: | |
556 | return withcase |
|
577 | return withcase | |
557 | # if none, then case insensitive ones are ok too |
|
578 | # if none, then case insensitive ones are ok too | |
558 | return [r for r in res if r.lower().startswith(text.lower())] |
|
579 | text_low = text.lower() | |
|
580 | return [r for r in res if r.lower().startswith(text_low)] | |||
559 | except TryNext: |
|
581 | except TryNext: | |
560 | pass |
|
582 | pass | |
561 |
|
583 | |||
562 | return None |
|
584 | return None | |
563 |
|
585 | |||
564 | def complete(self, text, state,line_buffer=None): |
|
586 | def complete(self, text, state,line_buffer=None): | |
565 | """Return the next possible completion for 'text'. |
|
587 | """Return the next possible completion for 'text'. | |
566 |
|
588 | |||
567 | This is called successively with state == 0, 1, 2, ... until it |
|
589 | This is called successively with state == 0, 1, 2, ... until it | |
568 | returns None. The completion should begin with 'text'. |
|
590 | returns None. The completion should begin with 'text'. | |
569 |
|
591 | |||
570 | :Keywords: |
|
592 | :Keywords: | |
571 | - line_buffer: string |
|
593 | - line_buffer: string | |
572 | If not given, the completer attempts to obtain the current line buffer |
|
594 | If not given, the completer attempts to obtain the current line buffer | |
573 | via readline. This keyword allows clients which are requesting for |
|
595 | via readline. This keyword allows clients which are requesting for | |
574 | text completions in non-readline contexts to inform the completer of |
|
596 | text completions in non-readline contexts to inform the completer of | |
575 | the entire text. |
|
597 | the entire text. | |
576 | """ |
|
598 | """ | |
577 |
|
599 | |||
578 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
600 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
579 |
|
601 | |||
580 | # if there is only a tab on a line with only whitespace, instead |
|
602 | # if there is only a tab on a line with only whitespace, instead | |
581 | # of the mostly useless 'do you want to see all million |
|
603 | # of the mostly useless 'do you want to see all million | |
582 | # completions' message, just do the right thing and give the user |
|
604 | # completions' message, just do the right thing and give the user | |
583 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
605 | # his tab! Incidentally, this enables pasting of tabbed text from | |
584 | # an editor (as long as autoindent is off). |
|
606 | # an editor (as long as autoindent is off). | |
585 |
|
607 | |||
586 | # It should be noted that at least pyreadline still shows |
|
608 | # It should be noted that at least pyreadline still shows | |
587 | # file completions - is there a way around it? |
|
609 | # file completions - is there a way around it? | |
588 |
|
610 | |||
589 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
611 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we | |
590 | # don't interfere with their own tab-completion mechanism. |
|
612 | # don't interfere with their own tab-completion mechanism. | |
591 | if line_buffer is None: |
|
613 | if line_buffer is None: | |
592 | self.full_lbuf = self.get_line_buffer() |
|
614 | self.full_lbuf = self.get_line_buffer() | |
593 | else: |
|
615 | else: | |
594 | self.full_lbuf = line_buffer |
|
616 | self.full_lbuf = line_buffer | |
595 |
|
617 | |||
596 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
618 | if not (self.dumb_terminal or self.full_lbuf.strip()): | |
597 | self.readline.insert_text('\t') |
|
619 | self.readline.insert_text('\t') | |
598 | return None |
|
620 | return None | |
599 |
|
621 | |||
600 | magic_escape = self.magic_escape |
|
622 | magic_escape = self.magic_escape | |
601 | magic_prefix = self.magic_prefix |
|
|||
602 |
|
623 | |||
603 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
624 | self.lbuf = self.full_lbuf[:self.get_endidx()] | |
604 |
|
625 | |||
605 | try: |
|
626 | try: | |
606 |
if text.startswith( |
|
627 | if text.startswith('~'): | |
607 | text = text.replace(magic_escape,magic_prefix) |
|
|||
608 | elif text.startswith('~'): |
|
|||
609 | text = os.path.expanduser(text) |
|
628 | text = os.path.expanduser(text) | |
610 | if state == 0: |
|
629 | if state == 0: | |
611 | custom_res = self.dispatch_custom_completer(text) |
|
630 | custom_res = self.dispatch_custom_completer(text) | |
612 | if custom_res is not None: |
|
631 | if custom_res is not None: | |
613 | # did custom completers produce something? |
|
632 | # did custom completers produce something? | |
614 | self.matches = custom_res |
|
633 | self.matches = custom_res | |
615 | else: |
|
634 | else: | |
616 | # Extend the list of completions with the results of each |
|
635 | # Extend the list of completions with the results of each | |
617 | # matcher, so we return results to the user from all |
|
636 | # matcher, so we return results to the user from all | |
618 | # namespaces. |
|
637 | # namespaces. | |
619 | if self.merge_completions: |
|
638 | if self.merge_completions: | |
620 | self.matches = [] |
|
639 | self.matches = [] | |
621 | for matcher in self.matchers: |
|
640 | for matcher in self.matchers: | |
622 | self.matches.extend(matcher(text)) |
|
641 | self.matches.extend(matcher(text)) | |
623 | else: |
|
642 | else: | |
624 | for matcher in self.matchers: |
|
643 | for matcher in self.matchers: | |
625 | self.matches = matcher(text) |
|
644 | self.matches = matcher(text) | |
626 | if self.matches: |
|
645 | if self.matches: | |
627 | break |
|
646 | break | |
628 | def uniq(alist): |
|
647 | self.matches = list(set(self.matches)) | |
629 | set = {} |
|
|||
630 | return [set.setdefault(e,e) for e in alist if e not in set] |
|
|||
631 | self.matches = uniq(self.matches) |
|
|||
632 | try: |
|
648 | try: | |
633 | ret = self.matches[state].replace(magic_prefix,magic_escape) |
|
649 | #print "MATCH: %r" % self.matches[state] # dbg | |
634 |
return |
|
650 | return self.matches[state] | |
635 | except IndexError: |
|
651 | except IndexError: | |
636 | return None |
|
652 | return None | |
637 | except: |
|
653 | except: | |
638 | #from IPython.core.ultratb import AutoFormattedTB; # dbg |
|
654 | #from IPython.core.ultratb import AutoFormattedTB; # dbg | |
639 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
655 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
640 |
|
656 | |||
641 | # If completion fails, don't annoy the user. |
|
657 | # If completion fails, don't annoy the user. | |
642 | return None |
|
658 | return None |
@@ -1,325 +1,346 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A lightweight component system for IPython. |
|
4 | A lightweight component system for IPython. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | from copy import deepcopy |
|
23 | from copy import deepcopy | |
24 | import datetime |
|
24 | import datetime | |
25 | from weakref import WeakValueDictionary |
|
25 | from weakref import WeakValueDictionary | |
26 |
|
26 | |||
27 | from IPython.utils.importstring import import_item |
|
27 | from IPython.utils.importstring import import_item | |
28 | from IPython.config.loader import Config |
|
28 | from IPython.config.loader import Config | |
29 | from IPython.utils.traitlets import ( |
|
29 | from IPython.utils.traitlets import ( | |
30 | HasTraits, TraitError, MetaHasTraits, Instance, This |
|
30 | HasTraits, TraitError, MetaHasTraits, Instance, This | |
31 | ) |
|
31 | ) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
35 | # Helper classes for Components |
|
35 | # Helper classes for Components | |
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | class ComponentError(Exception): |
|
39 | class ComponentError(Exception): | |
40 | pass |
|
40 | pass | |
41 |
|
41 | |||
42 | class MetaComponentTracker(type): |
|
42 | class MetaComponentTracker(type): | |
43 | """A metaclass that tracks instances of Components and its subclasses.""" |
|
43 | """A metaclass that tracks instances of Components and its subclasses.""" | |
44 |
|
44 | |||
45 | def __init__(cls, name, bases, d): |
|
45 | def __init__(cls, name, bases, d): | |
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) |
|
46 | super(MetaComponentTracker, cls).__init__(name, bases, d) | |
47 | cls.__instance_refs = WeakValueDictionary() |
|
47 | cls.__instance_refs = WeakValueDictionary() | |
48 | cls.__numcreated = 0 |
|
48 | cls.__numcreated = 0 | |
49 |
|
49 | |||
50 | def __call__(cls, *args, **kw): |
|
50 | def __call__(cls, *args, **kw): | |
51 | """Called when a class is called (instantiated)!!! |
|
51 | """Called when a class is called (instantiated)!!! | |
52 |
|
52 | |||
53 | When a Component or subclass is instantiated, this is called and |
|
53 | When a Component or subclass is instantiated, this is called and | |
54 | the instance is saved in a WeakValueDictionary for tracking. |
|
54 | the instance is saved in a WeakValueDictionary for tracking. | |
55 | """ |
|
55 | """ | |
56 | instance = cls.__new__(cls, *args, **kw) |
|
56 | instance = cls.__new__(cls, *args, **kw) | |
57 |
|
57 | |||
58 | # Register the instance before __init__ is called so get_instances |
|
58 | # Register the instance before __init__ is called so get_instances | |
59 | # works inside __init__ methods! |
|
59 | # works inside __init__ methods! | |
60 | indices = cls.register_instance(instance) |
|
60 | indices = cls.register_instance(instance) | |
61 |
|
61 | |||
62 | # This is in a try/except because of the __init__ method fails, the |
|
62 | # This is in a try/except because of the __init__ method fails, the | |
63 | # instance is discarded and shouldn't be tracked. |
|
63 | # instance is discarded and shouldn't be tracked. | |
64 | try: |
|
64 | try: | |
65 | if isinstance(instance, cls): |
|
65 | if isinstance(instance, cls): | |
66 | cls.__init__(instance, *args, **kw) |
|
66 | cls.__init__(instance, *args, **kw) | |
67 | except: |
|
67 | except: | |
68 | # Unregister the instance because __init__ failed! |
|
68 | # Unregister the instance because __init__ failed! | |
69 | cls.unregister_instances(indices) |
|
69 | cls.unregister_instances(indices) | |
70 | raise |
|
70 | raise | |
71 | else: |
|
71 | else: | |
72 | return instance |
|
72 | return instance | |
73 |
|
73 | |||
74 | def register_instance(cls, instance): |
|
74 | def register_instance(cls, instance): | |
75 | """Register instance with cls and its subclasses.""" |
|
75 | """Register instance with cls and its subclasses.""" | |
76 | # indices is a list of the keys used to register the instance |
|
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. |
|
77 | # with. This list is needed if the instance needs to be unregistered. | |
78 | indices = [] |
|
78 | indices = [] | |
79 | for c in cls.__mro__: |
|
79 | for c in cls.__mro__: | |
80 | if issubclass(cls, c) and issubclass(c, Component): |
|
80 | if issubclass(cls, c) and issubclass(c, Component): | |
81 | c.__numcreated += 1 |
|
81 | c.__numcreated += 1 | |
82 | indices.append(c.__numcreated) |
|
82 | indices.append(c.__numcreated) | |
83 | c.__instance_refs[c.__numcreated] = instance |
|
83 | c.__instance_refs[c.__numcreated] = instance | |
84 | else: |
|
84 | else: | |
85 | break |
|
85 | break | |
86 | return indices |
|
86 | return indices | |
87 |
|
87 | |||
88 | def unregister_instances(cls, indices): |
|
88 | def unregister_instances(cls, indices): | |
89 | """Unregister instance with cls and its subclasses.""" |
|
89 | """Unregister instance with cls and its subclasses.""" | |
90 | for c, index in zip(cls.__mro__, indices): |
|
90 | for c, index in zip(cls.__mro__, indices): | |
91 | try: |
|
91 | try: | |
92 | del c.__instance_refs[index] |
|
92 | del c.__instance_refs[index] | |
93 | except KeyError: |
|
93 | except KeyError: | |
94 | pass |
|
94 | pass | |
95 |
|
95 | |||
96 | def clear_instances(cls): |
|
96 | def clear_instances(cls): | |
97 | """Clear all instances tracked by cls.""" |
|
97 | """Clear all instances tracked by cls.""" | |
98 | cls.__instance_refs.clear() |
|
98 | cls.__instance_refs.clear() | |
99 | cls.__numcreated = 0 |
|
99 | cls.__numcreated = 0 | |
100 |
|
100 | |||
101 | def get_instances(cls, name=None, root=None, klass=None): |
|
101 | def get_instances(cls, name=None, root=None, klass=None): | |
102 | """Get all instances of cls and its subclasses. |
|
102 | """Get all instances of cls and its subclasses. | |
103 |
|
103 | |||
104 | Parameters |
|
104 | Parameters | |
105 | ---------- |
|
105 | ---------- | |
106 | name : str |
|
106 | name : str | |
107 | Limit to components with this name. |
|
107 | Limit to components with this name. | |
108 | root : Component or subclass |
|
108 | root : Component or subclass | |
109 | Limit to components having this root. |
|
109 | Limit to components having this root. | |
110 | klass : class or str |
|
110 | klass : class or str | |
111 | Limits to instances of the class or its subclasses. If a str |
|
111 | Limits to instances of the class or its subclasses. If a str | |
112 | is given ut must be in the form 'foo.bar.MyClass'. The str |
|
112 | is given ut must be in the form 'foo.bar.MyClass'. The str | |
113 | form of this argument is useful for forward declarations. |
|
113 | form of this argument is useful for forward declarations. | |
114 | """ |
|
114 | """ | |
115 | if klass is not None: |
|
115 | if klass is not None: | |
116 | if isinstance(klass, basestring): |
|
116 | if isinstance(klass, basestring): | |
117 | klass = import_item(klass) |
|
117 | klass = import_item(klass) | |
118 | # Limit search to instances of klass for performance |
|
118 | # Limit search to instances of klass for performance | |
119 | if issubclass(klass, Component): |
|
119 | if issubclass(klass, Component): | |
120 | return klass.get_instances(name=name, root=root) |
|
120 | return klass.get_instances(name=name, root=root) | |
121 | instances = cls.__instance_refs.values() |
|
121 | instances = cls.__instance_refs.values() | |
122 | if name is not None: |
|
122 | if name is not None: | |
123 | instances = [i for i in instances if i.name == name] |
|
123 | instances = [i for i in instances if i.name == name] | |
124 | if klass is not None: |
|
124 | if klass is not None: | |
125 | instances = [i for i in instances if isinstance(i, klass)] |
|
125 | instances = [i for i in instances if isinstance(i, klass)] | |
126 | if root is not None: |
|
126 | if root is not None: | |
127 | instances = [i for i in instances if i.root == root] |
|
127 | instances = [i for i in instances if i.root == root] | |
128 | return instances |
|
128 | return instances | |
129 |
|
129 | |||
130 | def get_instances_by_condition(cls, call, name=None, root=None, |
|
130 | def get_instances_by_condition(cls, call, name=None, root=None, | |
131 | klass=None): |
|
131 | klass=None): | |
132 | """Get all instances of cls, i such that call(i)==True. |
|
132 | """Get all instances of cls, i such that call(i)==True. | |
133 |
|
133 | |||
134 | This also takes the ``name`` and ``root`` and ``classname`` |
|
134 | This also takes the ``name`` and ``root`` and ``classname`` | |
135 | arguments of :meth:`get_instance` |
|
135 | arguments of :meth:`get_instance` | |
136 | """ |
|
136 | """ | |
137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] |
|
137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | def masquerade_as(instance, cls): |
|
140 | def masquerade_as(instance, cls): | |
141 | """Let instance masquerade as an instance of cls. |
|
141 | """Let instance masquerade as an instance of cls. | |
142 |
|
142 | |||
143 | Sometimes, such as in testing code, it is useful to let a class |
|
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 |
|
144 | masquerade as another. Python, being duck typed, allows this by | |
145 | default. But, instances of components are tracked by their class type. |
|
145 | default. But, instances of components are tracked by their class type. | |
146 |
|
146 | |||
147 | After calling this, ``cls.get_instances()`` will return ``instance``. This |
|
147 | After calling this, ``cls.get_instances()`` will return ``instance``. This | |
148 | does not, however, cause ``isinstance(instance, cls)`` to return ``True``. |
|
148 | does not, however, cause ``isinstance(instance, cls)`` to return ``True``. | |
149 |
|
149 | |||
150 | Parameters |
|
150 | Parameters | |
151 | ---------- |
|
151 | ---------- | |
152 | instance : an instance of a Component or Component subclass |
|
152 | instance : an instance of a Component or Component subclass | |
153 | The instance that will pretend to be a cls. |
|
153 | The instance that will pretend to be a cls. | |
154 | cls : subclass of Component |
|
154 | cls : subclass of Component | |
155 | The Component subclass that instance will pretend to be. |
|
155 | The Component subclass that instance will pretend to be. | |
156 | """ |
|
156 | """ | |
157 | cls.register_instance(instance) |
|
157 | cls.register_instance(instance) | |
158 |
|
158 | |||
159 |
|
159 | |||
160 | class ComponentNameGenerator(object): |
|
160 | class __ComponentNameGenerator(object): | |
161 | """A Singleton to generate unique component names.""" |
|
161 | """A Singleton to generate unique component names.""" | |
162 |
|
162 | |||
163 | def __init__(self, prefix): |
|
163 | def __init__(self, prefix): | |
164 | self.prefix = prefix |
|
164 | self.prefix = prefix | |
165 | self.i = 0 |
|
165 | self.i = 0 | |
166 |
|
166 | |||
167 | def __call__(self): |
|
167 | def __call__(self): | |
168 | count = self.i |
|
168 | count = self.i | |
169 | self.i += 1 |
|
169 | self.i += 1 | |
170 | return "%s%s" % (self.prefix, count) |
|
170 | return "%s%s" % (self.prefix, count) | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | ComponentNameGenerator = ComponentNameGenerator('ipython.component') |
|
173 | ComponentNameGenerator = __ComponentNameGenerator('ipython.component') | |
174 |
|
174 | |||
175 |
|
175 | |||
176 | class MetaComponent(MetaHasTraits, MetaComponentTracker): |
|
176 | class MetaComponent(MetaHasTraits, MetaComponentTracker): | |
177 | pass |
|
177 | pass | |
178 |
|
178 | |||
179 |
|
179 | |||
180 | #----------------------------------------------------------------------------- |
|
180 | #----------------------------------------------------------------------------- | |
181 | # Component implementation |
|
181 | # Component implementation | |
182 | #----------------------------------------------------------------------------- |
|
182 | #----------------------------------------------------------------------------- | |
183 |
|
183 | |||
184 |
|
184 | |||
185 | class Component(HasTraits): |
|
185 | class Component(HasTraits): | |
186 |
|
186 | |||
187 | __metaclass__ = MetaComponent |
|
187 | __metaclass__ = MetaComponent | |
188 |
|
188 | |||
189 | # Traits are fun! |
|
189 | # Traits are fun! | |
190 | config = Instance(Config,(),{}) |
|
190 | config = Instance(Config,(),{}) | |
191 | parent = This() |
|
191 | parent = This() | |
192 | root = This() |
|
192 | root = This() | |
193 | created = None |
|
193 | created = None | |
194 |
|
194 | |||
195 | def __init__(self, parent, name=None, config=None): |
|
195 | def __init__(self, parent, name=None, config=None): | |
196 | """Create a component given a parent and possibly and name and config. |
|
196 | """Create a component given a parent and possibly and name and config. | |
197 |
|
197 | |||
198 | Parameters |
|
198 | Parameters | |
199 | ---------- |
|
199 | ---------- | |
200 | parent : Component subclass |
|
200 | parent : Component subclass | |
201 | The parent in the component graph. The parent is used |
|
201 | The parent in the component graph. The parent is used | |
202 | to get the root of the component graph. |
|
202 | to get the root of the component graph. | |
203 | name : str |
|
203 | name : str | |
204 | The unique name of the component. If empty, then a unique |
|
204 | The unique name of the component. If empty, then a unique | |
205 | one will be autogenerated. |
|
205 | one will be autogenerated. | |
206 | config : Config |
|
206 | config : Config | |
207 | If this is empty, self.config = parent.config, otherwise |
|
207 | If this is empty, self.config = parent.config, otherwise | |
208 | self.config = config and root.config is ignored. This argument |
|
208 | self.config = config and root.config is ignored. This argument | |
209 | should only be used to *override* the automatic inheritance of |
|
209 | should only be used to *override* the automatic inheritance of | |
210 | parent.config. If a caller wants to modify parent.config |
|
210 | parent.config. If a caller wants to modify parent.config | |
211 | (not override), the caller should make a copy and change |
|
211 | (not override), the caller should make a copy and change | |
212 | attributes and then pass the copy to this argument. |
|
212 | attributes and then pass the copy to this argument. | |
213 |
|
213 | |||
214 | Notes |
|
214 | Notes | |
215 | ----- |
|
215 | ----- | |
216 | Subclasses of Component must call the :meth:`__init__` method of |
|
216 | Subclasses of Component must call the :meth:`__init__` method of | |
217 | :class:`Component` *before* doing anything else and using |
|
217 | :class:`Component` *before* doing anything else and using | |
218 | :func:`super`:: |
|
218 | :func:`super`:: | |
219 |
|
219 | |||
220 | class MyComponent(Component): |
|
220 | class MyComponent(Component): | |
221 | def __init__(self, parent, name=None, config=None): |
|
221 | def __init__(self, parent, name=None, config=None): | |
222 | super(MyComponent, self).__init__(parent, name, config) |
|
222 | super(MyComponent, self).__init__(parent, name, config) | |
223 | # Then any other code you need to finish initialization. |
|
223 | # Then any other code you need to finish initialization. | |
224 |
|
224 | |||
225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` |
|
225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` | |
226 | attributes are handled properly. |
|
226 | attributes are handled properly. | |
227 | """ |
|
227 | """ | |
228 | super(Component, self).__init__() |
|
228 | super(Component, self).__init__() | |
229 | self._children = [] |
|
229 | self._children = [] | |
230 | if name is None: |
|
230 | if name is None: | |
231 | self.name = ComponentNameGenerator() |
|
231 | self.name = ComponentNameGenerator() | |
232 | else: |
|
232 | else: | |
233 | self.name = name |
|
233 | self.name = name | |
234 | self.root = self # This is the default, it is set when parent is set |
|
234 | self.root = self # This is the default, it is set when parent is set | |
235 | self.parent = parent |
|
235 | self.parent = parent | |
236 | if config is not None: |
|
236 | if config is not None: | |
237 | self.config = config |
|
237 | self.config = config | |
238 | # We used to deepcopy, but for now we are trying to just save |
|
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 |
|
239 | # by reference. This *could* have side effects as all components | |
240 | # will share config. |
|
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. | |||
241 | # self.config = deepcopy(config) |
|
244 | # self.config = deepcopy(config) | |
242 | else: |
|
245 | else: | |
243 | if self.parent is not None: |
|
246 | if self.parent is not None: | |
244 | self.config = self.parent.config |
|
247 | self.config = self.parent.config | |
245 | # We used to deepcopy, but for now we are trying to just save |
|
248 | # We used to deepcopy, but for now we are trying to just save | |
246 | # by reference. This *could* have side effects as all components |
|
249 | # by reference. This *could* have side effects as all components | |
247 | # will share config. |
|
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. | |||
248 | # self.config = deepcopy(self.parent.config) |
|
254 | # self.config = deepcopy(self.parent.config) | |
249 |
|
255 | |||
250 | self.created = datetime.datetime.now() |
|
256 | self.created = datetime.datetime.now() | |
251 |
|
257 | |||
252 | #------------------------------------------------------------------------- |
|
258 | #------------------------------------------------------------------------- | |
253 | # Static trait notifiations |
|
259 | # Static trait notifiations | |
254 | #------------------------------------------------------------------------- |
|
260 | #------------------------------------------------------------------------- | |
255 |
|
261 | |||
256 | def _parent_changed(self, name, old, new): |
|
262 | def _parent_changed(self, name, old, new): | |
257 | if old is not None: |
|
263 | if old is not None: | |
258 | old._remove_child(self) |
|
264 | old._remove_child(self) | |
259 | if new is not None: |
|
265 | if new is not None: | |
260 | new._add_child(self) |
|
266 | new._add_child(self) | |
261 |
|
267 | |||
262 | if new is None: |
|
268 | if new is None: | |
263 | self.root = self |
|
269 | self.root = self | |
264 | else: |
|
270 | else: | |
265 | self.root = new.root |
|
271 | self.root = new.root | |
266 |
|
272 | |||
267 | def _root_changed(self, name, old, new): |
|
273 | def _root_changed(self, name, old, new): | |
268 | if self.parent is None: |
|
274 | if self.parent is None: | |
269 | if not (new is self): |
|
275 | if not (new is self): | |
270 | raise ComponentError("Root not self, but parent is None.") |
|
276 | raise ComponentError("Root not self, but parent is None.") | |
271 | else: |
|
277 | else: | |
272 | if not self.parent.root is new: |
|
278 | if not self.parent.root is new: | |
273 | raise ComponentError("Error in setting the root attribute: " |
|
279 | raise ComponentError("Error in setting the root attribute: " | |
274 | "root != parent.root") |
|
280 | "root != parent.root") | |
275 |
|
281 | |||
276 | def _config_changed(self, name, old, new): |
|
282 | def _config_changed(self, name, old, new): | |
277 | """Update all the class traits having ``config=True`` as metadata. |
|
283 | """Update all the class traits having ``config=True`` as metadata. | |
278 |
|
284 | |||
279 | For any class trait with a ``config`` metadata attribute that is |
|
285 | For any class trait with a ``config`` metadata attribute that is | |
280 | ``True``, we update the trait with the value of the corresponding |
|
286 | ``True``, we update the trait with the value of the corresponding | |
281 | config entry. |
|
287 | config entry. | |
282 | """ |
|
288 | """ | |
283 | # Get all traits with a config metadata entry that is True |
|
289 | # Get all traits with a config metadata entry that is True | |
284 | traits = self.traits(config=True) |
|
290 | traits = self.traits(config=True) | |
285 |
|
291 | |||
286 | # We auto-load config section for this class as well as any parent |
|
292 | # We auto-load config section for this class as well as any parent | |
287 | # classes that are Component subclasses. This starts with Component |
|
293 | # classes that are Component subclasses. This starts with Component | |
288 | # and works down the mro loading the config for each section. |
|
294 | # and works down the mro loading the config for each section. | |
289 | section_names = [cls.__name__ for cls in \ |
|
295 | section_names = [cls.__name__ for cls in \ | |
290 | reversed(self.__class__.__mro__) if |
|
296 | reversed(self.__class__.__mro__) if | |
291 | issubclass(cls, Component) and issubclass(self.__class__, cls)] |
|
297 | issubclass(cls, Component) and issubclass(self.__class__, cls)] | |
292 |
|
298 | |||
293 | for sname in section_names: |
|
299 | for sname in section_names: | |
294 | # Don't do a blind getattr as that would cause the config to |
|
300 | # Don't do a blind getattr as that would cause the config to | |
295 | # dynamically create the section with name self.__class__.__name__. |
|
301 | # dynamically create the section with name self.__class__.__name__. | |
296 | if new._has_section(sname): |
|
302 | if new._has_section(sname): | |
297 | my_config = new[sname] |
|
303 | my_config = new[sname] | |
298 | for k, v in traits.items(): |
|
304 | for k, v in traits.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)) | |||
299 | try: |
|
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. | |||
300 | config_value = my_config[k] |
|
318 | config_value = my_config[k] | |
301 | except KeyError: |
|
319 | except KeyError: | |
302 | pass |
|
320 | pass | |
303 | else: |
|
321 | else: | |
304 | # print "Setting %s.%s from %s.%s=%r" % \ |
|
322 | # print "Setting %s.%s from %s.%s=%r" % \ | |
305 | # (self.__class__.__name__,k,sname,k,config_value) |
|
323 | # (self.__class__.__name__,k,sname,k,config_value) | |
306 | setattr(self, 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)) | |||
307 |
|
328 | |||
308 | @property |
|
329 | @property | |
309 | def children(self): |
|
330 | def children(self): | |
310 | """A list of all my child components.""" |
|
331 | """A list of all my child components.""" | |
311 | return self._children |
|
332 | return self._children | |
312 |
|
333 | |||
313 | def _remove_child(self, child): |
|
334 | def _remove_child(self, child): | |
314 | """A private method for removing children components.""" |
|
335 | """A private method for removing children components.""" | |
315 | if child in self._children: |
|
336 | if child in self._children: | |
316 | index = self._children.index(child) |
|
337 | index = self._children.index(child) | |
317 | del self._children[index] |
|
338 | del self._children[index] | |
318 |
|
339 | |||
319 | def _add_child(self, child): |
|
340 | def _add_child(self, child): | |
320 | """A private method for adding children components.""" |
|
341 | """A private method for adding children components.""" | |
321 | if child not in self._children: |
|
342 | if child not in self._children: | |
322 | self._children.append(child) |
|
343 | self._children.append(child) | |
323 |
|
344 | |||
324 | def __repr__(self): |
|
345 | def __repr__(self): | |
325 | return "<%s('%s')>" % (self.__class__.__name__, self.name) |
|
346 | return "<%s('%s')>" % (self.__class__.__name__, self.name) |
@@ -1,229 +1,228 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. | |
3 |
|
3 | |||
4 |
|
4 | |||
5 | Authors |
|
5 | Authors | |
6 | ------- |
|
6 | ------- | |
7 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
7 | - Fernando Perez <Fernando.Perez@berkeley.edu> | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | # Copyright (C) 2008-2009 The IPython Development Team | |
12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #***************************************************************************** |
|
16 | #***************************************************************************** | |
17 |
|
17 | |||
18 | #**************************************************************************** |
|
18 | #**************************************************************************** | |
19 | # Required modules |
|
19 | # Required modules | |
20 |
|
20 | |||
21 | # From the standard library |
|
21 | # From the standard library | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | from pprint import pformat |
|
24 | from pprint import pformat | |
25 |
|
25 | |||
26 | # Our own |
|
26 | # Our own | |
27 | from IPython.core import release |
|
27 | from IPython.core import release | |
28 | from IPython.core import ultratb |
|
28 | from IPython.core import ultratb | |
29 | from IPython.external.Itpl import itpl |
|
29 | from IPython.external.Itpl import itpl | |
30 |
|
30 | |||
31 | from IPython.utils.genutils import * |
|
|||
32 |
|
||||
33 | #**************************************************************************** |
|
31 | #**************************************************************************** | |
34 | class CrashHandler: |
|
32 | class CrashHandler(object): | |
35 | """Customizable crash handlers for IPython-based systems. |
|
33 | """Customizable crash handlers for IPython-based systems. | |
36 |
|
34 | |||
37 | Instances of this class provide a __call__ method which can be used as a |
|
35 | Instances of this class provide a __call__ method which can be used as a | |
38 | sys.excepthook, i.e., the __call__ signature is: |
|
36 | sys.excepthook, i.e., the __call__ signature is: | |
39 |
|
37 | |||
40 | def __call__(self,etype, evalue, etb) |
|
38 | def __call__(self,etype, evalue, etb) | |
41 |
|
39 | |||
42 | """ |
|
40 | """ | |
43 |
|
41 | |||
44 |
def __init__(self, |
|
42 | def __init__(self,app, app_name, contact_name=None, contact_email=None, | |
45 | bug_tracker,crash_report_fname, |
|
43 | bug_tracker=None, crash_report_fname='CrashReport.txt', | |
46 | show_crash_traceback=True): |
|
44 | show_crash_traceback=True, call_pdb=False): | |
47 | """New crash handler. |
|
45 | """New crash handler. | |
48 |
|
46 | |||
49 | Inputs: |
|
47 | Inputs: | |
50 |
|
48 | |||
51 |
- |
|
49 | - app: a running application instance, which will be queried at crash | |
52 | for internal information. |
|
50 | time for internal information. | |
53 |
|
51 | |||
54 | - app_name: a string containing the name of your application. |
|
52 | - app_name: a string containing the name of your application. | |
55 |
|
53 | |||
56 | - contact_name: a string with the name of the person to contact. |
|
54 | - contact_name: a string with the name of the person to contact. | |
57 |
|
55 | |||
58 | - contact_email: a string with the email address of the contact. |
|
56 | - contact_email: a string with the email address of the contact. | |
59 |
|
57 | |||
60 | - bug_tracker: a string with the URL for your project's bug tracker. |
|
58 | - bug_tracker: a string with the URL for your project's bug tracker. | |
61 |
|
59 | |||
62 | - crash_report_fname: a string with the filename for the crash report |
|
60 | - crash_report_fname: a string with the filename for the crash report | |
63 | to be saved in. These reports are left in the ipython user directory |
|
61 | to be saved in. These reports are left in the ipython user directory | |
64 | as determined by the running IPython instance. |
|
62 | as determined by the running IPython instance. | |
65 |
|
63 | |||
66 | Optional inputs: |
|
64 | Optional inputs: | |
67 |
|
65 | |||
68 | - show_crash_traceback(True): if false, don't print the crash |
|
66 | - show_crash_traceback(True): if false, don't print the crash | |
69 | traceback on stderr, only generate the on-disk report |
|
67 | traceback on stderr, only generate the on-disk report | |
70 |
|
68 | |||
71 |
|
69 | |||
72 | Non-argument instance attributes: |
|
70 | Non-argument instance attributes: | |
73 |
|
71 | |||
74 | These instances contain some non-argument attributes which allow for |
|
72 | These instances contain some non-argument attributes which allow for | |
75 | further customization of the crash handler's behavior. Please see the |
|
73 | further customization of the crash handler's behavior. Please see the | |
76 | source for further details. |
|
74 | source for further details. | |
77 | """ |
|
75 | """ | |
78 |
|
76 | |||
79 | # apply args into instance |
|
77 | # apply args into instance | |
80 | self.IP = IP # IPython instance |
|
78 | self.app = app | |
81 | self.app_name = app_name |
|
79 | self.app_name = app_name | |
82 | self.contact_name = contact_name |
|
80 | self.contact_name = contact_name | |
83 | self.contact_email = contact_email |
|
81 | self.contact_email = contact_email | |
84 | self.bug_tracker = bug_tracker |
|
82 | self.bug_tracker = bug_tracker | |
85 | self.crash_report_fname = crash_report_fname |
|
83 | self.crash_report_fname = crash_report_fname | |
86 | self.show_crash_traceback = show_crash_traceback |
|
84 | self.show_crash_traceback = show_crash_traceback | |
|
85 | self.section_sep = '\n\n'+'*'*75+'\n\n' | |||
|
86 | self.call_pdb = call_pdb | |||
|
87 | #self.call_pdb = True # dbg | |||
87 |
|
88 | |||
88 | # Hardcoded defaults, which can be overridden either by subclasses or |
|
89 | # Hardcoded defaults, which can be overridden either by subclasses or | |
89 | # at runtime for the instance. |
|
90 | # at runtime for the instance. | |
90 |
|
91 | |||
91 | # Template for the user message. Subclasses which completely override |
|
92 | # Template for the user message. Subclasses which completely override | |
92 | # this, or user apps, can modify it to suit their tastes. It gets |
|
93 | # this, or user apps, can modify it to suit their tastes. It gets | |
93 | # expanded using itpl, so calls of the kind $self.foo are valid. |
|
94 | # expanded using itpl, so calls of the kind $self.foo are valid. | |
94 | self.user_message_template = """ |
|
95 | self.user_message_template = """ | |
95 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
96 | Oops, $self.app_name crashed. We do our best to make it stable, but... | |
96 |
|
97 | |||
97 | A crash report was automatically generated with the following information: |
|
98 | A crash report was automatically generated with the following information: | |
98 | - A verbatim copy of the crash traceback. |
|
99 | - A verbatim copy of the crash traceback. | |
99 | - A copy of your input history during this session. |
|
100 | - A copy of your input history during this session. | |
100 | - Data on your current $self.app_name configuration. |
|
101 | - Data on your current $self.app_name configuration. | |
101 |
|
102 | |||
102 | It was left in the file named: |
|
103 | It was left in the file named: | |
103 | \t'$self.crash_report_fname' |
|
104 | \t'$self.crash_report_fname' | |
104 | If you can email this file to the developers, the information in it will help |
|
105 | If you can email this file to the developers, the information in it will help | |
105 | them in understanding and correcting the problem. |
|
106 | them in understanding and correcting the problem. | |
106 |
|
107 | |||
107 | You can mail it to: $self.contact_name at $self.contact_email |
|
108 | You can mail it to: $self.contact_name at $self.contact_email | |
108 | with the subject '$self.app_name Crash Report'. |
|
109 | with the subject '$self.app_name Crash Report'. | |
109 |
|
110 | |||
110 | If you want to do it now, the following command will work (under Unix): |
|
111 | If you want to do it now, the following command will work (under Unix): | |
111 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
112 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname | |
112 |
|
113 | |||
113 | To ensure accurate tracking of this issue, please file a report about it at: |
|
114 | To ensure accurate tracking of this issue, please file a report about it at: | |
114 | $self.bug_tracker |
|
115 | $self.bug_tracker | |
115 | """ |
|
116 | """ | |
116 |
|
117 | |||
117 | def __call__(self,etype, evalue, etb): |
|
118 | def __call__(self,etype, evalue, etb): | |
118 | """Handle an exception, call for compatible with sys.excepthook""" |
|
119 | """Handle an exception, call for compatible with sys.excepthook""" | |
119 |
|
120 | |||
120 | # Report tracebacks shouldn't use color in general (safer for users) |
|
121 | # Report tracebacks shouldn't use color in general (safer for users) | |
121 | color_scheme = 'NoColor' |
|
122 | color_scheme = 'NoColor' | |
122 |
|
123 | |||
123 | # Use this ONLY for developer debugging (keep commented out for release) |
|
124 | # Use this ONLY for developer debugging (keep commented out for release) | |
124 | #color_scheme = 'Linux' # dbg |
|
125 | #color_scheme = 'Linux' # dbg | |
125 |
|
126 | |||
126 | try: |
|
127 | try: | |
127 |
rptdir = self. |
|
128 | rptdir = self.app.ipython_dir | |
128 | except: |
|
129 | except: | |
129 | rptdir = os.getcwd() |
|
130 | rptdir = os.getcwd() | |
130 | if not os.path.isdir(rptdir): |
|
131 | if not os.path.isdir(rptdir): | |
131 | rptdir = os.getcwd() |
|
132 | rptdir = os.getcwd() | |
132 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
133 | report_name = os.path.join(rptdir,self.crash_report_fname) | |
133 | # write the report filename into the instance dict so it can get |
|
134 | # write the report filename into the instance dict so it can get | |
134 | # properly expanded out in the user message template |
|
135 | # properly expanded out in the user message template | |
135 | self.crash_report_fname = report_name |
|
136 | self.crash_report_fname = report_name | |
136 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, |
|
137 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, | |
137 |
|
|
138 | long_header=1, | |
138 | traceback = TBhandler.text(etype,evalue,etb,context=31) |
|
139 | call_pdb=self.call_pdb, | |
|
140 | ) | |||
|
141 | if self.call_pdb: | |||
|
142 | TBhandler(etype,evalue,etb) | |||
|
143 | return | |||
|
144 | else: | |||
|
145 | traceback = TBhandler.text(etype,evalue,etb,context=31) | |||
139 |
|
146 | |||
140 | # print traceback to screen |
|
147 | # print traceback to screen | |
141 | if self.show_crash_traceback: |
|
148 | if self.show_crash_traceback: | |
142 | print >> sys.stderr, traceback |
|
149 | print >> sys.stderr, traceback | |
143 |
|
150 | |||
144 | # and generate a complete report on disk |
|
151 | # and generate a complete report on disk | |
145 | try: |
|
152 | try: | |
146 | report = open(report_name,'w') |
|
153 | report = open(report_name,'w') | |
147 | except: |
|
154 | except: | |
148 | print >> sys.stderr, 'Could not create crash report on disk.' |
|
155 | print >> sys.stderr, 'Could not create crash report on disk.' | |
149 | return |
|
156 | return | |
150 |
|
157 | |||
151 | # Inform user on stderr of what happened |
|
158 | # Inform user on stderr of what happened | |
152 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) |
|
159 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) | |
153 | print >> sys.stderr, msg |
|
160 | print >> sys.stderr, msg | |
154 |
|
161 | |||
155 | # Construct report on disk |
|
162 | # Construct report on disk | |
156 | report.write(self.make_report(traceback)) |
|
163 | report.write(self.make_report(traceback)) | |
157 | report.close() |
|
164 | report.close() | |
158 | raw_input("Press enter to exit:") |
|
165 | raw_input("Hit <Enter> to quit this message (your terminal may close):") | |
159 |
|
166 | |||
160 | def make_report(self,traceback): |
|
167 | def make_report(self,traceback): | |
161 | """Return a string containing a crash report.""" |
|
168 | """Return a string containing a crash report.""" | |
162 |
|
169 | import platform | ||
163 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
170 | ||
164 |
|
171 | sec_sep = self.section_sep | ||
|
172 | ||||
165 | report = [] |
|
173 | report = [] | |
166 | rpt_add = report.append |
|
174 | rpt_add = report.append | |
167 |
|
175 | |||
168 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
176 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') | |
169 |
rpt_add('IPython version: %s |
|
177 | rpt_add('IPython version: %s \n' % release.version) | |
170 |
rpt_add('BZR revision : %s |
|
178 | rpt_add('BZR revision : %s \n' % release.revision) | |
171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
179 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s\n' % | |
172 | (os.name,sys.platform) ) |
|
180 | (os.name,sys.platform) ) | |
173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
181 | rpt_add(' : %s\n' % platform.platform()) | |
174 | rpt_add(pformat(self.IP.dict())) |
|
182 | rpt_add('Python info : %s\n' % sys.version) | |
175 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
183 | ||
176 | try: |
|
184 | try: | |
177 | rpt_add(sec_sep+"History of session input:") |
|
185 | config = pformat(self.app.config) | |
178 | for line in self.IP.user_ns['_ih']: |
|
186 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
179 |
|
|
187 | rpt_add(config) | |
180 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
|||
181 | rpt_add(self.IP._last_input_line+'\n') |
|
|||
182 | except: |
|
188 | except: | |
183 | pass |
|
189 | pass | |
|
190 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) | |||
184 |
|
191 | |||
185 | return ''.join(report) |
|
192 | return ''.join(report) | |
186 |
|
193 | |||
|
194 | ||||
187 | class IPythonCrashHandler(CrashHandler): |
|
195 | class IPythonCrashHandler(CrashHandler): | |
188 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
196 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" | |
189 |
|
197 | |||
190 | def __init__(self,IP): |
|
198 | def __init__(self, app, app_name='IPython'): | |
191 |
|
199 | |||
192 | # Set here which of the IPython authors should be listed as contact |
|
200 | # Set here which of the IPython authors should be listed as contact | |
193 | AUTHOR_CONTACT = 'Fernando' |
|
201 | AUTHOR_CONTACT = 'Fernando' | |
194 |
|
202 | |||
195 | # Set argument defaults |
|
203 | # Set argument defaults | |
196 | app_name = 'IPython' |
|
|||
197 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
204 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' | |
198 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] |
|
205 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] | |
199 | crash_report_fname = 'IPython_crash_report.txt' |
|
206 | crash_report_fname = 'IPython_crash_report.txt' | |
200 | # Call parent constructor |
|
207 | # Call parent constructor | |
201 |
CrashHandler.__init__(self, |
|
208 | CrashHandler.__init__(self,app,app_name,contact_name,contact_email, | |
202 | bug_tracker,crash_report_fname) |
|
209 | bug_tracker,crash_report_fname) | |
203 |
|
210 | |||
204 | def make_report(self,traceback): |
|
211 | def make_report(self,traceback): | |
205 | """Return a string containing a crash report.""" |
|
212 | """Return a string containing a crash report.""" | |
206 |
|
213 | |||
207 | sec_sep = '\n\n'+'*'*75+'\n\n' |
|
214 | sec_sep = self.section_sep | |
208 |
|
215 | # Start with parent report | ||
209 | report = [] |
|
216 | report = [super(IPythonCrashHandler, self).make_report(traceback)] | |
|
217 | # Add interactive-specific info we may have | |||
210 | rpt_add = report.append |
|
218 | rpt_add = report.append | |
211 |
|
||||
212 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
|||
213 | rpt_add('IPython version: %s \n\n' % release.version) |
|
|||
214 | rpt_add('BZR revision : %s \n\n' % release.revision) |
|
|||
215 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % |
|
|||
216 | (os.name,sys.platform) ) |
|
|||
217 | rpt_add(sec_sep+'Current user configuration structure:\n\n') |
|
|||
218 | # rpt_add(pformat(self.IP.dict())) |
|
|||
219 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) |
|
|||
220 | try: |
|
219 | try: | |
221 | rpt_add(sec_sep+"History of session input:") |
|
220 | rpt_add(sec_sep+"History of session input:") | |
222 |
for line in self. |
|
221 | for line in self.app.shell.user_ns['_ih']: | |
223 | rpt_add(line) |
|
222 | rpt_add(line) | |
224 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
223 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
225 |
rpt_add(self. |
|
224 | rpt_add(self.app.shell._last_input_line+'\n') | |
226 | except: |
|
225 | except: | |
227 | pass |
|
226 | pass | |
228 |
|
227 | |||
229 | return ''.join(report) |
|
228 | return ''.join(report) |
@@ -1,524 +1,512 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Pdb debugger class. |
|
3 | Pdb debugger class. | |
4 |
|
4 | |||
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that | |
6 | the command line completion of other programs which include this isn't |
|
6 | the command line completion of other programs which include this isn't | |
7 | damaged. |
|
7 | damaged. | |
8 |
|
8 | |||
9 | In the future, this class will be expanded with improvements over the standard |
|
9 | In the future, this class will be expanded with improvements over the standard | |
10 | pdb. |
|
10 | pdb. | |
11 |
|
11 | |||
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor | |
13 | changes. Licensing should therefore be under the standard Python terms. For |
|
13 | changes. Licensing should therefore be under the standard Python terms. For | |
14 | details on the PSF (Python Software Foundation) standard license, see: |
|
14 | details on the PSF (Python Software Foundation) standard license, see: | |
15 |
|
15 | |||
16 | http://www.python.org/2.2.3/license.html""" |
|
16 | http://www.python.org/2.2.3/license.html""" | |
17 |
|
17 | |||
18 | #***************************************************************************** |
|
18 | #***************************************************************************** | |
19 | # |
|
19 | # | |
20 | # This file is licensed under the PSF license. |
|
20 | # This file is licensed under the PSF license. | |
21 | # |
|
21 | # | |
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> | |
24 | # |
|
24 | # | |
25 | # |
|
25 | # | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 |
|
27 | |||
28 | import bdb |
|
28 | import bdb | |
29 | import cmd |
|
29 | import cmd | |
30 | import linecache |
|
30 | import linecache | |
31 | import os |
|
31 | import os | |
32 | import sys |
|
32 | import sys | |
33 |
|
33 | |||
34 | from IPython.utils import PyColorize |
|
34 | from IPython.utils import PyColorize | |
35 | from IPython.core import ipapi |
|
35 | from IPython.core import ipapi | |
36 | from IPython.utils import coloransi |
|
36 | from IPython.utils import coloransi | |
37 | from IPython.utils.genutils import Term |
|
37 | from IPython.utils.genutils import Term | |
38 | from IPython.core.excolors import exception_colors |
|
38 | from IPython.core.excolors import exception_colors | |
39 |
|
39 | |||
40 | # See if we can use pydb. |
|
40 | # See if we can use pydb. | |
41 | has_pydb = False |
|
41 | has_pydb = False | |
42 | prompt = 'ipdb> ' |
|
42 | prompt = 'ipdb> ' | |
43 | #We have to check this directly from sys.argv, config struct not yet available |
|
43 | #We have to check this directly from sys.argv, config struct not yet available | |
44 | if '-pydb' in sys.argv: |
|
44 | if '-pydb' in sys.argv: | |
45 | try: |
|
45 | try: | |
46 | import pydb |
|
46 | import pydb | |
47 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
47 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': | |
48 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
48 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we | |
49 | # better protect against it. |
|
49 | # better protect against it. | |
50 | has_pydb = True |
|
50 | has_pydb = True | |
51 | except ImportError: |
|
51 | except ImportError: | |
52 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" |
|
52 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" | |
53 |
|
53 | |||
54 | if has_pydb: |
|
54 | if has_pydb: | |
55 | from pydb import Pdb as OldPdb |
|
55 | from pydb import Pdb as OldPdb | |
56 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
56 | #print "Using pydb for %run -d and post-mortem" #dbg | |
57 | prompt = 'ipydb> ' |
|
57 | prompt = 'ipydb> ' | |
58 | else: |
|
58 | else: | |
59 | from pdb import Pdb as OldPdb |
|
59 | from pdb import Pdb as OldPdb | |
60 |
|
60 | |||
61 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
61 | # Allow the set_trace code to operate outside of an ipython instance, even if | |
62 | # it does so with some limitations. The rest of this support is implemented in |
|
62 | # it does so with some limitations. The rest of this support is implemented in | |
63 | # the Tracer constructor. |
|
63 | # the Tracer constructor. | |
64 | def BdbQuit_excepthook(et,ev,tb): |
|
64 | def BdbQuit_excepthook(et,ev,tb): | |
65 | if et==bdb.BdbQuit: |
|
65 | if et==bdb.BdbQuit: | |
66 | print 'Exiting Debugger.' |
|
66 | print 'Exiting Debugger.' | |
67 | else: |
|
67 | else: | |
68 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
68 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) | |
69 |
|
69 | |||
70 | def BdbQuit_IPython_excepthook(self,et,ev,tb): |
|
70 | def BdbQuit_IPython_excepthook(self,et,ev,tb): | |
71 | print 'Exiting Debugger.' |
|
71 | print 'Exiting Debugger.' | |
72 |
|
72 | |||
|
73 | ||||
73 | class Tracer(object): |
|
74 | class Tracer(object): | |
74 | """Class for local debugging, similar to pdb.set_trace. |
|
75 | """Class for local debugging, similar to pdb.set_trace. | |
75 |
|
76 | |||
76 | Instances of this class, when called, behave like pdb.set_trace, but |
|
77 | Instances of this class, when called, behave like pdb.set_trace, but | |
77 | providing IPython's enhanced capabilities. |
|
78 | providing IPython's enhanced capabilities. | |
78 |
|
79 | |||
79 | This is implemented as a class which must be initialized in your own code |
|
80 | This is implemented as a class which must be initialized in your own code | |
80 | and not as a standalone function because we need to detect at runtime |
|
81 | and not as a standalone function because we need to detect at runtime | |
81 | whether IPython is already active or not. That detection is done in the |
|
82 | whether IPython is already active or not. That detection is done in the | |
82 | constructor, ensuring that this code plays nicely with a running IPython, |
|
83 | constructor, ensuring that this code plays nicely with a running IPython, | |
83 | while functioning acceptably (though with limitations) if outside of it. |
|
84 | while functioning acceptably (though with limitations) if outside of it. | |
84 | """ |
|
85 | """ | |
85 |
|
86 | |||
86 | def __init__(self,colors=None): |
|
87 | def __init__(self,colors=None): | |
87 | """Create a local debugger instance. |
|
88 | """Create a local debugger instance. | |
88 |
|
89 | |||
89 | :Parameters: |
|
90 | :Parameters: | |
90 |
|
91 | |||
91 | - `colors` (None): a string containing the name of the color scheme to |
|
92 | - `colors` (None): a string containing the name of the color scheme to | |
92 | use, it must be one of IPython's valid color schemes. If not given, the |
|
93 | use, it must be one of IPython's valid color schemes. If not given, the | |
93 | function will default to the current IPython scheme when running inside |
|
94 | function will default to the current IPython scheme when running inside | |
94 | IPython, and to 'NoColor' otherwise. |
|
95 | IPython, and to 'NoColor' otherwise. | |
95 |
|
96 | |||
96 | Usage example: |
|
97 | Usage example: | |
97 |
|
98 | |||
98 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
99 | from IPython.core.debugger import Tracer; debug_here = Tracer() | |
99 |
|
100 | |||
100 | ... later in your code |
|
101 | ... later in your code | |
101 | debug_here() # -> will open up the debugger at that point. |
|
102 | debug_here() # -> will open up the debugger at that point. | |
102 |
|
103 | |||
103 | Once the debugger activates, you can use all of its regular commands to |
|
104 | Once the debugger activates, you can use all of its regular commands to | |
104 | step through code, set breakpoints, etc. See the pdb documentation |
|
105 | step through code, set breakpoints, etc. See the pdb documentation | |
105 | from the Python standard library for usage details. |
|
106 | from the Python standard library for usage details. | |
106 | """ |
|
107 | """ | |
107 |
|
108 | |||
108 | global __IPYTHON__ |
|
|||
109 | try: |
|
109 | try: | |
110 | __IPYTHON__ |
|
110 | ip = ipapi.get() | |
111 |
except |
|
111 | except: | |
112 | # Outside of ipython, we set our own exception hook manually |
|
112 | # Outside of ipython, we set our own exception hook manually | |
113 | __IPYTHON__ = ipapi.get() |
|
|||
114 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
113 | BdbQuit_excepthook.excepthook_ori = sys.excepthook | |
115 | sys.excepthook = BdbQuit_excepthook |
|
114 | sys.excepthook = BdbQuit_excepthook | |
116 | def_colors = 'NoColor' |
|
115 | def_colors = 'NoColor' | |
117 | try: |
|
116 | try: | |
118 | # Limited tab completion support |
|
117 | # Limited tab completion support | |
119 | import readline |
|
118 | import readline | |
120 | readline.parse_and_bind('tab: complete') |
|
119 | readline.parse_and_bind('tab: complete') | |
121 | except ImportError: |
|
120 | except ImportError: | |
122 | pass |
|
121 | pass | |
123 | else: |
|
122 | else: | |
124 | # In ipython, we use its custom exception handler mechanism |
|
123 | # In ipython, we use its custom exception handler mechanism | |
125 | ip = ipapi.get() |
|
|||
126 | def_colors = ip.colors |
|
124 | def_colors = ip.colors | |
127 | ip.set_custom_exc((bdb.BdbQuit,),BdbQuit_IPython_excepthook) |
|
125 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) | |
128 |
|
126 | |||
129 | if colors is None: |
|
127 | if colors is None: | |
130 | colors = def_colors |
|
128 | colors = def_colors | |
131 | self.debugger = Pdb(colors) |
|
129 | self.debugger = Pdb(colors) | |
132 |
|
130 | |||
133 | def __call__(self): |
|
131 | def __call__(self): | |
134 | """Starts an interactive debugger at the point where called. |
|
132 | """Starts an interactive debugger at the point where called. | |
135 |
|
133 | |||
136 | This is similar to the pdb.set_trace() function from the std lib, but |
|
134 | This is similar to the pdb.set_trace() function from the std lib, but | |
137 | using IPython's enhanced debugger.""" |
|
135 | using IPython's enhanced debugger.""" | |
138 |
|
136 | |||
139 | self.debugger.set_trace(sys._getframe().f_back) |
|
137 | self.debugger.set_trace(sys._getframe().f_back) | |
140 |
|
138 | |||
|
139 | ||||
141 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
140 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): | |
142 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
141 | """Make new_fn have old_fn's doc string. This is particularly useful | |
143 | for the do_... commands that hook into the help system. |
|
142 | for the do_... commands that hook into the help system. | |
144 | Adapted from from a comp.lang.python posting |
|
143 | Adapted from from a comp.lang.python posting | |
145 | by Duncan Booth.""" |
|
144 | by Duncan Booth.""" | |
146 | def wrapper(*args, **kw): |
|
145 | def wrapper(*args, **kw): | |
147 | return new_fn(*args, **kw) |
|
146 | return new_fn(*args, **kw) | |
148 | if old_fn.__doc__: |
|
147 | if old_fn.__doc__: | |
149 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
148 | wrapper.__doc__ = old_fn.__doc__ + additional_text | |
150 | return wrapper |
|
149 | return wrapper | |
151 |
|
150 | |||
|
151 | ||||
152 | def _file_lines(fname): |
|
152 | def _file_lines(fname): | |
153 | """Return the contents of a named file as a list of lines. |
|
153 | """Return the contents of a named file as a list of lines. | |
154 |
|
154 | |||
155 | This function never raises an IOError exception: if the file can't be |
|
155 | This function never raises an IOError exception: if the file can't be | |
156 | read, it simply returns an empty list.""" |
|
156 | read, it simply returns an empty list.""" | |
157 |
|
157 | |||
158 | try: |
|
158 | try: | |
159 | outfile = open(fname) |
|
159 | outfile = open(fname) | |
160 | except IOError: |
|
160 | except IOError: | |
161 | return [] |
|
161 | return [] | |
162 | else: |
|
162 | else: | |
163 | out = outfile.readlines() |
|
163 | out = outfile.readlines() | |
164 | outfile.close() |
|
164 | outfile.close() | |
165 | return out |
|
165 | return out | |
166 |
|
166 | |||
|
167 | ||||
167 | class Pdb(OldPdb): |
|
168 | class Pdb(OldPdb): | |
168 | """Modified Pdb class, does not load readline.""" |
|
169 | """Modified Pdb class, does not load readline.""" | |
169 |
|
170 | |||
170 | if sys.version[:3] >= '2.5' or has_pydb: |
|
171 | def __init__(self,color_scheme='NoColor',completekey=None, | |
171 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
172 | stdin=None, stdout=None): | |
172 | stdin=None, stdout=None): |
|
|||
173 |
|
173 | |||
174 |
|
|
174 | # Parent constructor: | |
175 |
|
|
175 | if has_pydb and completekey is None: | |
176 |
|
|
176 | OldPdb.__init__(self,stdin=stdin,stdout=Term.cout) | |
177 |
|
|
177 | else: | |
178 |
|
|
178 | OldPdb.__init__(self,completekey,stdin,stdout) | |
179 |
|
||||
180 | self.prompt = prompt # The default prompt is '(Pdb)' |
|
|||
181 |
|
179 | |||
182 | # IPython changes... |
|
180 | self.prompt = prompt # The default prompt is '(Pdb)' | |
183 | self.is_pydb = has_pydb |
|
181 | ||
184 |
|
182 | # IPython changes... | ||
185 |
|
|
183 | self.is_pydb = has_pydb | |
186 |
|
||||
187 | # iplib.py's ipalias seems to want pdb's checkline |
|
|||
188 | # which located in pydb.fn |
|
|||
189 | import pydb.fns |
|
|||
190 | self.checkline = lambda filename, lineno: \ |
|
|||
191 | pydb.fns.checkline(self, filename, lineno) |
|
|||
192 |
|
||||
193 | self.curframe = None |
|
|||
194 | self.do_restart = self.new_do_restart |
|
|||
195 |
|
||||
196 | self.old_all_completions = __IPYTHON__.Completer.all_completions |
|
|||
197 | __IPYTHON__.Completer.all_completions=self.all_completions |
|
|||
198 |
|
||||
199 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, |
|
|||
200 | OldPdb.do_list) |
|
|||
201 | self.do_l = self.do_list |
|
|||
202 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, |
|
|||
203 | OldPdb.do_frame) |
|
|||
204 |
|
||||
205 | self.aliases = {} |
|
|||
206 |
|
||||
207 | # Create color table: we copy the default one from the traceback |
|
|||
208 | # module and add a few attributes needed for debugging |
|
|||
209 | self.color_scheme_table = exception_colors() |
|
|||
210 |
|
184 | |||
211 | # shorthands |
|
185 | self.shell = ipapi.get() | |
212 | C = coloransi.TermColors |
|
|||
213 | cst = self.color_scheme_table |
|
|||
214 |
|
186 | |||
215 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
187 | if self.is_pydb: | |
216 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
|||
217 |
|
188 | |||
218 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
189 | # iplib.py's ipalias seems to want pdb's checkline | |
219 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
190 | # which located in pydb.fn | |
|
191 | import pydb.fns | |||
|
192 | self.checkline = lambda filename, lineno: \ | |||
|
193 | pydb.fns.checkline(self, filename, lineno) | |||
220 |
|
194 | |||
221 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
195 | self.curframe = None | |
222 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
196 | self.do_restart = self.new_do_restart | |
223 |
|
197 | |||
224 | self.set_colors(color_scheme) |
|
198 | self.old_all_completions = self.shell.Completer.all_completions | |
|
199 | self.shell.Completer.all_completions=self.all_completions | |||
225 |
|
200 | |||
226 | # Add a python parser so we can syntax highlight source while |
|
201 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, | |
227 | # debugging. |
|
202 | OldPdb.do_list) | |
228 | self.parser = PyColorize.Parser() |
|
203 | self.do_l = self.do_list | |
|
204 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, | |||
|
205 | OldPdb.do_frame) | |||
229 |
|
206 | |||
|
207 | self.aliases = {} | |||
230 |
|
208 | |||
231 | else: |
|
209 | # Create color table: we copy the default one from the traceback | |
232 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, |
|
210 | # module and add a few attributes needed for debugging | |
233 | # because it binds readline and breaks tab-completion. This means we |
|
211 | self.color_scheme_table = exception_colors() | |
234 | # have to COPY the constructor here. |
|
|||
235 | def __init__(self,color_scheme='NoColor'): |
|
|||
236 | bdb.Bdb.__init__(self) |
|
|||
237 | cmd.Cmd.__init__(self,completekey=None) # don't load readline |
|
|||
238 | self.prompt = 'ipdb> ' # The default prompt is '(Pdb)' |
|
|||
239 | self.aliases = {} |
|
|||
240 |
|
||||
241 | # These two lines are part of the py2.4 constructor, let's put them |
|
|||
242 | # unconditionally here as they won't cause any problems in 2.3. |
|
|||
243 | self.mainpyfile = '' |
|
|||
244 | self._wait_for_mainpyfile = 0 |
|
|||
245 |
|
||||
246 | # Read $HOME/.pdbrc and ./.pdbrc |
|
|||
247 | try: |
|
|||
248 | self.rcLines = _file_lines(os.path.join(os.environ['HOME'], |
|
|||
249 | ".pdbrc")) |
|
|||
250 | except KeyError: |
|
|||
251 | self.rcLines = [] |
|
|||
252 | self.rcLines.extend(_file_lines(".pdbrc")) |
|
|||
253 |
|
212 | |||
254 | # Create color table: we copy the default one from the traceback |
|
213 | # shorthands | |
255 | # module and add a few attributes needed for debugging |
|
214 | C = coloransi.TermColors | |
256 |
|
|
215 | cst = self.color_scheme_table | |
257 |
|
216 | |||
258 | # shorthands |
|
217 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
259 | C = coloransi.TermColors |
|
218 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
260 | cst = self.color_scheme_table |
|
|||
261 |
|
219 | |||
262 |
|
|
220 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
263 |
|
|
221 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
264 |
|
222 | |||
265 |
|
|
223 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
266 |
|
|
224 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
267 |
|
225 | |||
268 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
226 | self.set_colors(color_scheme) | |
269 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
|||
270 |
|
227 | |||
271 | self.set_colors(color_scheme) |
|
228 | # Add a python parser so we can syntax highlight source while | |
|
229 | # debugging. | |||
|
230 | self.parser = PyColorize.Parser() | |||
272 |
|
231 | |||
273 | # Add a python parser so we can syntax highlight source while |
|
|||
274 | # debugging. |
|
|||
275 | self.parser = PyColorize.Parser() |
|
|||
276 |
|
||||
277 | def set_colors(self, scheme): |
|
232 | def set_colors(self, scheme): | |
278 | """Shorthand access to the color table scheme selector method.""" |
|
233 | """Shorthand access to the color table scheme selector method.""" | |
279 | self.color_scheme_table.set_active_scheme(scheme) |
|
234 | self.color_scheme_table.set_active_scheme(scheme) | |
280 |
|
235 | |||
281 | def interaction(self, frame, traceback): |
|
236 | def interaction(self, frame, traceback): | |
282 |
|
|
237 | self.shell.set_completer_frame(frame) | |
283 | OldPdb.interaction(self, frame, traceback) |
|
238 | OldPdb.interaction(self, frame, traceback) | |
284 |
|
239 | |||
285 | def new_do_up(self, arg): |
|
240 | def new_do_up(self, arg): | |
286 | OldPdb.do_up(self, arg) |
|
241 | OldPdb.do_up(self, arg) | |
287 |
|
|
242 | self.shell.set_completer_frame(self.curframe) | |
288 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
243 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) | |
289 |
|
244 | |||
290 | def new_do_down(self, arg): |
|
245 | def new_do_down(self, arg): | |
291 | OldPdb.do_down(self, arg) |
|
246 | OldPdb.do_down(self, arg) | |
292 |
|
|
247 | self.shell.set_completer_frame(self.curframe) | |
293 |
|
248 | |||
294 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
249 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) | |
295 |
|
250 | |||
296 | def new_do_frame(self, arg): |
|
251 | def new_do_frame(self, arg): | |
297 | OldPdb.do_frame(self, arg) |
|
252 | OldPdb.do_frame(self, arg) | |
298 |
|
|
253 | self.shell.set_completer_frame(self.curframe) | |
299 |
|
254 | |||
300 | def new_do_quit(self, arg): |
|
255 | def new_do_quit(self, arg): | |
301 |
|
256 | |||
302 | if hasattr(self, 'old_all_completions'): |
|
257 | if hasattr(self, 'old_all_completions'): | |
303 |
|
|
258 | self.shell.Completer.all_completions=self.old_all_completions | |
304 |
|
259 | |||
305 |
|
260 | |||
306 | return OldPdb.do_quit(self, arg) |
|
261 | return OldPdb.do_quit(self, arg) | |
307 |
|
262 | |||
308 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
263 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) | |
309 |
|
264 | |||
310 | def new_do_restart(self, arg): |
|
265 | def new_do_restart(self, arg): | |
311 | """Restart command. In the context of ipython this is exactly the same |
|
266 | """Restart command. In the context of ipython this is exactly the same | |
312 | thing as 'quit'.""" |
|
267 | thing as 'quit'.""" | |
313 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
268 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") | |
314 | return self.do_quit(arg) |
|
269 | return self.do_quit(arg) | |
315 |
|
270 | |||
316 | def postloop(self): |
|
271 | def postloop(self): | |
317 |
|
|
272 | self.shell.set_completer_frame(None) | |
318 |
|
273 | |||
319 | def print_stack_trace(self): |
|
274 | def print_stack_trace(self): | |
320 | try: |
|
275 | try: | |
321 | for frame_lineno in self.stack: |
|
276 | for frame_lineno in self.stack: | |
322 | self.print_stack_entry(frame_lineno, context = 5) |
|
277 | self.print_stack_entry(frame_lineno, context = 5) | |
323 | except KeyboardInterrupt: |
|
278 | except KeyboardInterrupt: | |
324 | pass |
|
279 | pass | |
325 |
|
280 | |||
326 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
281 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', | |
327 | context = 3): |
|
282 | context = 3): | |
328 | #frame, lineno = frame_lineno |
|
283 | #frame, lineno = frame_lineno | |
329 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) |
|
284 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) | |
330 |
|
285 | |||
331 | # vds: >> |
|
286 | # vds: >> | |
332 | frame, lineno = frame_lineno |
|
287 | frame, lineno = frame_lineno | |
333 | filename = frame.f_code.co_filename |
|
288 | filename = frame.f_code.co_filename | |
334 |
|
|
289 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
335 | # vds: << |
|
290 | # vds: << | |
336 |
|
291 | |||
337 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
292 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): | |
338 | import linecache, repr |
|
293 | import linecache, repr | |
339 |
|
294 | |||
340 | ret = [] |
|
295 | ret = [] | |
341 |
|
296 | |||
342 | Colors = self.color_scheme_table.active_colors |
|
297 | Colors = self.color_scheme_table.active_colors | |
343 | ColorsNormal = Colors.Normal |
|
298 | ColorsNormal = Colors.Normal | |
344 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
299 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
345 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
300 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) | |
346 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
301 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
347 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
302 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, | |
348 | ColorsNormal) |
|
303 | ColorsNormal) | |
349 |
|
304 | |||
350 | frame, lineno = frame_lineno |
|
305 | frame, lineno = frame_lineno | |
351 |
|
306 | |||
352 | return_value = '' |
|
307 | return_value = '' | |
353 | if '__return__' in frame.f_locals: |
|
308 | if '__return__' in frame.f_locals: | |
354 | rv = frame.f_locals['__return__'] |
|
309 | rv = frame.f_locals['__return__'] | |
355 | #return_value += '->' |
|
310 | #return_value += '->' | |
356 | return_value += repr.repr(rv) + '\n' |
|
311 | return_value += repr.repr(rv) + '\n' | |
357 | ret.append(return_value) |
|
312 | ret.append(return_value) | |
358 |
|
313 | |||
359 | #s = filename + '(' + `lineno` + ')' |
|
314 | #s = filename + '(' + `lineno` + ')' | |
360 | filename = self.canonic(frame.f_code.co_filename) |
|
315 | filename = self.canonic(frame.f_code.co_filename) | |
361 | link = tpl_link % filename |
|
316 | link = tpl_link % filename | |
362 |
|
317 | |||
363 | if frame.f_code.co_name: |
|
318 | if frame.f_code.co_name: | |
364 | func = frame.f_code.co_name |
|
319 | func = frame.f_code.co_name | |
365 | else: |
|
320 | else: | |
366 | func = "<lambda>" |
|
321 | func = "<lambda>" | |
367 |
|
322 | |||
368 | call = '' |
|
323 | call = '' | |
369 | if func != '?': |
|
324 | if func != '?': | |
370 | if '__args__' in frame.f_locals: |
|
325 | if '__args__' in frame.f_locals: | |
371 | args = repr.repr(frame.f_locals['__args__']) |
|
326 | args = repr.repr(frame.f_locals['__args__']) | |
372 | else: |
|
327 | else: | |
373 | args = '()' |
|
328 | args = '()' | |
374 | call = tpl_call % (func, args) |
|
329 | call = tpl_call % (func, args) | |
375 |
|
330 | |||
376 | # The level info should be generated in the same format pdb uses, to |
|
331 | # The level info should be generated in the same format pdb uses, to | |
377 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
332 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. | |
378 | if frame is self.curframe: |
|
333 | if frame is self.curframe: | |
379 | ret.append('> ') |
|
334 | ret.append('> ') | |
380 | else: |
|
335 | else: | |
381 | ret.append(' ') |
|
336 | ret.append(' ') | |
382 | ret.append('%s(%s)%s\n' % (link,lineno,call)) |
|
337 | ret.append('%s(%s)%s\n' % (link,lineno,call)) | |
383 |
|
338 | |||
384 | start = lineno - 1 - context//2 |
|
339 | start = lineno - 1 - context//2 | |
385 | lines = linecache.getlines(filename) |
|
340 | lines = linecache.getlines(filename) | |
386 | start = max(start, 0) |
|
341 | start = max(start, 0) | |
387 | start = min(start, len(lines) - context) |
|
342 | start = min(start, len(lines) - context) | |
388 | lines = lines[start : start + context] |
|
343 | lines = lines[start : start + context] | |
389 |
|
344 | |||
390 | for i,line in enumerate(lines): |
|
345 | for i,line in enumerate(lines): | |
391 | show_arrow = (start + 1 + i == lineno) |
|
346 | show_arrow = (start + 1 + i == lineno) | |
392 | linetpl = (frame is self.curframe or show_arrow) \ |
|
347 | linetpl = (frame is self.curframe or show_arrow) \ | |
393 | and tpl_line_em \ |
|
348 | and tpl_line_em \ | |
394 | or tpl_line |
|
349 | or tpl_line | |
395 | ret.append(self.__format_line(linetpl, filename, |
|
350 | ret.append(self.__format_line(linetpl, filename, | |
396 | start + 1 + i, line, |
|
351 | start + 1 + i, line, | |
397 | arrow = show_arrow) ) |
|
352 | arrow = show_arrow) ) | |
398 |
|
353 | |||
399 | return ''.join(ret) |
|
354 | return ''.join(ret) | |
400 |
|
355 | |||
401 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
356 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): | |
402 | bp_mark = "" |
|
357 | bp_mark = "" | |
403 | bp_mark_color = "" |
|
358 | bp_mark_color = "" | |
404 |
|
359 | |||
405 | scheme = self.color_scheme_table.active_scheme_name |
|
360 | scheme = self.color_scheme_table.active_scheme_name | |
406 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
361 | new_line, err = self.parser.format2(line, 'str', scheme) | |
407 | if not err: line = new_line |
|
362 | if not err: line = new_line | |
408 |
|
363 | |||
409 | bp = None |
|
364 | bp = None | |
410 | if lineno in self.get_file_breaks(filename): |
|
365 | if lineno in self.get_file_breaks(filename): | |
411 | bps = self.get_breaks(filename, lineno) |
|
366 | bps = self.get_breaks(filename, lineno) | |
412 | bp = bps[-1] |
|
367 | bp = bps[-1] | |
413 |
|
368 | |||
414 | if bp: |
|
369 | if bp: | |
415 | Colors = self.color_scheme_table.active_colors |
|
370 | Colors = self.color_scheme_table.active_colors | |
416 | bp_mark = str(bp.number) |
|
371 | bp_mark = str(bp.number) | |
417 | bp_mark_color = Colors.breakpoint_enabled |
|
372 | bp_mark_color = Colors.breakpoint_enabled | |
418 | if not bp.enabled: |
|
373 | if not bp.enabled: | |
419 | bp_mark_color = Colors.breakpoint_disabled |
|
374 | bp_mark_color = Colors.breakpoint_disabled | |
420 |
|
375 | |||
421 | numbers_width = 7 |
|
376 | numbers_width = 7 | |
422 | if arrow: |
|
377 | if arrow: | |
423 | # This is the line with the error |
|
378 | # This is the line with the error | |
424 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
379 | pad = numbers_width - len(str(lineno)) - len(bp_mark) | |
425 | if pad >= 3: |
|
380 | if pad >= 3: | |
426 | marker = '-'*(pad-3) + '-> ' |
|
381 | marker = '-'*(pad-3) + '-> ' | |
427 | elif pad == 2: |
|
382 | elif pad == 2: | |
428 | marker = '> ' |
|
383 | marker = '> ' | |
429 | elif pad == 1: |
|
384 | elif pad == 1: | |
430 | marker = '>' |
|
385 | marker = '>' | |
431 | else: |
|
386 | else: | |
432 | marker = '' |
|
387 | marker = '' | |
433 | num = '%s%s' % (marker, str(lineno)) |
|
388 | num = '%s%s' % (marker, str(lineno)) | |
434 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
389 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
435 | else: |
|
390 | else: | |
436 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
391 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) | |
437 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
392 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
438 |
|
393 | |||
439 | return line |
|
394 | return line | |
440 |
|
395 | |||
441 | def list_command_pydb(self, arg): |
|
396 | def list_command_pydb(self, arg): | |
442 | """List command to use if we have a newer pydb installed""" |
|
397 | """List command to use if we have a newer pydb installed""" | |
443 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
398 | filename, first, last = OldPdb.parse_list_cmd(self, arg) | |
444 | if filename is not None: |
|
399 | if filename is not None: | |
445 | self.print_list_lines(filename, first, last) |
|
400 | self.print_list_lines(filename, first, last) | |
446 |
|
401 | |||
447 | def print_list_lines(self, filename, first, last): |
|
402 | def print_list_lines(self, filename, first, last): | |
448 | """The printing (as opposed to the parsing part of a 'list' |
|
403 | """The printing (as opposed to the parsing part of a 'list' | |
449 | command.""" |
|
404 | command.""" | |
450 | try: |
|
405 | try: | |
451 | Colors = self.color_scheme_table.active_colors |
|
406 | Colors = self.color_scheme_table.active_colors | |
452 | ColorsNormal = Colors.Normal |
|
407 | ColorsNormal = Colors.Normal | |
453 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
408 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
454 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
409 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) | |
455 | src = [] |
|
410 | src = [] | |
456 | for lineno in range(first, last+1): |
|
411 | for lineno in range(first, last+1): | |
457 | line = linecache.getline(filename, lineno) |
|
412 | line = linecache.getline(filename, lineno) | |
458 | if not line: |
|
413 | if not line: | |
459 | break |
|
414 | break | |
460 |
|
415 | |||
461 | if lineno == self.curframe.f_lineno: |
|
416 | if lineno == self.curframe.f_lineno: | |
462 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
417 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) | |
463 | else: |
|
418 | else: | |
464 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
419 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) | |
465 |
|
420 | |||
466 | src.append(line) |
|
421 | src.append(line) | |
467 | self.lineno = lineno |
|
422 | self.lineno = lineno | |
468 |
|
423 | |||
469 | print >>Term.cout, ''.join(src) |
|
424 | print >>Term.cout, ''.join(src) | |
470 |
|
425 | |||
471 | except KeyboardInterrupt: |
|
426 | except KeyboardInterrupt: | |
472 | pass |
|
427 | pass | |
473 |
|
428 | |||
474 | def do_list(self, arg): |
|
429 | def do_list(self, arg): | |
475 | self.lastcmd = 'list' |
|
430 | self.lastcmd = 'list' | |
476 | last = None |
|
431 | last = None | |
477 | if arg: |
|
432 | if arg: | |
478 | try: |
|
433 | try: | |
479 | x = eval(arg, {}, {}) |
|
434 | x = eval(arg, {}, {}) | |
480 | if type(x) == type(()): |
|
435 | if type(x) == type(()): | |
481 | first, last = x |
|
436 | first, last = x | |
482 | first = int(first) |
|
437 | first = int(first) | |
483 | last = int(last) |
|
438 | last = int(last) | |
484 | if last < first: |
|
439 | if last < first: | |
485 | # Assume it's a count |
|
440 | # Assume it's a count | |
486 | last = first + last |
|
441 | last = first + last | |
487 | else: |
|
442 | else: | |
488 | first = max(1, int(x) - 5) |
|
443 | first = max(1, int(x) - 5) | |
489 | except: |
|
444 | except: | |
490 | print '*** Error in argument:', `arg` |
|
445 | print '*** Error in argument:', `arg` | |
491 | return |
|
446 | return | |
492 | elif self.lineno is None: |
|
447 | elif self.lineno is None: | |
493 | first = max(1, self.curframe.f_lineno - 5) |
|
448 | first = max(1, self.curframe.f_lineno - 5) | |
494 | else: |
|
449 | else: | |
495 | first = self.lineno + 1 |
|
450 | first = self.lineno + 1 | |
496 | if last is None: |
|
451 | if last is None: | |
497 | last = first + 10 |
|
452 | last = first + 10 | |
498 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
453 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) | |
499 |
|
454 | |||
500 | # vds: >> |
|
455 | # vds: >> | |
501 | lineno = first |
|
456 | lineno = first | |
502 | filename = self.curframe.f_code.co_filename |
|
457 | filename = self.curframe.f_code.co_filename | |
503 |
|
|
458 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
504 | # vds: << |
|
459 | # vds: << | |
505 |
|
460 | |||
506 | do_l = do_list |
|
461 | do_l = do_list | |
507 |
|
462 | |||
508 | def do_pdef(self, arg): |
|
463 | def do_pdef(self, arg): | |
509 | """The debugger interface to magic_pdef""" |
|
464 | """The debugger interface to magic_pdef""" | |
510 | namespaces = [('Locals', self.curframe.f_locals), |
|
465 | namespaces = [('Locals', self.curframe.f_locals), | |
511 | ('Globals', self.curframe.f_globals)] |
|
466 | ('Globals', self.curframe.f_globals)] | |
512 |
|
|
467 | self.shell.magic_pdef(arg, namespaces=namespaces) | |
513 |
|
468 | |||
514 | def do_pdoc(self, arg): |
|
469 | def do_pdoc(self, arg): | |
515 | """The debugger interface to magic_pdoc""" |
|
470 | """The debugger interface to magic_pdoc""" | |
516 | namespaces = [('Locals', self.curframe.f_locals), |
|
471 | namespaces = [('Locals', self.curframe.f_locals), | |
517 | ('Globals', self.curframe.f_globals)] |
|
472 | ('Globals', self.curframe.f_globals)] | |
518 |
|
|
473 | self.shell.magic_pdoc(arg, namespaces=namespaces) | |
519 |
|
474 | |||
520 | def do_pinfo(self, arg): |
|
475 | def do_pinfo(self, arg): | |
521 | """The debugger equivalant of ?obj""" |
|
476 | """The debugger equivalant of ?obj""" | |
522 | namespaces = [('Locals', self.curframe.f_locals), |
|
477 | namespaces = [('Locals', self.curframe.f_locals), | |
523 | ('Globals', self.curframe.f_globals)] |
|
478 | ('Globals', self.curframe.f_globals)] | |
524 |
|
|
479 | self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces) | |
|
480 | ||||
|
481 | def checkline(self, filename, lineno): | |||
|
482 | """Check whether specified line seems to be executable. | |||
|
483 | ||||
|
484 | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank | |||
|
485 | line or EOF). Warning: testing is not comprehensive. | |||
|
486 | """ | |||
|
487 | ####################################################################### | |||
|
488 | # XXX Hack! Use python-2.5 compatible code for this call, because with | |||
|
489 | # all of our changes, we've drifted from the pdb api in 2.6. For now, | |||
|
490 | # changing: | |||
|
491 | # | |||
|
492 | #line = linecache.getline(filename, lineno, self.curframe.f_globals) | |||
|
493 | # to: | |||
|
494 | # | |||
|
495 | line = linecache.getline(filename, lineno) | |||
|
496 | # | |||
|
497 | # does the trick. But in reality, we need to fix this by reconciling | |||
|
498 | # our updates with the new Pdb APIs in Python 2.6. | |||
|
499 | # | |||
|
500 | # End hack. The rest of this method is copied verbatim from 2.6 pdb.py | |||
|
501 | ####################################################################### | |||
|
502 | ||||
|
503 | if not line: | |||
|
504 | print >>self.stdout, 'End of file' | |||
|
505 | return 0 | |||
|
506 | line = line.strip() | |||
|
507 | # Don't allow setting breakpoint at a blank line | |||
|
508 | if (not line or (line[0] == '#') or | |||
|
509 | (line[:3] == '"""') or line[:3] == "'''"): | |||
|
510 | print >>self.stdout, '*** Blank or comment' | |||
|
511 | return 0 | |||
|
512 | return lineno |
@@ -1,77 +1,77 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | A context manager for handling sys.displayhook. |
|
4 | A context manager for handling sys.displayhook. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Robert Kern |
|
8 | * Robert Kern | |
9 | * Brian Granger |
|
9 | * Brian Granger | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | # Copyright (C) 2008-2009 The IPython Development Team | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 | # Imports |
|
20 | # Imports | |
21 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
22 |
|
22 | |||
23 | import sys |
|
23 | import sys | |
24 |
|
24 | |||
25 | from IPython.core.component import Component |
|
25 | from IPython.core.component import Component | |
26 |
|
26 | |||
27 | from IPython.utils.autoattr import auto_attr |
|
27 | from IPython.utils.autoattr import auto_attr | |
28 |
|
28 | |||
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 | # Classes and functions |
|
30 | # Classes and functions | |
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | class DisplayTrap(Component): |
|
34 | class DisplayTrap(Component): | |
35 | """Object to manage sys.displayhook. |
|
35 | """Object to manage sys.displayhook. | |
36 |
|
36 | |||
37 | This came from IPython.core.kernel.display_hook, but is simplified |
|
37 | This came from IPython.core.kernel.display_hook, but is simplified | |
38 | (no callbacks or formatters) until more of the core is refactored. |
|
38 | (no callbacks or formatters) until more of the core is refactored. | |
39 | """ |
|
39 | """ | |
40 |
|
40 | |||
41 | def __init__(self, parent, hook): |
|
41 | def __init__(self, parent, hook): | |
42 | super(DisplayTrap, self).__init__(parent, None, None) |
|
42 | super(DisplayTrap, self).__init__(parent, None, None) | |
43 | self.hook = hook |
|
43 | self.hook = hook | |
44 | self.old_hook = None |
|
44 | self.old_hook = None | |
45 | # We define this to track if a single BuiltinTrap is nested. |
|
45 | # We define this to track if a single BuiltinTrap is nested. | |
46 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
46 | # Only turn off the trap when the outermost call to __exit__ is made. | |
47 | self._nested_level = 0 |
|
47 | self._nested_level = 0 | |
48 |
|
48 | |||
49 | @auto_attr |
|
49 | # @auto_attr | |
50 | def shell(self): |
|
50 | # def shell(self): | |
51 | return Component.get_instances( |
|
51 | # return Component.get_instances( | |
52 | root=self.root, |
|
52 | # root=self.root, | |
53 | klass='IPython.core.iplib.InteractiveShell')[0] |
|
53 | # klass='IPython.core.iplib.InteractiveShell')[0] | |
54 |
|
54 | |||
55 | def __enter__(self): |
|
55 | def __enter__(self): | |
56 | if self._nested_level == 0: |
|
56 | if self._nested_level == 0: | |
57 | self.set() |
|
57 | self.set() | |
58 | self._nested_level += 1 |
|
58 | self._nested_level += 1 | |
59 | return self |
|
59 | return self | |
60 |
|
60 | |||
61 | def __exit__(self, type, value, traceback): |
|
61 | def __exit__(self, type, value, traceback): | |
62 | if self._nested_level == 1: |
|
62 | if self._nested_level == 1: | |
63 | self.unset() |
|
63 | self.unset() | |
64 | self._nested_level -= 1 |
|
64 | self._nested_level -= 1 | |
65 | # Returning False will cause exceptions to propagate |
|
65 | # Returning False will cause exceptions to propagate | |
66 | return False |
|
66 | return False | |
67 |
|
67 | |||
68 | def set(self): |
|
68 | def set(self): | |
69 | """Set the hook.""" |
|
69 | """Set the hook.""" | |
70 | if sys.displayhook is not self.hook: |
|
70 | if sys.displayhook is not self.hook: | |
71 | self.old_hook = sys.displayhook |
|
71 | self.old_hook = sys.displayhook | |
72 | sys.displayhook = self.hook |
|
72 | sys.displayhook = self.hook | |
73 |
|
73 | |||
74 | def unset(self): |
|
74 | def unset(self): | |
75 | """Unset the hook.""" |
|
75 | """Unset the hook.""" | |
76 | sys.displayhook = self.old_hook |
|
76 | sys.displayhook = self.old_hook | |
77 |
|
77 |
@@ -1,280 +1,272 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | An embedded IPython shell. |
|
4 | An embedded IPython shell. | |
5 |
|
5 | |||
6 | Authors: |
|
6 | Authors: | |
7 |
|
7 | |||
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | * Fernando Perez |
|
9 | * Fernando Perez | |
10 |
|
10 | |||
11 | Notes |
|
11 | Notes | |
12 | ----- |
|
12 | ----- | |
13 | """ |
|
13 | """ | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
16 | # Copyright (C) 2008-2009 The IPython Development Team | |
17 | # |
|
17 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
19 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | from __future__ import with_statement |
|
26 | from __future__ import with_statement | |
27 |
|
27 | |||
28 | import sys |
|
28 | import sys | |
29 | from contextlib import nested |
|
29 | from contextlib import nested | |
30 |
|
30 | |||
31 | from IPython.core import ultratb |
|
31 | from IPython.core import ultratb | |
32 | from IPython.core.iplib import InteractiveShell |
|
32 | from IPython.core.iplib import InteractiveShell | |
33 | from IPython.core.ipapp import load_default_config |
|
33 | from IPython.core.ipapp import load_default_config | |
34 |
|
34 | |||
35 | from IPython.utils.traitlets import Bool, Str, CBool |
|
35 | from IPython.utils.traitlets import Bool, Str, CBool | |
36 | from IPython.utils.genutils import ask_yes_no |
|
36 | from IPython.utils.genutils import ask_yes_no | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 | # Classes and functions |
|
40 | # Classes and functions | |
41 | #----------------------------------------------------------------------------- |
|
41 | #----------------------------------------------------------------------------- | |
42 |
|
42 | |||
43 | # This is an additional magic that is exposed in embedded shells. |
|
43 | # This is an additional magic that is exposed in embedded shells. | |
44 | def kill_embedded(self,parameter_s=''): |
|
44 | def kill_embedded(self,parameter_s=''): | |
45 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
45 | """%kill_embedded : deactivate for good the current embedded IPython. | |
46 |
|
46 | |||
47 | This function (after asking for confirmation) sets an internal flag so that |
|
47 | This function (after asking for confirmation) sets an internal flag so that | |
48 | an embedded IPython will never activate again. This is useful to |
|
48 | an embedded IPython will never activate again. This is useful to | |
49 | permanently disable a shell that is being called inside a loop: once you've |
|
49 | permanently disable a shell that is being called inside a loop: once you've | |
50 | figured out what you needed from it, you may then kill it and the program |
|
50 | figured out what you needed from it, you may then kill it and the program | |
51 | will then continue to run without the interactive shell interfering again. |
|
51 | will then continue to run without the interactive shell interfering again. | |
52 | """ |
|
52 | """ | |
53 |
|
53 | |||
54 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
54 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " | |
55 | "(y/n)? [y/N] ",'n') |
|
55 | "(y/n)? [y/N] ",'n') | |
56 | if kill: |
|
56 | if kill: | |
57 | self.embedded_active = False |
|
57 | self.embedded_active = False | |
58 | print "This embedded IPython will not reactivate anymore once you exit." |
|
58 | print "This embedded IPython will not reactivate anymore once you exit." | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | class InteractiveShellEmbed(InteractiveShell): |
|
61 | class InteractiveShellEmbed(InteractiveShell): | |
62 |
|
62 | |||
63 | dummy_mode = Bool(False) |
|
63 | dummy_mode = Bool(False) | |
64 | exit_msg = Str('') |
|
64 | exit_msg = Str('') | |
65 | embedded = CBool(True) |
|
65 | embedded = CBool(True) | |
66 | embedded_active = CBool(True) |
|
66 | embedded_active = CBool(True) | |
67 | # Like the base class display_banner is not configurable, but here it |
|
67 | # Like the base class display_banner is not configurable, but here it | |
68 | # is True by default. |
|
68 | # is True by default. | |
69 | display_banner = CBool(True) |
|
69 | display_banner = CBool(True) | |
70 |
|
70 | |||
71 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
71 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, | |
72 | user_ns=None, user_global_ns=None, |
|
72 | user_ns=None, user_global_ns=None, | |
73 | banner1=None, banner2=None, display_banner=None, |
|
73 | banner1=None, banner2=None, display_banner=None, | |
74 | custom_exceptions=((),None), exit_msg=''): |
|
74 | custom_exceptions=((),None), exit_msg=''): | |
75 |
|
75 | |||
76 | self.save_sys_ipcompleter() |
|
76 | self.save_sys_ipcompleter() | |
77 |
|
77 | |||
78 | super(InteractiveShellEmbed,self).__init__( |
|
78 | super(InteractiveShellEmbed,self).__init__( | |
79 | parent=parent, config=config, ipythondir=ipythondir, usage=usage, |
|
79 | parent=parent, config=config, ipython_dir=ipython_dir, usage=usage, | |
80 | user_ns=user_ns, user_global_ns=user_global_ns, |
|
80 | user_ns=user_ns, user_global_ns=user_global_ns, | |
81 | banner1=banner1, banner2=banner2, display_banner=display_banner, |
|
81 | banner1=banner1, banner2=banner2, display_banner=display_banner, | |
82 | custom_exceptions=custom_exceptions) |
|
82 | custom_exceptions=custom_exceptions) | |
83 |
|
83 | |||
84 | self.exit_msg = exit_msg |
|
84 | self.exit_msg = exit_msg | |
85 | self.define_magic("kill_embedded", kill_embedded) |
|
85 | self.define_magic("kill_embedded", kill_embedded) | |
86 |
|
86 | |||
87 | # don't use the ipython crash handler so that user exceptions aren't |
|
87 | # don't use the ipython crash handler so that user exceptions aren't | |
88 | # trapped |
|
88 | # trapped | |
89 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
89 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, | |
90 | mode=self.xmode, |
|
90 | mode=self.xmode, | |
91 | call_pdb=self.pdb) |
|
91 | call_pdb=self.pdb) | |
92 |
|
92 | |||
93 | self.restore_sys_ipcompleter() |
|
93 | self.restore_sys_ipcompleter() | |
94 |
|
94 | |||
95 | def init_sys_modules(self): |
|
95 | def init_sys_modules(self): | |
96 | pass |
|
96 | pass | |
97 |
|
97 | |||
98 | def save_sys_ipcompleter(self): |
|
98 | def save_sys_ipcompleter(self): | |
99 | """Save readline completer status.""" |
|
99 | """Save readline completer status.""" | |
100 | try: |
|
100 | try: | |
101 | #print 'Save completer',sys.ipcompleter # dbg |
|
101 | #print 'Save completer',sys.ipcompleter # dbg | |
102 | self.sys_ipcompleter_orig = sys.ipcompleter |
|
102 | self.sys_ipcompleter_orig = sys.ipcompleter | |
103 | except: |
|
103 | except: | |
104 | pass # not nested with IPython |
|
104 | pass # not nested with IPython | |
105 |
|
105 | |||
106 | def restore_sys_ipcompleter(self): |
|
106 | def restore_sys_ipcompleter(self): | |
107 | """Restores the readline completer which was in place. |
|
107 | """Restores the readline completer which was in place. | |
108 |
|
108 | |||
109 | This allows embedded IPython within IPython not to disrupt the |
|
109 | This allows embedded IPython within IPython not to disrupt the | |
110 | parent's completion. |
|
110 | parent's completion. | |
111 | """ |
|
111 | """ | |
112 | try: |
|
112 | try: | |
113 | self.readline.set_completer(self.sys_ipcompleter_orig) |
|
113 | self.readline.set_completer(self.sys_ipcompleter_orig) | |
114 | sys.ipcompleter = self.sys_ipcompleter_orig |
|
114 | sys.ipcompleter = self.sys_ipcompleter_orig | |
115 | except: |
|
115 | except: | |
116 | pass |
|
116 | pass | |
117 |
|
117 | |||
118 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, |
|
118 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, | |
119 | stack_depth=1): |
|
119 | stack_depth=1): | |
120 | """Activate the interactive interpreter. |
|
120 | """Activate the interactive interpreter. | |
121 |
|
121 | |||
122 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
122 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start | |
123 | the interpreter shell with the given local and global namespaces, and |
|
123 | the interpreter shell with the given local and global namespaces, and | |
124 | optionally print a header string at startup. |
|
124 | optionally print a header string at startup. | |
125 |
|
125 | |||
126 | The shell can be globally activated/deactivated using the |
|
126 | The shell can be globally activated/deactivated using the | |
127 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
127 | set/get_dummy_mode methods. This allows you to turn off a shell used | |
128 | for debugging globally. |
|
128 | for debugging globally. | |
129 |
|
129 | |||
130 | However, *each* time you call the shell you can override the current |
|
130 | However, *each* time you call the shell you can override the current | |
131 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
131 | state of dummy_mode with the optional keyword parameter 'dummy'. For | |
132 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
132 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you | |
133 | can still have a specific call work by making it as IPShell(dummy=0). |
|
133 | can still have a specific call work by making it as IPShell(dummy=0). | |
134 |
|
134 | |||
135 | The optional keyword parameter dummy controls whether the call |
|
135 | The optional keyword parameter dummy controls whether the call | |
136 | actually does anything. |
|
136 | actually does anything. | |
137 | """ |
|
137 | """ | |
138 |
|
138 | |||
139 | # If the user has turned it off, go away |
|
139 | # If the user has turned it off, go away | |
140 | if not self.embedded_active: |
|
140 | if not self.embedded_active: | |
141 | return |
|
141 | return | |
142 |
|
142 | |||
143 | # Normal exits from interactive mode set this flag, so the shell can't |
|
143 | # Normal exits from interactive mode set this flag, so the shell can't | |
144 | # re-enter (it checks this variable at the start of interactive mode). |
|
144 | # re-enter (it checks this variable at the start of interactive mode). | |
145 | self.exit_now = False |
|
145 | self.exit_now = False | |
146 |
|
146 | |||
147 | # Allow the dummy parameter to override the global __dummy_mode |
|
147 | # Allow the dummy parameter to override the global __dummy_mode | |
148 | if dummy or (dummy != 0 and self.dummy_mode): |
|
148 | if dummy or (dummy != 0 and self.dummy_mode): | |
149 | return |
|
149 | return | |
150 |
|
150 | |||
151 | if self.has_readline: |
|
151 | if self.has_readline: | |
152 | self.set_completer() |
|
152 | self.set_completer() | |
153 |
|
153 | |||
154 | # self.banner is auto computed |
|
154 | # self.banner is auto computed | |
155 | if header: |
|
155 | if header: | |
156 | self.old_banner2 = self.banner2 |
|
156 | self.old_banner2 = self.banner2 | |
157 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
157 | self.banner2 = self.banner2 + '\n' + header + '\n' | |
158 |
|
158 | |||
159 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
159 | # Call the embedding code with a stack depth of 1 so it can skip over | |
160 | # our call and get the original caller's namespaces. |
|
160 | # our call and get the original caller's namespaces. | |
161 | self.mainloop(local_ns, global_ns, stack_depth=stack_depth) |
|
161 | self.mainloop(local_ns, global_ns, stack_depth=stack_depth) | |
162 |
|
162 | |||
163 | self.banner2 = self.old_banner2 |
|
163 | self.banner2 = self.old_banner2 | |
164 |
|
164 | |||
165 | if self.exit_msg is not None: |
|
165 | if self.exit_msg is not None: | |
166 | print self.exit_msg |
|
166 | print self.exit_msg | |
167 |
|
167 | |||
168 | self.restore_sys_ipcompleter() |
|
168 | self.restore_sys_ipcompleter() | |
169 |
|
169 | |||
170 | def mainloop(self, local_ns=None, global_ns=None, stack_depth=0, |
|
170 | def mainloop(self, local_ns=None, global_ns=None, stack_depth=0, | |
171 | display_banner=None): |
|
171 | display_banner=None): | |
172 | """Embeds IPython into a running python program. |
|
172 | """Embeds IPython into a running python program. | |
173 |
|
173 | |||
174 | Input: |
|
174 | Input: | |
175 |
|
175 | |||
176 | - header: An optional header message can be specified. |
|
176 | - header: An optional header message can be specified. | |
177 |
|
177 | |||
178 | - local_ns, global_ns: working namespaces. If given as None, the |
|
178 | - local_ns, global_ns: working namespaces. If given as None, the | |
179 | IPython-initialized one is updated with __main__.__dict__, so that |
|
179 | IPython-initialized one is updated with __main__.__dict__, so that | |
180 | program variables become visible but user-specific configuration |
|
180 | program variables become visible but user-specific configuration | |
181 | remains possible. |
|
181 | remains possible. | |
182 |
|
182 | |||
183 | - stack_depth: specifies how many levels in the stack to go to |
|
183 | - stack_depth: specifies how many levels in the stack to go to | |
184 | looking for namespaces (when local_ns and global_ns are None). This |
|
184 | looking for namespaces (when local_ns and global_ns are None). This | |
185 | allows an intermediate caller to make sure that this function gets |
|
185 | allows an intermediate caller to make sure that this function gets | |
186 | the namespace from the intended level in the stack. By default (0) |
|
186 | the namespace from the intended level in the stack. By default (0) | |
187 | it will get its locals and globals from the immediate caller. |
|
187 | it will get its locals and globals from the immediate caller. | |
188 |
|
188 | |||
189 | Warning: it's possible to use this in a program which is being run by |
|
189 | Warning: it's possible to use this in a program which is being run by | |
190 | IPython itself (via %run), but some funny things will happen (a few |
|
190 | IPython itself (via %run), but some funny things will happen (a few | |
191 | globals get overwritten). In the future this will be cleaned up, as |
|
191 | globals get overwritten). In the future this will be cleaned up, as | |
192 | there is no fundamental reason why it can't work perfectly.""" |
|
192 | there is no fundamental reason why it can't work perfectly.""" | |
193 |
|
193 | |||
194 | # Get locals and globals from caller |
|
194 | # Get locals and globals from caller | |
195 | if local_ns is None or global_ns is None: |
|
195 | if local_ns is None or global_ns is None: | |
196 | call_frame = sys._getframe(stack_depth).f_back |
|
196 | call_frame = sys._getframe(stack_depth).f_back | |
197 |
|
197 | |||
198 | if local_ns is None: |
|
198 | if local_ns is None: | |
199 | local_ns = call_frame.f_locals |
|
199 | local_ns = call_frame.f_locals | |
200 | if global_ns is None: |
|
200 | if global_ns is None: | |
201 | global_ns = call_frame.f_globals |
|
201 | global_ns = call_frame.f_globals | |
202 |
|
202 | |||
203 | # Update namespaces and fire up interpreter |
|
203 | # Update namespaces and fire up interpreter | |
204 |
|
204 | |||
205 | # The global one is easy, we can just throw it in |
|
205 | # The global one is easy, we can just throw it in | |
206 | self.user_global_ns = global_ns |
|
206 | self.user_global_ns = global_ns | |
207 |
|
207 | |||
208 | # but the user/local one is tricky: ipython needs it to store internal |
|
208 | # but the user/local one is tricky: ipython needs it to store internal | |
209 | # data, but we also need the locals. We'll copy locals in the user |
|
209 | # data, but we also need the locals. We'll copy locals in the user | |
210 | # one, but will track what got copied so we can delete them at exit. |
|
210 | # one, but will track what got copied so we can delete them at exit. | |
211 | # This is so that a later embedded call doesn't see locals from a |
|
211 | # This is so that a later embedded call doesn't see locals from a | |
212 | # previous call (which most likely existed in a separate scope). |
|
212 | # previous call (which most likely existed in a separate scope). | |
213 | local_varnames = local_ns.keys() |
|
213 | local_varnames = local_ns.keys() | |
214 | self.user_ns.update(local_ns) |
|
214 | self.user_ns.update(local_ns) | |
215 | #self.user_ns['local_ns'] = local_ns # dbg |
|
215 | #self.user_ns['local_ns'] = local_ns # dbg | |
216 |
|
216 | |||
217 | # Patch for global embedding to make sure that things don't overwrite |
|
217 | # Patch for global embedding to make sure that things don't overwrite | |
218 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
218 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> | |
219 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
219 | # FIXME. Test this a bit more carefully (the if.. is new) | |
220 | if local_ns is None and global_ns is None: |
|
220 | if local_ns is None and global_ns is None: | |
221 | self.user_global_ns.update(__main__.__dict__) |
|
221 | self.user_global_ns.update(__main__.__dict__) | |
222 |
|
222 | |||
223 | # make sure the tab-completer has the correct frame information, so it |
|
223 | # make sure the tab-completer has the correct frame information, so it | |
224 | # actually completes using the frame's locals/globals |
|
224 | # actually completes using the frame's locals/globals | |
225 | self.set_completer_frame() |
|
225 | self.set_completer_frame() | |
226 |
|
226 | |||
227 | with nested(self.builtin_trap, self.display_trap): |
|
227 | with nested(self.builtin_trap, self.display_trap): | |
228 | self.interact(display_banner=display_banner) |
|
228 | self.interact(display_banner=display_banner) | |
229 |
|
229 | |||
230 | # now, purge out the user namespace from anything we might have added |
|
230 | # now, purge out the user namespace from anything we might have added | |
231 | # from the caller's local namespace |
|
231 | # from the caller's local namespace | |
232 | delvar = self.user_ns.pop |
|
232 | delvar = self.user_ns.pop | |
233 | for var in local_varnames: |
|
233 | for var in local_varnames: | |
234 | delvar(var,None) |
|
234 | delvar(var,None) | |
235 |
|
235 | |||
236 | def set_completer_frame(self, frame=None): |
|
|||
237 | if frame: |
|
|||
238 | self.Completer.namespace = frame.f_locals |
|
|||
239 | self.Completer.global_namespace = frame.f_globals |
|
|||
240 | else: |
|
|||
241 | self.Completer.namespace = self.user_ns |
|
|||
242 | self.Completer.global_namespace = self.user_global_ns |
|
|||
243 |
|
||||
244 |
|
236 | |||
245 | _embedded_shell = None |
|
237 | _embedded_shell = None | |
246 |
|
238 | |||
247 |
|
239 | |||
248 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, |
|
240 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, | |
249 | display_banner=True, exit_msg=''): |
|
241 | display_banner=True, exit_msg=''): | |
250 | """Call this to embed IPython at the current point in your program. |
|
242 | """Call this to embed IPython at the current point in your program. | |
251 |
|
243 | |||
252 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
244 | The first invocation of this will create an :class:`InteractiveShellEmbed` | |
253 | instance and then call it. Consecutive calls just call the already |
|
245 | instance and then call it. Consecutive calls just call the already | |
254 | created instance. |
|
246 | created instance. | |
255 |
|
247 | |||
256 | Here is a simple example:: |
|
248 | Here is a simple example:: | |
257 |
|
249 | |||
258 | from IPython import embed |
|
250 | from IPython import embed | |
259 | a = 10 |
|
251 | a = 10 | |
260 | b = 20 |
|
252 | b = 20 | |
261 | embed('First time') |
|
253 | embed('First time') | |
262 | c = 30 |
|
254 | c = 30 | |
263 | d = 40 |
|
255 | d = 40 | |
264 | embed |
|
256 | embed | |
265 |
|
257 | |||
266 | Full customization can be done by passing a :class:`Struct` in as the |
|
258 | Full customization can be done by passing a :class:`Struct` in as the | |
267 | config argument. |
|
259 | config argument. | |
268 | """ |
|
260 | """ | |
269 | if config is None: |
|
261 | if config is None: | |
270 | config = load_default_config() |
|
262 | config = load_default_config() | |
271 | config.InteractiveShellEmbed = config.InteractiveShell |
|
263 | config.InteractiveShellEmbed = config.InteractiveShell | |
272 | global _embedded_shell |
|
264 | global _embedded_shell | |
273 | if _embedded_shell is None: |
|
265 | if _embedded_shell is None: | |
274 | _embedded_shell = InteractiveShellEmbed( |
|
266 | _embedded_shell = InteractiveShellEmbed( | |
275 | config=config, usage=usage, |
|
267 | config=config, usage=usage, | |
276 | banner1=banner1, banner2=banner2, |
|
268 | banner1=banner1, banner2=banner2, | |
277 | display_banner=display_banner, exit_msg=exit_msg |
|
269 | display_banner=display_banner, exit_msg=exit_msg | |
278 | ) |
|
270 | ) | |
279 | _embedded_shell(header=header, stack_depth=2) |
|
271 | _embedded_shell(header=header, stack_depth=2) | |
280 |
|
272 |
@@ -1,254 +1,274 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ History related magics and functionality """ |
|
2 | """ History related magics and functionality """ | |
3 |
|
3 | |||
4 | # Stdlib imports |
|
4 | # Stdlib imports | |
5 | import fnmatch |
|
5 | import fnmatch | |
6 | import os |
|
6 | import os | |
7 |
|
7 | |||
8 | from IPython.utils.genutils import Term, ask_yes_no, warn |
|
8 | from IPython.utils.genutils import Term, ask_yes_no, warn | |
9 | from IPython.core import ipapi |
|
9 | from IPython.core import ipapi | |
10 |
|
10 | |||
11 | def magic_history(self, parameter_s = ''): |
|
11 | def magic_history(self, parameter_s = ''): | |
12 | """Print input history (_i<n> variables), with most recent last. |
|
12 | """Print input history (_i<n> variables), with most recent last. | |
13 |
|
13 | |||
14 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
14 | %history -> print at most 40 inputs (some may be multi-line)\\ | |
15 | %history n -> print at most n inputs\\ |
|
15 | %history n -> print at most n inputs\\ | |
16 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
16 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ | |
17 |
|
||||
18 | Each input's number <n> is shown, and is accessible as the |
|
|||
19 | automatically generated variable _i<n>. Multi-line statements are |
|
|||
20 | printed starting at a new line for easy copy/paste. |
|
|||
21 |
|
||||
22 |
|
17 | |||
23 | Options: |
|
18 | By default, input history is printed without line numbers so it can be | |
|
19 | directly pasted into an editor. | |||
24 |
|
20 | |||
25 | -n: do NOT print line numbers. This is useful if you want to get a |
|
21 | With -n, each input's number <n> is shown, and is accessible as the | |
26 | printout of many lines which can be directly pasted into a text |
|
22 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
27 | editor. |
|
23 | statements are printed starting at a new line for easy copy/paste. | |
|
24 | ||||
|
25 | Options: | |||
28 |
|
26 | |||
|
27 | -n: print line numbers for each input. | |||
29 | This feature is only available if numbered prompts are in use. |
|
28 | This feature is only available if numbered prompts are in use. | |
30 |
|
29 | |||
|
30 | -o: also print outputs for each input. | |||
|
31 | ||||
|
32 | -p: print classic '>>>' python prompts before each input. This is useful | |||
|
33 | for making documentation, and in conjunction with -o, for producing | |||
|
34 | doctest-ready output. | |||
|
35 | ||||
31 | -t: (default) print the 'translated' history, as IPython understands it. |
|
36 | -t: (default) print the 'translated' history, as IPython understands it. | |
32 | IPython filters your input and converts it all into valid Python source |
|
37 | IPython filters your input and converts it all into valid Python source | |
33 | before executing it (things like magics or aliases are turned into |
|
38 | before executing it (things like magics or aliases are turned into | |
34 | function calls, for example). With this option, you'll see the native |
|
39 | function calls, for example). With this option, you'll see the native | |
35 | history instead of the user-entered version: '%cd /' will be seen as |
|
40 | history instead of the user-entered version: '%cd /' will be seen as | |
36 | '_ip.magic("%cd /")' instead of '%cd /'. |
|
41 | '_ip.magic("%cd /")' instead of '%cd /'. | |
37 |
|
42 | |||
38 | -r: print the 'raw' history, i.e. the actual commands you typed. |
|
43 | -r: print the 'raw' history, i.e. the actual commands you typed. | |
39 |
|
44 | |||
40 | -g: treat the arg as a pattern to grep for in (full) history. |
|
45 | -g: treat the arg as a pattern to grep for in (full) history. | |
41 | This includes the "shadow history" (almost all commands ever written). |
|
46 | This includes the "shadow history" (almost all commands ever written). | |
42 | Use '%hist -g' to show full shadow history (may be very long). |
|
47 | Use '%hist -g' to show full shadow history (may be very long). | |
43 | In shadow history, every index nuwber starts with 0. |
|
48 | In shadow history, every index nuwber starts with 0. | |
44 |
|
49 | |||
45 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
50 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
46 | the given file. The file is always overwritten, though IPython asks for |
|
51 | the given file. The file is always overwritten, though IPython asks for | |
47 | confirmation first if it already exists. |
|
52 | confirmation first if it already exists. | |
48 | """ |
|
53 | """ | |
49 |
|
54 | |||
50 | if not self.outputcache.do_full_cache: |
|
55 | if not self.outputcache.do_full_cache: | |
51 | print 'This feature is only available if numbered prompts are in use.' |
|
56 | print 'This feature is only available if numbered prompts are in use.' | |
52 | return |
|
57 | return | |
53 | opts,args = self.parse_options(parameter_s,'gntsrf:',mode='list') |
|
58 | opts,args = self.parse_options(parameter_s,'gnoptsrf:',mode='list') | |
54 |
|
59 | |||
55 | # Check if output to specific file was requested. |
|
60 | # Check if output to specific file was requested. | |
56 | try: |
|
61 | try: | |
57 | outfname = opts['f'] |
|
62 | outfname = opts['f'] | |
58 | except KeyError: |
|
63 | except KeyError: | |
59 | outfile = Term.cout # default |
|
64 | outfile = Term.cout # default | |
60 | # We don't want to close stdout at the end! |
|
65 | # We don't want to close stdout at the end! | |
61 | close_at_end = False |
|
66 | close_at_end = False | |
62 | else: |
|
67 | else: | |
63 | if os.path.exists(outfname): |
|
68 | if os.path.exists(outfname): | |
64 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
69 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
65 | print 'Aborting.' |
|
70 | print 'Aborting.' | |
66 | return |
|
71 | return | |
67 |
|
72 | |||
68 | outfile = open(outfname,'w') |
|
73 | outfile = open(outfname,'w') | |
69 | close_at_end = True |
|
74 | close_at_end = True | |
70 |
|
75 | |||
71 | if 't' in opts: |
|
76 | if 't' in opts: | |
72 | input_hist = self.input_hist |
|
77 | input_hist = self.input_hist | |
73 | elif 'r' in opts: |
|
78 | elif 'r' in opts: | |
74 | input_hist = self.input_hist_raw |
|
79 | input_hist = self.input_hist_raw | |
75 | else: |
|
80 | else: | |
76 | input_hist = self.input_hist |
|
81 | input_hist = self.input_hist | |
77 |
|
82 | |||
78 | default_length = 40 |
|
83 | default_length = 40 | |
79 | pattern = None |
|
84 | pattern = None | |
80 | if 'g' in opts: |
|
85 | if 'g' in opts: | |
81 | init = 1 |
|
86 | init = 1 | |
82 | final = len(input_hist) |
|
87 | final = len(input_hist) | |
83 | parts = parameter_s.split(None,1) |
|
88 | parts = parameter_s.split(None,1) | |
84 | if len(parts) == 1: |
|
89 | if len(parts) == 1: | |
85 | parts += '*' |
|
90 | parts += '*' | |
86 | head, pattern = parts |
|
91 | head, pattern = parts | |
87 | pattern = "*" + pattern + "*" |
|
92 | pattern = "*" + pattern + "*" | |
88 | elif len(args) == 0: |
|
93 | elif len(args) == 0: | |
89 | final = len(input_hist) |
|
94 | final = len(input_hist) | |
90 | init = max(1,final-default_length) |
|
95 | init = max(1,final-default_length) | |
91 | elif len(args) == 1: |
|
96 | elif len(args) == 1: | |
92 | final = len(input_hist) |
|
97 | final = len(input_hist) | |
93 | init = max(1,final-int(args[0])) |
|
98 | init = max(1,final-int(args[0])) | |
94 | elif len(args) == 2: |
|
99 | elif len(args) == 2: | |
95 | init,final = map(int,args) |
|
100 | init,final = map(int,args) | |
96 | else: |
|
101 | else: | |
97 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
102 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') | |
98 | print self.magic_hist.__doc__ |
|
103 | print self.magic_hist.__doc__ | |
99 | return |
|
104 | return | |
|
105 | ||||
100 | width = len(str(final)) |
|
106 | width = len(str(final)) | |
101 | line_sep = ['','\n'] |
|
107 | line_sep = ['','\n'] | |
102 |
print_nums = |
|
108 | print_nums = 'n' in opts | |
|
109 | print_outputs = 'o' in opts | |||
|
110 | pyprompts = 'p' in opts | |||
103 |
|
111 | |||
104 | found = False |
|
112 | found = False | |
105 | if pattern is not None: |
|
113 | if pattern is not None: | |
106 | sh = self.shadowhist.all() |
|
114 | sh = self.shadowhist.all() | |
107 | for idx, s in sh: |
|
115 | for idx, s in sh: | |
108 | if fnmatch.fnmatch(s, pattern): |
|
116 | if fnmatch.fnmatch(s, pattern): | |
109 | print "0%d: %s" %(idx, s) |
|
117 | print "0%d: %s" %(idx, s) | |
110 | found = True |
|
118 | found = True | |
111 |
|
119 | |||
112 | if found: |
|
120 | if found: | |
113 | print "===" |
|
121 | print "===" | |
114 | print "shadow history ends, fetch by %rep <number> (must start with 0)" |
|
122 | print "shadow history ends, fetch by %rep <number> (must start with 0)" | |
115 | print "=== start of normal history ===" |
|
123 | print "=== start of normal history ===" | |
116 |
|
124 | |||
117 | for in_num in range(init,final): |
|
125 | for in_num in range(init,final): | |
118 | inline = input_hist[in_num] |
|
126 | inline = input_hist[in_num] | |
119 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
127 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): | |
120 | continue |
|
128 | continue | |
121 |
|
129 | |||
122 | multiline = int(inline.count('\n') > 1) |
|
130 | multiline = int(inline.count('\n') > 1) | |
123 | if print_nums: |
|
131 | if print_nums: | |
124 | print >> outfile, \ |
|
132 | print >> outfile, \ | |
125 | '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), |
|
133 | '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]), | |
126 | print >> outfile, inline, |
|
134 | if pyprompts: | |
|
135 | print >> outfile, '>>>', | |||
|
136 | if multiline: | |||
|
137 | lines = inline.splitlines() | |||
|
138 | print >> outfile, '\n... '.join(lines) | |||
|
139 | print >> outfile, '... ' | |||
|
140 | else: | |||
|
141 | print >> outfile, inline, | |||
|
142 | else: | |||
|
143 | print >> outfile, inline, | |||
|
144 | output = self.shell.user_ns['Out'].get(in_num) | |||
|
145 | if output is not None: | |||
|
146 | print repr(output) | |||
127 |
|
147 | |||
128 | if close_at_end: |
|
148 | if close_at_end: | |
129 | outfile.close() |
|
149 | outfile.close() | |
130 |
|
150 | |||
131 |
|
151 | |||
132 | def magic_hist(self, parameter_s=''): |
|
152 | def magic_hist(self, parameter_s=''): | |
133 | """Alternate name for %history.""" |
|
153 | """Alternate name for %history.""" | |
134 | return self.magic_history(parameter_s) |
|
154 | return self.magic_history(parameter_s) | |
135 |
|
155 | |||
136 |
|
156 | |||
137 | def rep_f(self, arg): |
|
157 | def rep_f(self, arg): | |
138 | r""" Repeat a command, or get command to input line for editing |
|
158 | r""" Repeat a command, or get command to input line for editing | |
139 |
|
159 | |||
140 | - %rep (no arguments): |
|
160 | - %rep (no arguments): | |
141 |
|
161 | |||
142 | Place a string version of last computation result (stored in the special '_' |
|
162 | Place a string version of last computation result (stored in the special '_' | |
143 | variable) to the next input prompt. Allows you to create elaborate command |
|
163 | variable) to the next input prompt. Allows you to create elaborate command | |
144 | lines without using copy-paste:: |
|
164 | lines without using copy-paste:: | |
145 |
|
165 | |||
146 | $ l = ["hei", "vaan"] |
|
166 | $ l = ["hei", "vaan"] | |
147 | $ "".join(l) |
|
167 | $ "".join(l) | |
148 | ==> heivaan |
|
168 | ==> heivaan | |
149 | $ %rep |
|
169 | $ %rep | |
150 | $ heivaan_ <== cursor blinking |
|
170 | $ heivaan_ <== cursor blinking | |
151 |
|
171 | |||
152 | %rep 45 |
|
172 | %rep 45 | |
153 |
|
173 | |||
154 | Place history line 45 to next input prompt. Use %hist to find out the |
|
174 | Place history line 45 to next input prompt. Use %hist to find out the | |
155 | number. |
|
175 | number. | |
156 |
|
176 | |||
157 | %rep 1-4 6-7 3 |
|
177 | %rep 1-4 6-7 3 | |
158 |
|
178 | |||
159 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
179 | Repeat the specified lines immediately. Input slice syntax is the same as | |
160 | in %macro and %save. |
|
180 | in %macro and %save. | |
161 |
|
181 | |||
162 | %rep foo |
|
182 | %rep foo | |
163 |
|
183 | |||
164 | Place the most recent line that has the substring "foo" to next input. |
|
184 | Place the most recent line that has the substring "foo" to next input. | |
165 | (e.g. 'svn ci -m foobar'). |
|
185 | (e.g. 'svn ci -m foobar'). | |
166 | """ |
|
186 | """ | |
167 |
|
187 | |||
168 | opts,args = self.parse_options(arg,'',mode='list') |
|
188 | opts,args = self.parse_options(arg,'',mode='list') | |
169 | if not args: |
|
189 | if not args: | |
170 | self.set_next_input(str(self.user_ns["_"])) |
|
190 | self.set_next_input(str(self.user_ns["_"])) | |
171 | return |
|
191 | return | |
172 |
|
192 | |||
173 | if len(args) == 1 and not '-' in args[0]: |
|
193 | if len(args) == 1 and not '-' in args[0]: | |
174 | arg = args[0] |
|
194 | arg = args[0] | |
175 | if len(arg) > 1 and arg.startswith('0'): |
|
195 | if len(arg) > 1 and arg.startswith('0'): | |
176 | # get from shadow hist |
|
196 | # get from shadow hist | |
177 | num = int(arg[1:]) |
|
197 | num = int(arg[1:]) | |
178 | line = self.shadowhist.get(num) |
|
198 | line = self.shadowhist.get(num) | |
179 | self.set_next_input(str(line)) |
|
199 | self.set_next_input(str(line)) | |
180 | return |
|
200 | return | |
181 | try: |
|
201 | try: | |
182 | num = int(args[0]) |
|
202 | num = int(args[0]) | |
183 | self.set_next_input(str(self.input_hist_raw[num]).rstrip()) |
|
203 | self.set_next_input(str(self.input_hist_raw[num]).rstrip()) | |
184 | return |
|
204 | return | |
185 | except ValueError: |
|
205 | except ValueError: | |
186 | pass |
|
206 | pass | |
187 |
|
207 | |||
188 | for h in reversed(self.input_hist_raw): |
|
208 | for h in reversed(self.input_hist_raw): | |
189 | if 'rep' in h: |
|
209 | if 'rep' in h: | |
190 | continue |
|
210 | continue | |
191 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
211 | if fnmatch.fnmatch(h,'*' + arg + '*'): | |
192 | self.set_next_input(str(h).rstrip()) |
|
212 | self.set_next_input(str(h).rstrip()) | |
193 | return |
|
213 | return | |
194 |
|
214 | |||
195 | try: |
|
215 | try: | |
196 | lines = self.extract_input_slices(args, True) |
|
216 | lines = self.extract_input_slices(args, True) | |
197 | print "lines",lines |
|
217 | print "lines",lines | |
198 | self.runlines(lines) |
|
218 | self.runlines(lines) | |
199 | except ValueError: |
|
219 | except ValueError: | |
200 | print "Not found in recent history:", args |
|
220 | print "Not found in recent history:", args | |
201 |
|
221 | |||
202 |
|
222 | |||
203 | _sentinel = object() |
|
223 | _sentinel = object() | |
204 |
|
224 | |||
205 | class ShadowHist(object): |
|
225 | class ShadowHist(object): | |
206 | def __init__(self,db): |
|
226 | def __init__(self,db): | |
207 | # cmd => idx mapping |
|
227 | # cmd => idx mapping | |
208 | self.curidx = 0 |
|
228 | self.curidx = 0 | |
209 | self.db = db |
|
229 | self.db = db | |
210 | self.disabled = False |
|
230 | self.disabled = False | |
211 |
|
231 | |||
212 | def inc_idx(self): |
|
232 | def inc_idx(self): | |
213 | idx = self.db.get('shadowhist_idx', 1) |
|
233 | idx = self.db.get('shadowhist_idx', 1) | |
214 | self.db['shadowhist_idx'] = idx + 1 |
|
234 | self.db['shadowhist_idx'] = idx + 1 | |
215 | return idx |
|
235 | return idx | |
216 |
|
236 | |||
217 | def add(self, ent): |
|
237 | def add(self, ent): | |
218 | if self.disabled: |
|
238 | if self.disabled: | |
219 | return |
|
239 | return | |
220 | try: |
|
240 | try: | |
221 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
241 | old = self.db.hget('shadowhist', ent, _sentinel) | |
222 | if old is not _sentinel: |
|
242 | if old is not _sentinel: | |
223 | return |
|
243 | return | |
224 | newidx = self.inc_idx() |
|
244 | newidx = self.inc_idx() | |
225 | #print "new",newidx # dbg |
|
245 | #print "new",newidx # dbg | |
226 | self.db.hset('shadowhist',ent, newidx) |
|
246 | self.db.hset('shadowhist',ent, newidx) | |
227 | except: |
|
247 | except: | |
228 | ipapi.get().showtraceback() |
|
248 | ipapi.get().showtraceback() | |
229 | print "WARNING: disabling shadow history" |
|
249 | print "WARNING: disabling shadow history" | |
230 | self.disabled = True |
|
250 | self.disabled = True | |
231 |
|
251 | |||
232 | def all(self): |
|
252 | def all(self): | |
233 | d = self.db.hdict('shadowhist') |
|
253 | d = self.db.hdict('shadowhist') | |
234 | items = [(i,s) for (s,i) in d.items()] |
|
254 | items = [(i,s) for (s,i) in d.items()] | |
235 | items.sort() |
|
255 | items.sort() | |
236 | return items |
|
256 | return items | |
237 |
|
257 | |||
238 | def get(self, idx): |
|
258 | def get(self, idx): | |
239 | all = self.all() |
|
259 | all = self.all() | |
240 |
|
260 | |||
241 | for k, v in all: |
|
261 | for k, v in all: | |
242 | #print k,v |
|
262 | #print k,v | |
243 | if k == idx: |
|
263 | if k == idx: | |
244 | return v |
|
264 | return v | |
245 |
|
265 | |||
246 |
|
266 | |||
247 | def init_ipython(ip): |
|
267 | def init_ipython(ip): | |
248 | import ipy_completers |
|
|||
249 |
|
||||
250 | ip.define_magic("rep",rep_f) |
|
268 | ip.define_magic("rep",rep_f) | |
251 | ip.define_magic("hist",magic_hist) |
|
269 | ip.define_magic("hist",magic_hist) | |
252 | ip.define_magic("history",magic_history) |
|
270 | ip.define_magic("history",magic_history) | |
253 |
|
271 | |||
254 | ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
272 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
|
273 | #import ipy_completers | |||
|
274 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,274 +1,273 b'' | |||||
1 | """hooks for IPython. |
|
1 | """hooks for IPython. | |
2 |
|
2 | |||
3 | In Python, it is possible to overwrite any method of any object if you really |
|
3 | In Python, it is possible to overwrite any method of any object if you really | |
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to | |
5 | be overwritten by users for customization purposes. This module defines the |
|
5 | be overwritten by users for customization purposes. This module defines the | |
6 | default versions of all such hooks, which get used by IPython if not |
|
6 | default versions of all such hooks, which get used by IPython if not | |
7 | overridden by the user. |
|
7 | overridden by the user. | |
8 |
|
8 | |||
9 | hooks are simple functions, but they should be declared with 'self' as their |
|
9 | hooks are simple functions, but they should be declared with 'self' as their | |
10 | first argument, because when activated they are registered into IPython as |
|
10 | first argument, because when activated they are registered into IPython as | |
11 | instance methods. The self argument will be the IPython running instance |
|
11 | instance methods. The self argument will be the IPython running instance | |
12 | itself, so hooks have full access to the entire IPython object. |
|
12 | itself, so hooks have full access to the entire IPython object. | |
13 |
|
13 | |||
14 | If you wish to define a new hook and activate it, you need to put the |
|
14 | If you wish to define a new hook and activate it, you need to put the | |
15 | necessary code into a python file which can be either imported or execfile()'d |
|
15 | necessary code into a python file which can be either imported or execfile()'d | |
16 | from within your ipythonrc configuration. |
|
16 | from within your ipythonrc configuration. | |
17 |
|
17 | |||
18 | For example, suppose that you have a module called 'myiphooks' in your |
|
18 | 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 | from IPython.core import ipapi |
|
22 | from IPython.core import ipapi | |
23 | ip = 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 TryNext() |
|
29 | raise TryNext() | |
30 |
|
30 | |||
31 | ip.set_hook('editor', calljed) |
|
31 | ip.set_hook('editor', calljed) | |
32 |
|
32 | |||
33 | You can then enable the functionality by doing 'import myiphooks' |
|
33 | You can then enable the functionality by doing 'import myiphooks' | |
34 | somewhere in your configuration files or ipython command line. |
|
34 | somewhere in your configuration files or ipython command line. | |
35 | """ |
|
35 | """ | |
36 |
|
36 | |||
37 | #***************************************************************************** |
|
37 | #***************************************************************************** | |
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> | |
39 | # |
|
39 | # | |
40 | # Distributed under the terms of the BSD License. The full license is in |
|
40 | # Distributed under the terms of the BSD License. The full license is in | |
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 | import os, bisect |
|
44 | import os, bisect | |
45 | import sys |
|
45 | import sys | |
46 | from IPython.utils.genutils import Term, shell |
|
46 | from IPython.utils.genutils import Term, shell | |
47 | from pprint import PrettyPrinter |
|
47 | from pprint import PrettyPrinter | |
48 |
|
48 | |||
49 | from IPython.core.error import TryNext |
|
49 | from IPython.core.error import TryNext | |
50 |
|
50 | |||
51 | # List here all the default hooks. For now it's just the editor functions |
|
51 | # List here all the default hooks. For now it's just the editor functions | |
52 | # but over time we'll move here all the public API for user-accessible things. |
|
52 | # but over time we'll move here all the public API for user-accessible things. | |
53 |
|
53 | |||
54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', |
|
54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', | |
55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', | |
56 | 'generate_prompt', 'generate_output_prompt','shell_hook', |
|
56 | 'generate_prompt', 'generate_output_prompt','shell_hook', | |
57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', |
|
57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', | |
58 | 'clipboard_get'] |
|
58 | 'clipboard_get'] | |
59 |
|
59 | |||
60 | pformat = PrettyPrinter().pformat |
|
60 | pformat = PrettyPrinter().pformat | |
61 |
|
61 | |||
62 | def editor(self,filename, linenum=None): |
|
62 | def editor(self,filename, linenum=None): | |
63 | """Open the default editor at the given filename and linenumber. |
|
63 | """Open the default editor at the given filename and linenumber. | |
64 |
|
64 | |||
65 | This is IPython's default editor hook, you can use it as an example to |
|
65 | This is IPython's default editor hook, you can use it as an example to | |
66 | write your own modified one. To set your own editor function as the |
|
66 | write your own modified one. To set your own editor function as the | |
67 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
67 | new editor hook, call ip.set_hook('editor',yourfunc).""" | |
68 |
|
68 | |||
69 | # IPython configures a default editor at startup by reading $EDITOR from |
|
69 | # IPython configures a default editor at startup by reading $EDITOR from | |
70 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
70 | # the environment, and falling back on vi (unix) or notepad (win32). | |
71 | editor = self.editor |
|
71 | editor = self.editor | |
72 |
|
72 | |||
73 | # marker for at which line to open the file (for existing objects) |
|
73 | # marker for at which line to open the file (for existing objects) | |
74 | if linenum is None or editor=='notepad': |
|
74 | if linenum is None or editor=='notepad': | |
75 | linemark = '' |
|
75 | linemark = '' | |
76 | else: |
|
76 | else: | |
77 | linemark = '+%d' % int(linenum) |
|
77 | linemark = '+%d' % int(linenum) | |
78 |
|
78 | |||
79 | # Enclose in quotes if necessary and legal |
|
79 | # Enclose in quotes if necessary and legal | |
80 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
80 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': | |
81 | editor = '"%s"' % editor |
|
81 | editor = '"%s"' % editor | |
82 |
|
82 | |||
83 | # Call the actual editor |
|
83 | # Call the actual editor | |
84 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
84 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: | |
85 | raise TryNext() |
|
85 | raise TryNext() | |
86 |
|
86 | |||
87 | import tempfile |
|
87 | import tempfile | |
88 | def fix_error_editor(self,filename,linenum,column,msg): |
|
88 | def fix_error_editor(self,filename,linenum,column,msg): | |
89 | """Open the editor at the given filename, linenumber, column and |
|
89 | """Open the editor at the given filename, linenumber, column and | |
90 | show an error message. This is used for correcting syntax errors. |
|
90 | show an error message. This is used for correcting syntax errors. | |
91 | The current implementation only has special support for the VIM editor, |
|
91 | The current implementation only has special support for the VIM editor, | |
92 | and falls back on the 'editor' hook if VIM is not used. |
|
92 | and falls back on the 'editor' hook if VIM is not used. | |
93 |
|
93 | |||
94 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
94 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, | |
95 | """ |
|
95 | """ | |
96 | def vim_quickfix_file(): |
|
96 | def vim_quickfix_file(): | |
97 | t = tempfile.NamedTemporaryFile() |
|
97 | t = tempfile.NamedTemporaryFile() | |
98 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
98 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) | |
99 | t.flush() |
|
99 | t.flush() | |
100 | return t |
|
100 | return t | |
101 | if os.path.basename(self.editor) != 'vim': |
|
101 | if os.path.basename(self.editor) != 'vim': | |
102 | self.hooks.editor(filename,linenum) |
|
102 | self.hooks.editor(filename,linenum) | |
103 | return |
|
103 | return | |
104 | t = vim_quickfix_file() |
|
104 | t = vim_quickfix_file() | |
105 | try: |
|
105 | try: | |
106 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
106 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): | |
107 | raise TryNext() |
|
107 | raise TryNext() | |
108 | finally: |
|
108 | finally: | |
109 | t.close() |
|
109 | t.close() | |
110 |
|
110 | |||
111 |
|
111 | |||
112 | def synchronize_with_editor(self, filename, linenum, column): |
|
112 | def synchronize_with_editor(self, filename, linenum, column): | |
113 | pass |
|
113 | pass | |
114 |
|
114 | |||
115 |
|
115 | |||
116 | class CommandChainDispatcher: |
|
116 | class CommandChainDispatcher: | |
117 | """ Dispatch calls to a chain of commands until some func can handle it |
|
117 | """ Dispatch calls to a chain of commands until some func can handle it | |
118 |
|
118 | |||
119 | Usage: instantiate, execute "add" to add commands (with optional |
|
119 | Usage: instantiate, execute "add" to add commands (with optional | |
120 | priority), execute normally via f() calling mechanism. |
|
120 | priority), execute normally via f() calling mechanism. | |
121 |
|
121 | |||
122 | """ |
|
122 | """ | |
123 | def __init__(self,commands=None): |
|
123 | def __init__(self,commands=None): | |
124 | if commands is None: |
|
124 | if commands is None: | |
125 | self.chain = [] |
|
125 | self.chain = [] | |
126 | else: |
|
126 | else: | |
127 | self.chain = commands |
|
127 | self.chain = commands | |
128 |
|
128 | |||
129 |
|
129 | |||
130 | def __call__(self,*args, **kw): |
|
130 | def __call__(self,*args, **kw): | |
131 | """ Command chain is called just like normal func. |
|
131 | """ Command chain is called just like normal func. | |
132 |
|
132 | |||
133 | This will call all funcs in chain with the same args as were given to this |
|
133 | This will call all funcs in chain with the same args as were given to this | |
134 | function, and return the result of first func that didn't raise |
|
134 | function, and return the result of first func that didn't raise | |
135 | TryNext """ |
|
135 | TryNext """ | |
136 |
|
136 | |||
137 | for prio,cmd in self.chain: |
|
137 | for prio,cmd in self.chain: | |
138 | #print "prio",prio,"cmd",cmd #dbg |
|
138 | #print "prio",prio,"cmd",cmd #dbg | |
139 | try: |
|
139 | try: | |
140 |
ret |
|
140 | return cmd(*args, **kw) | |
141 | return ret |
|
|||
142 | except TryNext, exc: |
|
141 | except TryNext, exc: | |
143 | if exc.args or exc.kwargs: |
|
142 | if exc.args or exc.kwargs: | |
144 | args = exc.args |
|
143 | args = exc.args | |
145 | kw = exc.kwargs |
|
144 | kw = exc.kwargs | |
146 | # if no function will accept it, raise TryNext up to the caller |
|
145 | # if no function will accept it, raise TryNext up to the caller | |
147 | raise TryNext |
|
146 | raise TryNext | |
148 |
|
147 | |||
149 | def __str__(self): |
|
148 | def __str__(self): | |
150 | return str(self.chain) |
|
149 | return str(self.chain) | |
151 |
|
150 | |||
152 | def add(self, func, priority=0): |
|
151 | def add(self, func, priority=0): | |
153 | """ Add a func to the cmd chain with given priority """ |
|
152 | """ Add a func to the cmd chain with given priority """ | |
154 | bisect.insort(self.chain,(priority,func)) |
|
153 | bisect.insort(self.chain,(priority,func)) | |
155 |
|
154 | |||
156 | def __iter__(self): |
|
155 | def __iter__(self): | |
157 | """ Return all objects in chain. |
|
156 | """ Return all objects in chain. | |
158 |
|
157 | |||
159 | Handy if the objects are not callable. |
|
158 | Handy if the objects are not callable. | |
160 | """ |
|
159 | """ | |
161 | return iter(self.chain) |
|
160 | return iter(self.chain) | |
162 |
|
161 | |||
163 |
|
162 | |||
164 | def result_display(self,arg): |
|
163 | def result_display(self,arg): | |
165 | """ Default display hook. |
|
164 | """ Default display hook. | |
166 |
|
165 | |||
167 | Called for displaying the result to the user. |
|
166 | Called for displaying the result to the user. | |
168 | """ |
|
167 | """ | |
169 |
|
168 | |||
170 | if self.pprint: |
|
169 | if self.pprint: | |
171 | out = pformat(arg) |
|
170 | out = pformat(arg) | |
172 | if '\n' in out: |
|
171 | if '\n' in out: | |
173 | # So that multi-line strings line up with the left column of |
|
172 | # So that multi-line strings line up with the left column of | |
174 | # the screen, instead of having the output prompt mess up |
|
173 | # the screen, instead of having the output prompt mess up | |
175 | # their first line. |
|
174 | # their first line. | |
176 | Term.cout.write('\n') |
|
175 | Term.cout.write('\n') | |
177 | print >>Term.cout, out |
|
176 | print >>Term.cout, out | |
178 | else: |
|
177 | else: | |
179 | # By default, the interactive prompt uses repr() to display results, |
|
178 | # By default, the interactive prompt uses repr() to display results, | |
180 | # so we should honor this. Users who'd rather use a different |
|
179 | # so we should honor this. Users who'd rather use a different | |
181 | # mechanism can easily override this hook. |
|
180 | # mechanism can easily override this hook. | |
182 | print >>Term.cout, repr(arg) |
|
181 | print >>Term.cout, repr(arg) | |
183 | # the default display hook doesn't manipulate the value to put in history |
|
182 | # the default display hook doesn't manipulate the value to put in history | |
184 | return None |
|
183 | return None | |
185 |
|
184 | |||
186 |
|
185 | |||
187 | def input_prefilter(self,line): |
|
186 | def input_prefilter(self,line): | |
188 | """ Default input prefilter |
|
187 | """ Default input prefilter | |
189 |
|
188 | |||
190 | This returns the line as unchanged, so that the interpreter |
|
189 | This returns the line as unchanged, so that the interpreter | |
191 | knows that nothing was done and proceeds with "classic" prefiltering |
|
190 | knows that nothing was done and proceeds with "classic" prefiltering | |
192 | (%magics, !shell commands etc.). |
|
191 | (%magics, !shell commands etc.). | |
193 |
|
192 | |||
194 | Note that leading whitespace is not passed to this hook. Prefilter |
|
193 | Note that leading whitespace is not passed to this hook. Prefilter | |
195 | can't alter indentation. |
|
194 | can't alter indentation. | |
196 |
|
195 | |||
197 | """ |
|
196 | """ | |
198 | #print "attempt to rewrite",line #dbg |
|
197 | #print "attempt to rewrite",line #dbg | |
199 | return line |
|
198 | return line | |
200 |
|
199 | |||
201 |
|
200 | |||
202 | def shutdown_hook(self): |
|
201 | def shutdown_hook(self): | |
203 | """ default shutdown hook |
|
202 | """ default shutdown hook | |
204 |
|
203 | |||
205 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
204 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done | |
206 | """ |
|
205 | """ | |
207 |
|
206 | |||
208 | #print "default shutdown hook ok" # dbg |
|
207 | #print "default shutdown hook ok" # dbg | |
209 | return |
|
208 | return | |
210 |
|
209 | |||
211 |
|
210 | |||
212 | def late_startup_hook(self): |
|
211 | def late_startup_hook(self): | |
213 | """ Executed after ipython has been constructed and configured |
|
212 | """ Executed after ipython has been constructed and configured | |
214 |
|
213 | |||
215 | """ |
|
214 | """ | |
216 | #print "default startup hook ok" # dbg |
|
215 | #print "default startup hook ok" # dbg | |
217 |
|
216 | |||
218 |
|
217 | |||
219 | def generate_prompt(self, is_continuation): |
|
218 | def generate_prompt(self, is_continuation): | |
220 | """ calculate and return a string with the prompt to display """ |
|
219 | """ calculate and return a string with the prompt to display """ | |
221 | if is_continuation: |
|
220 | if is_continuation: | |
222 | return str(self.outputcache.prompt2) |
|
221 | return str(self.outputcache.prompt2) | |
223 | return str(self.outputcache.prompt1) |
|
222 | return str(self.outputcache.prompt1) | |
224 |
|
223 | |||
225 |
|
224 | |||
226 | def generate_output_prompt(self): |
|
225 | def generate_output_prompt(self): | |
227 | return str(self.outputcache.prompt_out) |
|
226 | return str(self.outputcache.prompt_out) | |
228 |
|
227 | |||
229 |
|
228 | |||
230 | def shell_hook(self,cmd): |
|
229 | def shell_hook(self,cmd): | |
231 | """ Run system/shell command a'la os.system() """ |
|
230 | """ Run system/shell command a'la os.system() """ | |
232 |
|
231 | |||
233 | shell(cmd, header=self.system_header, verbose=self.system_verbose) |
|
232 | shell(cmd, header=self.system_header, verbose=self.system_verbose) | |
234 |
|
233 | |||
235 |
|
234 | |||
236 | def show_in_pager(self,s): |
|
235 | def show_in_pager(self,s): | |
237 | """ Run a string through pager """ |
|
236 | """ Run a string through pager """ | |
238 | # raising TryNext here will use the default paging functionality |
|
237 | # raising TryNext here will use the default paging functionality | |
239 | raise TryNext |
|
238 | raise TryNext | |
240 |
|
239 | |||
241 |
|
240 | |||
242 | def pre_prompt_hook(self): |
|
241 | def pre_prompt_hook(self): | |
243 | """ Run before displaying the next prompt |
|
242 | """ Run before displaying the next prompt | |
244 |
|
243 | |||
245 | Use this e.g. to display output from asynchronous operations (in order |
|
244 | Use this e.g. to display output from asynchronous operations (in order | |
246 | to not mess up text entry) |
|
245 | to not mess up text entry) | |
247 | """ |
|
246 | """ | |
248 |
|
247 | |||
249 | return None |
|
248 | return None | |
250 |
|
249 | |||
251 |
|
250 | |||
252 | def pre_runcode_hook(self): |
|
251 | def pre_runcode_hook(self): | |
253 | """ Executed before running the (prefiltered) code in IPython """ |
|
252 | """ Executed before running the (prefiltered) code in IPython """ | |
254 | return None |
|
253 | return None | |
255 |
|
254 | |||
256 |
|
255 | |||
257 | def clipboard_get(self): |
|
256 | def clipboard_get(self): | |
258 | """ Get text from the clipboard. |
|
257 | """ Get text from the clipboard. | |
259 | """ |
|
258 | """ | |
260 | from IPython.lib.clipboard import ( |
|
259 | from IPython.lib.clipboard import ( | |
261 | osx_clipboard_get, tkinter_clipboard_get, |
|
260 | osx_clipboard_get, tkinter_clipboard_get, | |
262 | win32_clipboard_get |
|
261 | win32_clipboard_get | |
263 | ) |
|
262 | ) | |
264 | if sys.platform == 'win32': |
|
263 | if sys.platform == 'win32': | |
265 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
264 | chain = [win32_clipboard_get, tkinter_clipboard_get] | |
266 | elif sys.platform == 'darwin': |
|
265 | elif sys.platform == 'darwin': | |
267 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
266 | chain = [osx_clipboard_get, tkinter_clipboard_get] | |
268 | else: |
|
267 | else: | |
269 | chain = [tkinter_clipboard_get] |
|
268 | chain = [tkinter_clipboard_get] | |
270 | dispatcher = CommandChainDispatcher() |
|
269 | dispatcher = CommandChainDispatcher() | |
271 | for func in chain: |
|
270 | for func in chain: | |
272 | dispatcher.add(func) |
|
271 | dispatcher.add(func) | |
273 | text = dispatcher() |
|
272 | text = dispatcher() | |
274 | return text |
|
273 | return text |
@@ -1,35 +1,38 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | This module is *completely* deprecated and should no longer be used for |
|
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 |
|
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 |
|
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. |
|
7 | has been made into a component, this module will be sent to deathrow. | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | # Copyright (C) 2008-2009 The IPython Development Team | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Imports |
|
18 | # Imports | |
19 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
20 |
|
20 | |||
21 | from IPython.core.error import TryNext, UsageError |
|
21 | from IPython.core.error import TryNext, UsageError, IPythonCoreError | |
22 |
|
22 | |||
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | # Classes and functions |
|
24 | # Classes and functions | |
25 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
26 |
|
26 | |||
|
27 | ||||
27 | def get(): |
|
28 | def get(): | |
28 | """Get the most recently created InteractiveShell instance.""" |
|
29 | """Get the most recently created InteractiveShell instance.""" | |
29 | from IPython.core.iplib import InteractiveShell |
|
30 | from IPython.core.iplib import InteractiveShell | |
30 | insts = InteractiveShell.get_instances() |
|
31 | insts = InteractiveShell.get_instances() | |
|
32 | if len(insts)==0: | |||
|
33 | return None | |||
31 | most_recent = insts[0] |
|
34 | most_recent = insts[0] | |
32 | for inst in insts[1:]: |
|
35 | for inst in insts[1:]: | |
33 | if inst.created > most_recent.created: |
|
36 | if inst.created > most_recent.created: | |
34 | most_recent = inst |
|
37 | most_recent = inst | |
35 | return most_recent |
|
38 | return most_recent |
This diff has been collapsed as it changes many lines, (579 lines changed) Show them Hide them | |||||
@@ -1,546 +1,655 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | The main IPython application object |
|
4 | The :class:`~IPython.core.application.Application` object for the command | |
|
5 | line :command:`ipython` program. | |||
5 |
|
6 | |||
6 |
Authors |
|
7 | Authors | |
|
8 | ------- | |||
7 |
|
9 | |||
8 | * Brian Granger |
|
10 | * Brian Granger | |
9 | * Fernando Perez |
|
11 | * Fernando Perez | |
10 |
|
||||
11 | Notes |
|
|||
12 | ----- |
|
|||
13 | """ |
|
12 | """ | |
14 |
|
13 | |||
15 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
16 |
# Copyright (C) 2008-200 |
|
15 | # Copyright (C) 2008-2010 The IPython Development Team | |
17 | # |
|
16 | # | |
18 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | # Distributed under the terms of the BSD License. The full license is in | |
19 | # the file COPYING, distributed as part of this software. |
|
18 | # the file COPYING, distributed as part of this software. | |
20 | #----------------------------------------------------------------------------- |
|
19 | #----------------------------------------------------------------------------- | |
21 |
|
20 | |||
22 | #----------------------------------------------------------------------------- |
|
21 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
22 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
|
24 | from __future__ import absolute_import | |||
25 |
|
25 | |||
26 | import logging |
|
26 | import logging | |
27 | import os |
|
27 | import os | |
28 | import sys |
|
28 | import sys | |
29 | import warnings |
|
|||
30 |
|
29 | |||
31 | from IPython.core.application import Application, IPythonArgParseConfigLoader |
|
30 | from IPython.core import crashhandler | |
32 |
from IPython.core import |
|
31 | from IPython.core.application import Application | |
33 | from IPython.core.iplib import InteractiveShell |
|
32 | from IPython.core.iplib import InteractiveShell | |
34 | from IPython.config.loader import ( |
|
33 | from IPython.config.loader import ( | |
35 | NoConfigDefault, |
|
|||
36 | Config, |
|
34 | Config, | |
37 |
Config |
|
35 | PyFileConfigLoader, | |
38 | PyFileConfigLoader |
|
36 | # NoConfigDefault, | |
39 | ) |
|
37 | ) | |
40 |
|
||||
41 | from IPython.lib import inputhook |
|
38 | from IPython.lib import inputhook | |
42 |
|
||||
43 | from IPython.utils.ipstruct import Struct |
|
|||
44 | from IPython.utils.genutils import filefind, get_ipython_dir |
|
39 | from IPython.utils.genutils import filefind, get_ipython_dir | |
|
40 | from . import usage | |||
45 |
|
41 | |||
46 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
47 |
# |
|
43 | # Globals, utilities and helpers | |
48 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
49 |
|
45 | |||
50 |
|
46 | default_config_file_name = u'ipython_config.py' | ||
51 | ipython_desc = """ |
|
|||
52 | A Python shell with automatic history (input and output), dynamic object |
|
|||
53 | introspection, easier configuration, command completion, access to the system |
|
|||
54 | shell and more. |
|
|||
55 | """ |
|
|||
56 |
|
||||
57 | def pylab_warning(): |
|
|||
58 | msg = """ |
|
|||
59 |
|
||||
60 | IPython's -pylab mode has been disabled until matplotlib supports this version |
|
|||
61 | of IPython. This version of IPython has greatly improved GUI integration that |
|
|||
62 | matplotlib will soon be able to take advantage of. This will eventually |
|
|||
63 | result in greater stability and a richer API for matplotlib under IPython. |
|
|||
64 | However during this transition, you will either need to use an older version |
|
|||
65 | of IPython, or do the following to use matplotlib interactively:: |
|
|||
66 |
|
||||
67 | import matplotlib |
|
|||
68 | matplotlib.interactive(True) |
|
|||
69 | matplotlib.use('wxagg') # adjust for your backend |
|
|||
70 | %gui -a wx # adjust for your GUI |
|
|||
71 | from matplotlib import pyplot as plt |
|
|||
72 |
|
||||
73 | See the %gui magic for information on the new interface. |
|
|||
74 | """ |
|
|||
75 | warnings.warn(msg, category=DeprecationWarning, stacklevel=1) |
|
|||
76 |
|
||||
77 |
|
||||
78 | #----------------------------------------------------------------------------- |
|
|||
79 | # Main classes and functions |
|
|||
80 | #----------------------------------------------------------------------------- |
|
|||
81 |
|
47 | |||
82 | cl_args = ( |
|
48 | cl_args = ( | |
83 | (('-autocall',), dict( |
|
49 | (('--autocall',), dict( | |
84 |
type=int, dest='InteractiveShell.autocall', |
|
50 | type=int, dest='InteractiveShell.autocall', | |
85 | help='Set the autocall value (0,1,2).', |
|
51 | help= | |
|
52 | """Make IPython automatically call any callable object even if you | |||
|
53 | didn't type explicit parentheses. For example, 'str 43' becomes | |||
|
54 | 'str(43)' automatically. The value can be '0' to disable the feature, | |||
|
55 | '1' for 'smart' autocall, where it is not applied if there are no more | |||
|
56 | arguments on the line, and '2' for 'full' autocall, where all callable | |||
|
57 | objects are automatically called (even if no arguments are present). | |||
|
58 | The default is '1'.""", | |||
86 | metavar='InteractiveShell.autocall') |
|
59 | metavar='InteractiveShell.autocall') | |
87 | ), |
|
60 | ), | |
88 | (('-autoindent',), dict( |
|
61 | (('--autoindent',), dict( | |
89 |
action='store_true', dest='InteractiveShell.autoindent', |
|
62 | action='store_true', dest='InteractiveShell.autoindent', | |
90 | help='Turn on autoindenting.') |
|
63 | help='Turn on autoindenting.') | |
91 | ), |
|
64 | ), | |
92 | (('-noautoindent',), dict( |
|
65 | (('--no-autoindent',), dict( | |
93 |
action='store_false', dest='InteractiveShell.autoindent', |
|
66 | action='store_false', dest='InteractiveShell.autoindent', | |
94 | help='Turn off autoindenting.') |
|
67 | help='Turn off autoindenting.') | |
95 | ), |
|
68 | ), | |
96 | (('-automagic',), dict( |
|
69 | (('--automagic',), dict( | |
97 |
action='store_true', dest='InteractiveShell.automagic', |
|
70 | action='store_true', dest='InteractiveShell.automagic', | |
98 |
help='Turn on the auto calling of magic commands.' |
|
71 | help='Turn on the auto calling of magic commands.' | |
99 | ), |
|
72 | 'Type %%magic at the IPython prompt for more information.') | |
100 | (('-noautomagic',), dict( |
|
73 | ), | |
101 | action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault, |
|
74 | (('--no-automagic',), dict( | |
|
75 | action='store_false', dest='InteractiveShell.automagic', | |||
102 | help='Turn off the auto calling of magic commands.') |
|
76 | help='Turn off the auto calling of magic commands.') | |
103 | ), |
|
77 | ), | |
104 |
(('-autoedit |
|
78 | (('--autoedit-syntax',), dict( | |
105 |
action='store_true', dest='InteractiveShell.autoedit_syntax', |
|
79 | action='store_true', dest='InteractiveShell.autoedit_syntax', | |
106 | help='Turn on auto editing of files with syntax errors.') |
|
80 | help='Turn on auto editing of files with syntax errors.') | |
107 | ), |
|
81 | ), | |
108 |
(('-noautoedit |
|
82 | (('--no-autoedit-syntax',), dict( | |
109 |
action='store_false', dest='InteractiveShell.autoedit_syntax', |
|
83 | action='store_false', dest='InteractiveShell.autoedit_syntax', | |
110 | help='Turn off auto editing of files with syntax errors.') |
|
84 | help='Turn off auto editing of files with syntax errors.') | |
111 | ), |
|
85 | ), | |
112 | (('-banner',), dict( |
|
86 | (('--banner',), dict( | |
113 |
action='store_true', dest='Global.display_banner', |
|
87 | action='store_true', dest='Global.display_banner', | |
114 | help='Display a banner upon starting IPython.') |
|
88 | help='Display a banner upon starting IPython.') | |
115 | ), |
|
89 | ), | |
116 | (('-nobanner',), dict( |
|
90 | (('--no-banner',), dict( | |
117 |
action='store_false', dest='Global.display_banner', |
|
91 | action='store_false', dest='Global.display_banner', | |
118 | help="Don't display a banner upon starting IPython.") |
|
92 | help="Don't display a banner upon starting IPython.") | |
119 | ), |
|
93 | ), | |
120 |
(('-cache |
|
94 | (('--cache-size',), dict( | |
121 |
type=int, dest='InteractiveShell.cache_size', |
|
95 | type=int, dest='InteractiveShell.cache_size', | |
122 | help="Set the size of the output cache.", |
|
96 | help= | |
|
97 | """Set the size of the output cache. The default is 1000, you can | |||
|
98 | change it permanently in your config file. Setting it to 0 completely | |||
|
99 | disables the caching system, and the minimum value accepted is 20 (if | |||
|
100 | you provide a value less than 20, it is reset to 0 and a warning is | |||
|
101 | issued). This limit is defined because otherwise you'll spend more | |||
|
102 | time re-flushing a too small cache than working. | |||
|
103 | """, | |||
123 | metavar='InteractiveShell.cache_size') |
|
104 | metavar='InteractiveShell.cache_size') | |
124 | ), |
|
105 | ), | |
125 | (('-classic',), dict( |
|
106 | (('--classic',), dict( | |
126 |
action='store_true', dest='Global.classic', |
|
107 | action='store_true', dest='Global.classic', | |
127 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
108 | help="Gives IPython a similar feel to the classic Python prompt.") | |
128 | ), |
|
109 | ), | |
129 | (('-colors',), dict( |
|
110 | (('--colors',), dict( | |
130 |
type=str, dest='InteractiveShell.colors', |
|
111 | type=str, dest='InteractiveShell.colors', | |
131 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
112 | help="Set the color scheme (NoColor, Linux, and LightBG).", | |
132 | metavar='InteractiveShell.colors') |
|
113 | metavar='InteractiveShell.colors') | |
133 | ), |
|
114 | ), | |
134 |
(('-color |
|
115 | (('--color-info',), dict( | |
135 |
action='store_true', dest='InteractiveShell.color_info', |
|
116 | action='store_true', dest='InteractiveShell.color_info', | |
136 | help="Enable using colors for info related things.") |
|
117 | help= | |
|
118 | """IPython can display information about objects via a set of func- | |||
|
119 | tions, and optionally can use colors for this, syntax highlighting | |||
|
120 | source code and various other elements. However, because this | |||
|
121 | information is passed through a pager (like 'less') and many pagers get | |||
|
122 | confused with color codes, this option is off by default. You can test | |||
|
123 | it and turn it on permanently in your ipython_config.py file if it | |||
|
124 | works for you. Test it and turn it on permanently if it works with | |||
|
125 | your system. The magic function %%color_info allows you to toggle this | |||
|
126 | inter- actively for testing.""" | |||
|
127 | ) | |||
137 | ), |
|
128 | ), | |
138 |
(('- |
|
129 | (('--no-color-info',), dict( | |
139 |
action='store_false', dest='InteractiveShell.color_info', |
|
130 | action='store_false', dest='InteractiveShell.color_info', | |
140 | help="Disable using colors for info related things.") |
|
131 | help="Disable using colors for info related things.") | |
141 | ), |
|
132 | ), | |
142 |
(('-confirm |
|
133 | (('--confirm-exit',), dict( | |
143 |
action='store_true', dest='InteractiveShell.confirm_exit', |
|
134 | action='store_true', dest='InteractiveShell.confirm_exit', | |
144 | help="Prompt the user when existing.") |
|
135 | help= | |
145 | ), |
|
136 | """Set to confirm when you try to exit IPython with an EOF (Control-D | |
146 | (('-noconfirm_exit',), dict( |
|
137 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or | |
147 | action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, |
|
138 | '%%Exit', you can force a direct exit without any confirmation. | |
148 | help="Don't prompt the user when existing.") |
|
139 | """ | |
149 |
) |
|
140 | ) | |
150 | (('-deep_reload',), dict( |
|
|||
151 | action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault, |
|
|||
152 | help="Enable deep (recursive) reloading by default.") |
|
|||
153 | ), |
|
141 | ), | |
154 |
(('- |
|
142 | (('--no-confirm-exit',), dict( | |
155 |
action='store_false', dest='InteractiveShell. |
|
143 | action='store_false', dest='InteractiveShell.confirm_exit', | |
|
144 | help="Don't prompt the user when exiting.") | |||
|
145 | ), | |||
|
146 | (('--deep-reload',), dict( | |||
|
147 | action='store_true', dest='InteractiveShell.deep_reload', | |||
|
148 | help= | |||
|
149 | """Enable deep (recursive) reloading by default. IPython can use the | |||
|
150 | deep_reload module which reloads changes in modules recursively (it | |||
|
151 | replaces the reload() function, so you don't need to change anything to | |||
|
152 | use it). deep_reload() forces a full reload of modules whose code may | |||
|
153 | have changed, which the default reload() function does not. When | |||
|
154 | deep_reload is off, IPython will use the normal reload(), but | |||
|
155 | deep_reload will still be available as dreload(). This fea- ture is off | |||
|
156 | by default [which means that you have both normal reload() and | |||
|
157 | dreload()].""") | |||
|
158 | ), | |||
|
159 | (('--no-deep-reload',), dict( | |||
|
160 | action='store_false', dest='InteractiveShell.deep_reload', | |||
156 | help="Disable deep (recursive) reloading by default.") |
|
161 | help="Disable deep (recursive) reloading by default.") | |
157 | ), |
|
162 | ), | |
158 | (('-editor',), dict( |
|
163 | (('--editor',), dict( | |
159 |
type=str, dest='InteractiveShell.editor', |
|
164 | type=str, dest='InteractiveShell.editor', | |
160 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
165 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", | |
161 | metavar='InteractiveShell.editor') |
|
166 | metavar='InteractiveShell.editor') | |
162 | ), |
|
167 | ), | |
163 | (('-log','-l'), dict( |
|
168 | (('--log','-l'), dict( | |
164 |
action='store_true', dest='InteractiveShell.logstart', |
|
169 | action='store_true', dest='InteractiveShell.logstart', | |
165 | help="Start logging to the default file (./ipython_log.py).") |
|
170 | help="Start logging to the default log file (./ipython_log.py).") | |
166 | ), |
|
171 | ), | |
167 | (('-logfile','-lf'), dict( |
|
172 | (('--logfile','-lf'), dict( | |
168 |
type= |
|
173 | type=unicode, dest='InteractiveShell.logfile', | |
169 | help="Start logging to logfile.", |
|
174 | help="Start logging to logfile with this name.", | |
170 | metavar='InteractiveShell.logfile') |
|
175 | metavar='InteractiveShell.logfile') | |
171 | ), |
|
176 | ), | |
172 | (('-logappend','-la'), dict( |
|
177 | (('--log-append','-la'), dict( | |
173 |
type= |
|
178 | type=unicode, dest='InteractiveShell.logappend', | |
174 |
help="Start logging to |
|
179 | help="Start logging to the given file in append mode.", | |
175 | metavar='InteractiveShell.logfile') |
|
180 | metavar='InteractiveShell.logfile') | |
176 | ), |
|
181 | ), | |
177 | (('-pdb',), dict( |
|
182 | (('--pdb',), dict( | |
178 |
action='store_true', dest='InteractiveShell.pdb', |
|
183 | action='store_true', dest='InteractiveShell.pdb', | |
179 | help="Enable auto calling the pdb debugger after every exception.") |
|
184 | help="Enable auto calling the pdb debugger after every exception.") | |
180 | ), |
|
185 | ), | |
181 | (('-nopdb',), dict( |
|
186 | (('--no-pdb',), dict( | |
182 |
action='store_false', dest='InteractiveShell.pdb', |
|
187 | action='store_false', dest='InteractiveShell.pdb', | |
183 | help="Disable auto calling the pdb debugger after every exception.") |
|
188 | help="Disable auto calling the pdb debugger after every exception.") | |
184 | ), |
|
189 | ), | |
185 | (('-pprint',), dict( |
|
190 | (('--pprint',), dict( | |
186 |
action='store_true', dest='InteractiveShell.pprint', |
|
191 | action='store_true', dest='InteractiveShell.pprint', | |
187 | help="Enable auto pretty printing of results.") |
|
192 | help="Enable auto pretty printing of results.") | |
188 | ), |
|
193 | ), | |
189 | (('-nopprint',), dict( |
|
194 | (('--no-pprint',), dict( | |
190 |
action='store_false', dest='InteractiveShell.pprint', |
|
195 | action='store_false', dest='InteractiveShell.pprint', | |
191 | help="Disable auto auto pretty printing of results.") |
|
196 | help="Disable auto auto pretty printing of results.") | |
192 | ), |
|
197 | ), | |
193 |
(('-prompt |
|
198 | (('--prompt-in1','-pi1'), dict( | |
194 |
type=str, dest='InteractiveShell.prompt_in1', |
|
199 | type=str, dest='InteractiveShell.prompt_in1', | |
195 | help="Set the main input prompt ('In [\#]: ')", |
|
200 | help= | |
|
201 | """Set the main input prompt ('In [\#]: '). Note that if you are using | |||
|
202 | numbered prompts, the number is represented with a '\#' in the string. | |||
|
203 | Don't forget to quote strings with spaces embedded in them. Most | |||
|
204 | bash-like escapes can be used to customize IPython's prompts, as well | |||
|
205 | as a few additional ones which are IPython-spe- cific. All valid | |||
|
206 | prompt escapes are described in detail in the Customization section of | |||
|
207 | the IPython manual.""", | |||
196 | metavar='InteractiveShell.prompt_in1') |
|
208 | metavar='InteractiveShell.prompt_in1') | |
197 | ), |
|
209 | ), | |
198 |
(('-prompt |
|
210 | (('--prompt-in2','-pi2'), dict( | |
199 |
type=str, dest='InteractiveShell.prompt_in2', |
|
211 | type=str, dest='InteractiveShell.prompt_in2', | |
200 | help="Set the secondary input prompt (' .\D.: ')", |
|
212 | help= | |
|
213 | """Set the secondary input prompt (' .\D.: '). Similar to the previous | |||
|
214 | option, but used for the continuation prompts. The special sequence | |||
|
215 | '\D' is similar to '\#', but with all digits replaced by dots (so you | |||
|
216 | can have your continuation prompt aligned with your input prompt). | |||
|
217 | Default: ' .\D.: ' (note three spaces at the start for alignment with | |||
|
218 | 'In [\#]')""", | |||
201 | metavar='InteractiveShell.prompt_in2') |
|
219 | metavar='InteractiveShell.prompt_in2') | |
202 | ), |
|
220 | ), | |
203 |
(('-prompt |
|
221 | (('--prompt-out','-po'), dict( | |
204 |
type=str, dest='InteractiveShell.prompt_out', |
|
222 | type=str, dest='InteractiveShell.prompt_out', | |
205 | help="Set the output prompt ('Out[\#]:')", |
|
223 | help="Set the output prompt ('Out[\#]:')", | |
206 | metavar='InteractiveShell.prompt_out') |
|
224 | metavar='InteractiveShell.prompt_out') | |
207 | ), |
|
225 | ), | |
208 | (('-quick',), dict( |
|
226 | (('--quick',), dict( | |
209 |
action='store_true', dest='Global.quick', |
|
227 | action='store_true', dest='Global.quick', | |
210 | help="Enable quick startup with no config files.") |
|
228 | help="Enable quick startup with no config files.") | |
211 | ), |
|
229 | ), | |
212 | (('-readline',), dict( |
|
230 | (('--readline',), dict( | |
213 |
action='store_true', dest='InteractiveShell.readline_use', |
|
231 | action='store_true', dest='InteractiveShell.readline_use', | |
214 | help="Enable readline for command line usage.") |
|
232 | help="Enable readline for command line usage.") | |
215 | ), |
|
233 | ), | |
216 | (('-noreadline',), dict( |
|
234 | (('--no-readline',), dict( | |
217 |
action='store_false', dest='InteractiveShell.readline_use', |
|
235 | action='store_false', dest='InteractiveShell.readline_use', | |
218 | help="Disable readline for command line usage.") |
|
236 | help="Disable readline for command line usage.") | |
219 | ), |
|
237 | ), | |
220 |
(('-screen |
|
238 | (('--screen-length','-sl'), dict( | |
221 |
type=int, dest='InteractiveShell.screen_length', |
|
239 | type=int, dest='InteractiveShell.screen_length', | |
222 | help='Number of lines on screen, used to control printing of long strings.', |
|
240 | help= | |
|
241 | """Number of lines of your screen, used to control printing of very | |||
|
242 | long strings. Strings longer than this number of lines will be sent | |||
|
243 | through a pager instead of directly printed. The default value for | |||
|
244 | this is 0, which means IPython will auto-detect your screen size every | |||
|
245 | time it needs to print certain potentially long strings (this doesn't | |||
|
246 | change the behavior of the 'print' keyword, it's only triggered | |||
|
247 | internally). If for some reason this isn't working well (it needs | |||
|
248 | curses support), specify it yourself. Otherwise don't change the | |||
|
249 | default.""", | |||
223 | metavar='InteractiveShell.screen_length') |
|
250 | metavar='InteractiveShell.screen_length') | |
224 | ), |
|
251 | ), | |
225 |
(('-separate |
|
252 | (('--separate-in','-si'), dict( | |
226 |
type=str, dest='InteractiveShell.separate_in', |
|
253 | type=str, dest='InteractiveShell.separate_in', | |
227 | help="Separator before input prompts. Default '\n'.", |
|
254 | help="Separator before input prompts. Default '\\n'.", | |
228 | metavar='InteractiveShell.separate_in') |
|
255 | metavar='InteractiveShell.separate_in') | |
229 | ), |
|
256 | ), | |
230 |
(('-separate |
|
257 | (('--separate-out','-so'), dict( | |
231 |
type=str, dest='InteractiveShell.separate_out', |
|
258 | type=str, dest='InteractiveShell.separate_out', | |
232 | help="Separator before output prompts. Default 0 (nothing).", |
|
259 | help="Separator before output prompts. Default 0 (nothing).", | |
233 | metavar='InteractiveShell.separate_out') |
|
260 | metavar='InteractiveShell.separate_out') | |
234 | ), |
|
261 | ), | |
235 |
(('-separate |
|
262 | (('--separate-out2','-so2'), dict( | |
236 |
type=str, dest='InteractiveShell.separate_out2', |
|
263 | type=str, dest='InteractiveShell.separate_out2', | |
237 | help="Separator after output prompts. Default 0 (nonight).", |
|
264 | help="Separator after output prompts. Default 0 (nonight).", | |
238 | metavar='InteractiveShell.separate_out2') |
|
265 | metavar='InteractiveShell.separate_out2') | |
239 | ), |
|
266 | ), | |
240 | (('-nosep',), dict( |
|
267 | (('-no-sep',), dict( | |
241 |
action='store_true', dest='Global.nosep', |
|
268 | action='store_true', dest='Global.nosep', | |
242 | help="Eliminate all spacing between prompts.") |
|
269 | help="Eliminate all spacing between prompts.") | |
243 | ), |
|
270 | ), | |
244 |
(('- |
|
271 | (('--term-title',), dict( | |
245 |
action='store_true', dest='InteractiveShell.term_title', |
|
272 | action='store_true', dest='InteractiveShell.term_title', | |
246 | help="Enable auto setting the terminal title.") |
|
273 | help="Enable auto setting the terminal title.") | |
247 | ), |
|
274 | ), | |
248 |
(('- |
|
275 | (('--no-term-title',), dict( | |
249 |
action='store_false', dest='InteractiveShell.term_title', |
|
276 | action='store_false', dest='InteractiveShell.term_title', | |
250 | help="Disable auto setting the terminal title.") |
|
277 | help="Disable auto setting the terminal title.") | |
251 | ), |
|
278 | ), | |
252 | (('-xmode',), dict( |
|
279 | (('--xmode',), dict( | |
253 |
type=str, dest='InteractiveShell.xmode', |
|
280 | type=str, dest='InteractiveShell.xmode', | |
254 | help="Exception mode ('Plain','Context','Verbose')", |
|
281 | help= | |
|
282 | """Exception reporting mode ('Plain','Context','Verbose'). Plain: | |||
|
283 | similar to python's normal traceback printing. Context: prints 5 lines | |||
|
284 | of context source code around each line in the traceback. Verbose: | |||
|
285 | similar to Context, but additionally prints the variables currently | |||
|
286 | visible where the exception happened (shortening their strings if too | |||
|
287 | long). This can potentially be very slow, if you happen to have a huge | |||
|
288 | data structure whose string representation is complex to compute. | |||
|
289 | Your computer may appear to freeze for a while with cpu usage at 100%%. | |||
|
290 | If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting | |||
|
291 | it more than once). | |||
|
292 | """, | |||
255 | metavar='InteractiveShell.xmode') |
|
293 | metavar='InteractiveShell.xmode') | |
256 | ), |
|
294 | ), | |
257 | (('-ext',), dict( |
|
295 | (('--ext',), dict( | |
258 |
type=str, dest='Global.extra_extension', |
|
296 | type=str, dest='Global.extra_extension', | |
259 | help="The dotted module name of an IPython extension to load.", |
|
297 | help="The dotted module name of an IPython extension to load.", | |
260 | metavar='Global.extra_extension') |
|
298 | metavar='Global.extra_extension') | |
261 | ), |
|
299 | ), | |
262 | (('-c',), dict( |
|
300 | (('-c',), dict( | |
263 |
type=str, dest='Global.code_to_run', |
|
301 | type=str, dest='Global.code_to_run', | |
264 | help="Execute the given command string.", |
|
302 | help="Execute the given command string.", | |
265 | metavar='Global.code_to_run') |
|
303 | metavar='Global.code_to_run') | |
266 | ), |
|
304 | ), | |
267 | (('-i',), dict( |
|
305 | (('-i',), dict( | |
268 |
action='store_true', dest='Global.force_interact', |
|
306 | action='store_true', dest='Global.force_interact', | |
269 | help="If running code from the command line, become interactive afterwards.") |
|
307 | help= | |
270 | ), |
|
308 | "If running code from the command line, become interactive afterwards." | |
271 | (('-wthread',), dict( |
|
309 | ) | |
272 | action='store_true', dest='Global.wthread', default=NoConfigDefault, |
|
310 | ), | |
273 | help="Enable wxPython event loop integration.") |
|
|||
274 | ), |
|
|||
275 | (('-q4thread','-qthread'), dict( |
|
|||
276 | action='store_true', dest='Global.q4thread', default=NoConfigDefault, |
|
|||
277 | help="Enable Qt4 event loop integration. Qt3 is no longer supported.") |
|
|||
278 | ), |
|
|||
279 | (('-gthread',), dict( |
|
|||
280 | action='store_true', dest='Global.gthread', default=NoConfigDefault, |
|
|||
281 | help="Enable GTK event loop integration.") |
|
|||
282 | ), |
|
|||
283 | # # These are only here to get the proper deprecation warnings |
|
|||
284 | (('-pylab',), dict( |
|
|||
285 | action='store_true', dest='Global.pylab', default=NoConfigDefault, |
|
|||
286 | help="Disabled. Pylab has been disabled until matplotlib supports this version of IPython.") |
|
|||
287 | ) |
|
|||
288 | ) |
|
|||
289 |
|
||||
290 |
|
||||
291 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): |
|
|||
292 |
|
311 | |||
293 | arguments = cl_args |
|
312 | # Options to start with GUI control enabled from the beginning | |
|
313 | (('--gui',), dict( | |||
|
314 | type=str, dest='Global.gui', | |||
|
315 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk').", | |||
|
316 | metavar='gui-mode') | |||
|
317 | ), | |||
294 |
|
318 | |||
|
319 | (('--pylab','-pylab'), dict( | |||
|
320 | type=str, dest='Global.pylab', | |||
|
321 | nargs='?', const='auto', metavar='gui-mode', | |||
|
322 | help="Pre-load matplotlib and numpy for interactive use. "+ | |||
|
323 | "If no value is given, the gui backend is matplotlib's, else use "+ | |||
|
324 | "one of: ['tk', 'qt', 'wx', 'gtk'].") | |||
|
325 | ), | |||
|
326 | ||||
|
327 | # Legacy GUI options. Leave them in for backwards compatibility, but the | |||
|
328 | # 'thread' names are really a misnomer now. | |||
|
329 | (('--wthread','-wthread'), dict( | |||
|
330 | action='store_true', dest='Global.wthread', | |||
|
331 | help="Enable wxPython event loop integration "+ | |||
|
332 | "(DEPRECATED, use --gui wx)") | |||
|
333 | ), | |||
|
334 | (('--q4thread','--qthread','-q4thread','-qthread'), dict( | |||
|
335 | action='store_true', dest='Global.q4thread', | |||
|
336 | help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+ | |||
|
337 | "(DEPRECATED, use --gui qt)") | |||
|
338 | ), | |||
|
339 | (('--gthread','-gthread'), dict( | |||
|
340 | action='store_true', dest='Global.gthread', | |||
|
341 | help="Enable GTK event loop integration. "+ | |||
|
342 | "(DEPRECATED, use --gui gtk)") | |||
|
343 | ), | |||
|
344 | ) | |||
295 |
|
345 | |||
296 | _default_config_file_name = 'ipython_config.py' |
|
346 | #----------------------------------------------------------------------------- | |
|
347 | # Main classes and functions | |||
|
348 | #----------------------------------------------------------------------------- | |||
297 |
|
349 | |||
298 | class IPythonApp(Application): |
|
350 | class IPythonApp(Application): | |
299 | name = 'ipython' |
|
351 | name = u'ipython' | |
300 | config_file_name = _default_config_file_name |
|
352 | #: argparse formats better the 'usage' than the 'description' field | |
|
353 | description = None | |||
|
354 | #: usage message printed by argparse. If None, auto-generate | |||
|
355 | usage = usage.cl_usage | |||
|
356 | ||||
|
357 | config_file_name = default_config_file_name | |||
|
358 | ||||
|
359 | cl_arguments = Application.cl_arguments + cl_args | |||
|
360 | ||||
|
361 | # Private and configuration attributes | |||
|
362 | _CrashHandler = crashhandler.IPythonCrashHandler | |||
|
363 | ||||
|
364 | def __init__(self, argv=None, | |||
|
365 | constructor_config=None, override_config=None, | |||
|
366 | **shell_params): | |||
|
367 | """Create a new IPythonApp. | |||
|
368 | ||||
|
369 | See the parent class for details on how configuration is handled. | |||
|
370 | ||||
|
371 | Parameters | |||
|
372 | ---------- | |||
|
373 | argv : optional, list | |||
|
374 | If given, used as the command-line argv environment to read arguments | |||
|
375 | from. | |||
|
376 | ||||
|
377 | constructor_config : optional, Config | |||
|
378 | If given, additional config that is merged last, after internal | |||
|
379 | defaults, command-line and file-based configs. | |||
|
380 | ||||
|
381 | override_config : optional, Config | |||
|
382 | If given, config that overrides all others unconditionally (except | |||
|
383 | for internal defaults, which ensure that all parameters exist). | |||
|
384 | ||||
|
385 | shell_params : optional, dict | |||
|
386 | All other keywords are passed to the :class:`iplib.InteractiveShell` | |||
|
387 | constructor. | |||
|
388 | """ | |||
|
389 | super(IPythonApp, self).__init__(argv, constructor_config, | |||
|
390 | override_config) | |||
|
391 | self.shell_params = shell_params | |||
301 |
|
392 | |||
302 | def create_default_config(self): |
|
393 | def create_default_config(self): | |
303 | super(IPythonApp, self).create_default_config() |
|
394 | super(IPythonApp, self).create_default_config() | |
304 | self.default_config.Global.display_banner = True |
|
395 | # Eliminate multiple lookups | |
|
396 | Global = self.default_config.Global | |||
|
397 | ||||
|
398 | # Set all default values | |||
|
399 | Global.display_banner = True | |||
305 |
|
400 | |||
306 | # If the -c flag is given or a file is given to run at the cmd line |
|
401 | # If the -c flag is given or a file is given to run at the cmd line | |
307 | # like "ipython foo.py", normally we exit without starting the main |
|
402 | # like "ipython foo.py", normally we exit without starting the main | |
308 | # loop. The force_interact config variable allows a user to override |
|
403 | # loop. The force_interact config variable allows a user to override | |
309 | # this and interact. It is also set by the -i cmd line flag, just |
|
404 | # this and interact. It is also set by the -i cmd line flag, just | |
310 | # like Python. |
|
405 | # like Python. | |
311 |
|
|
406 | Global.force_interact = False | |
312 |
|
407 | |||
313 | # By default always interact by starting the IPython mainloop. |
|
408 | # By default always interact by starting the IPython mainloop. | |
314 |
|
|
409 | Global.interact = True | |
315 |
|
||||
316 | # Let the parent class set the default, but each time log_level |
|
|||
317 | # changes from config, we need to update self.log_level as that is |
|
|||
318 | # what updates the actual log level in self.log. |
|
|||
319 | self.default_config.Global.log_level = self.log_level |
|
|||
320 |
|
410 | |||
321 | # No GUI integration by default |
|
411 | # No GUI integration by default | |
322 |
|
|
412 | Global.gui = False | |
323 | self.default_config.Global.q4thread = False |
|
413 | # Pylab off by default | |
324 |
|
|
414 | Global.pylab = False | |
325 |
|
415 | |||
326 | def create_command_line_config(self): |
|
416 | # Deprecated versions of gui support that used threading, we support | |
327 | """Create and return a command line config loader.""" |
|
417 | # them just for bacwards compatibility as an alternate spelling for | |
328 | return IPythonAppCLConfigLoader( |
|
418 | # '--gui X' | |
329 | description=ipython_desc, |
|
419 | Global.qthread = False | |
330 | version=release.version) |
|
420 | Global.q4thread = False | |
331 |
|
421 | Global.wthread = False | ||
332 | def post_load_command_line_config(self): |
|
422 | Global.gthread = False | |
333 | """Do actions after loading cl config.""" |
|
|||
334 | clc = self.command_line_config |
|
|||
335 |
|
||||
336 | # Display the deprecation warnings about threaded shells |
|
|||
337 | if hasattr(clc.Global, 'pylab'): |
|
|||
338 | pylab_warning() |
|
|||
339 | del clc.Global['pylab'] |
|
|||
340 |
|
423 | |||
341 | def load_file_config(self): |
|
424 | def load_file_config(self): | |
342 | if hasattr(self.command_line_config.Global, 'quick'): |
|
425 | if hasattr(self.command_line_config.Global, 'quick'): | |
343 | if self.command_line_config.Global.quick: |
|
426 | if self.command_line_config.Global.quick: | |
344 | self.file_config = Config() |
|
427 | self.file_config = Config() | |
345 | return |
|
428 | return | |
346 | super(IPythonApp, self).load_file_config() |
|
429 | super(IPythonApp, self).load_file_config() | |
347 |
|
430 | |||
348 | def post_load_file_config(self): |
|
431 | def post_load_file_config(self): | |
349 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
432 | if hasattr(self.command_line_config.Global, 'extra_extension'): | |
350 | if not hasattr(self.file_config.Global, 'extensions'): |
|
433 | if not hasattr(self.file_config.Global, 'extensions'): | |
351 | self.file_config.Global.extensions = [] |
|
434 | self.file_config.Global.extensions = [] | |
352 | self.file_config.Global.extensions.append( |
|
435 | self.file_config.Global.extensions.append( | |
353 | self.command_line_config.Global.extra_extension) |
|
436 | self.command_line_config.Global.extra_extension) | |
354 | del self.command_line_config.Global.extra_extension |
|
437 | del self.command_line_config.Global.extra_extension | |
355 |
|
438 | |||
356 | def pre_construct(self): |
|
439 | def pre_construct(self): | |
357 | config = self.master_config |
|
440 | config = self.master_config | |
358 |
|
441 | |||
359 | if hasattr(config.Global, 'classic'): |
|
442 | if hasattr(config.Global, 'classic'): | |
360 | if config.Global.classic: |
|
443 | if config.Global.classic: | |
361 | config.InteractiveShell.cache_size = 0 |
|
444 | config.InteractiveShell.cache_size = 0 | |
362 | config.InteractiveShell.pprint = 0 |
|
445 | config.InteractiveShell.pprint = 0 | |
363 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
446 | config.InteractiveShell.prompt_in1 = '>>> ' | |
364 | config.InteractiveShell.prompt_in2 = '... ' |
|
447 | config.InteractiveShell.prompt_in2 = '... ' | |
365 | config.InteractiveShell.prompt_out = '' |
|
448 | config.InteractiveShell.prompt_out = '' | |
366 | config.InteractiveShell.separate_in = \ |
|
449 | config.InteractiveShell.separate_in = \ | |
367 | config.InteractiveShell.separate_out = \ |
|
450 | config.InteractiveShell.separate_out = \ | |
368 | config.InteractiveShell.separate_out2 = '' |
|
451 | config.InteractiveShell.separate_out2 = '' | |
369 | config.InteractiveShell.colors = 'NoColor' |
|
452 | config.InteractiveShell.colors = 'NoColor' | |
370 | config.InteractiveShell.xmode = 'Plain' |
|
453 | config.InteractiveShell.xmode = 'Plain' | |
371 |
|
454 | |||
372 | if hasattr(config.Global, 'nosep'): |
|
455 | if hasattr(config.Global, 'nosep'): | |
373 | if config.Global.nosep: |
|
456 | if config.Global.nosep: | |
374 | config.InteractiveShell.separate_in = \ |
|
457 | config.InteractiveShell.separate_in = \ | |
375 | config.InteractiveShell.separate_out = \ |
|
458 | config.InteractiveShell.separate_out = \ | |
376 | config.InteractiveShell.separate_out2 = '' |
|
459 | config.InteractiveShell.separate_out2 = '' | |
377 |
|
460 | |||
378 | # if there is code of files to run from the cmd line, don't interact |
|
461 | # if there is code of files to run from the cmd line, don't interact | |
379 | # unless the -i flag (Global.force_interact) is true. |
|
462 | # unless the -i flag (Global.force_interact) is true. | |
380 | code_to_run = config.Global.get('code_to_run','') |
|
463 | code_to_run = config.Global.get('code_to_run','') | |
381 | file_to_run = False |
|
464 | file_to_run = False | |
382 |
if |
|
465 | if self.extra_args and self.extra_args[0]: | |
383 | if self.extra_args[0]: |
|
|||
384 | file_to_run = True |
|
466 | file_to_run = True | |
385 | if file_to_run or code_to_run: |
|
467 | if file_to_run or code_to_run: | |
386 | if not config.Global.force_interact: |
|
468 | if not config.Global.force_interact: | |
387 | config.Global.interact = False |
|
469 | config.Global.interact = False | |
388 |
|
470 | |||
389 | def construct(self): |
|
471 | def construct(self): | |
390 | # I am a little hesitant to put these into InteractiveShell itself. |
|
472 | # I am a little hesitant to put these into InteractiveShell itself. | |
391 | # But that might be the place for them |
|
473 | # But that might be the place for them | |
392 | sys.path.insert(0, '') |
|
474 | sys.path.insert(0, '') | |
393 |
|
475 | |||
394 | # Create an InteractiveShell instance |
|
476 | # Create an InteractiveShell instance | |
395 | self.shell = InteractiveShell( |
|
477 | self.shell = InteractiveShell(None, self.master_config, | |
396 | parent=None, |
|
478 | **self.shell_params ) | |
397 | config=self.master_config |
|
|||
398 | ) |
|
|||
399 |
|
479 | |||
400 | def post_construct(self): |
|
480 | def post_construct(self): | |
401 | """Do actions after construct, but before starting the app.""" |
|
481 | """Do actions after construct, but before starting the app.""" | |
402 | config = self.master_config |
|
482 | config = self.master_config | |
403 |
|
483 | |||
404 | # shell.display_banner should always be False for the terminal |
|
484 | # shell.display_banner should always be False for the terminal | |
405 | # based app, because we call shell.show_banner() by hand below |
|
485 | # based app, because we call shell.show_banner() by hand below | |
406 | # so the banner shows *before* all extension loading stuff. |
|
486 | # so the banner shows *before* all extension loading stuff. | |
407 | self.shell.display_banner = False |
|
487 | self.shell.display_banner = False | |
408 |
|
488 | |||
409 | if config.Global.display_banner and \ |
|
489 | if config.Global.display_banner and \ | |
410 | config.Global.interact: |
|
490 | config.Global.interact: | |
411 | self.shell.show_banner() |
|
491 | self.shell.show_banner() | |
412 |
|
492 | |||
413 | # Make sure there is a space below the banner. |
|
493 | # Make sure there is a space below the banner. | |
414 | if self.log_level <= logging.INFO: print |
|
494 | if self.log_level <= logging.INFO: print | |
415 |
|
495 | |||
416 | # Now a variety of things that happen after the banner is printed. |
|
496 | # Now a variety of things that happen after the banner is printed. | |
417 | self._enable_gui() |
|
497 | self._enable_gui_pylab() | |
418 | self._load_extensions() |
|
498 | self._load_extensions() | |
419 | self._run_exec_lines() |
|
499 | self._run_exec_lines() | |
420 | self._run_exec_files() |
|
500 | self._run_exec_files() | |
421 | self._run_cmd_line_code() |
|
501 | self._run_cmd_line_code() | |
|
502 | self._configure_xmode() | |||
|
503 | ||||
|
504 | def _enable_gui_pylab(self): | |||
|
505 | """Enable GUI event loop integration, taking pylab into account.""" | |||
|
506 | Global = self.master_config.Global | |||
|
507 | ||||
|
508 | # Select which gui to use | |||
|
509 | if Global.gui: | |||
|
510 | gui = Global.gui | |||
|
511 | # The following are deprecated, but there's likely to be a lot of use | |||
|
512 | # of this form out there, so we might as well support it for now. But | |||
|
513 | # the --gui option above takes precedence. | |||
|
514 | elif Global.wthread: | |||
|
515 | gui = inputhook.GUI_WX | |||
|
516 | elif Global.qthread: | |||
|
517 | gui = inputhook.GUI_QT | |||
|
518 | elif Global.gthread: | |||
|
519 | gui = inputhook.GUI_GTK | |||
|
520 | else: | |||
|
521 | gui = None | |||
|
522 | ||||
|
523 | # Using --pylab will also require gui activation, though which toolkit | |||
|
524 | # to use may be chosen automatically based on mpl configuration. | |||
|
525 | if Global.pylab: | |||
|
526 | activate = self.shell.enable_pylab | |||
|
527 | if Global.pylab == 'auto': | |||
|
528 | gui = None | |||
|
529 | else: | |||
|
530 | gui = Global.pylab | |||
|
531 | else: | |||
|
532 | # Enable only GUI integration, no pylab | |||
|
533 | activate = inputhook.enable_gui | |||
422 |
|
534 | |||
423 | def _enable_gui(self): |
|
535 | if gui or Global.pylab: | |
424 | """Enable GUI event loop integration.""" |
|
536 | try: | |
425 | config = self.master_config |
|
537 | self.log.info("Enabling GUI event loop integration, " | |
426 | try: |
|
538 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) | |
427 | # Enable GUI integration |
|
539 | activate(gui) | |
428 | if config.Global.wthread: |
|
540 | except: | |
429 |
self.log. |
|
541 | self.log.warn("Error in enabling GUI event loop integration:") | |
430 | inputhook.enable_wx(app=True) |
|
542 | self.shell.showtraceback() | |
431 | elif config.Global.q4thread: |
|
|||
432 | self.log.info("Enabling Qt4 GUI event loop integration") |
|
|||
433 | inputhook.enable_qt4(app=True) |
|
|||
434 | elif config.Global.gthread: |
|
|||
435 | self.log.info("Enabling GTK GUI event loop integration") |
|
|||
436 | inputhook.enable_gtk(app=True) |
|
|||
437 | except: |
|
|||
438 | self.log.warn("Error in enabling GUI event loop integration:") |
|
|||
439 | self.shell.showtraceback() |
|
|||
440 |
|
543 | |||
441 | def _load_extensions(self): |
|
544 | def _load_extensions(self): | |
442 | """Load all IPython extensions in Global.extensions. |
|
545 | """Load all IPython extensions in Global.extensions. | |
443 |
|
546 | |||
444 | This uses the :meth:`InteractiveShell.load_extensions` to load all |
|
547 | This uses the :meth:`InteractiveShell.load_extensions` to load all | |
445 | the extensions listed in ``self.master_config.Global.extensions``. |
|
548 | the extensions listed in ``self.master_config.Global.extensions``. | |
446 | """ |
|
549 | """ | |
447 | try: |
|
550 | try: | |
448 | if hasattr(self.master_config.Global, 'extensions'): |
|
551 | if hasattr(self.master_config.Global, 'extensions'): | |
449 | self.log.debug("Loading IPython extensions...") |
|
552 | self.log.debug("Loading IPython extensions...") | |
450 | extensions = self.master_config.Global.extensions |
|
553 | extensions = self.master_config.Global.extensions | |
451 | for ext in extensions: |
|
554 | for ext in extensions: | |
452 | try: |
|
555 | try: | |
453 | self.log.info("Loading IPython extension: %s" % ext) |
|
556 | self.log.info("Loading IPython extension: %s" % ext) | |
454 | self.shell.load_extension(ext) |
|
557 | self.shell.load_extension(ext) | |
455 | except: |
|
558 | except: | |
456 | self.log.warn("Error in loading extension: %s" % ext) |
|
559 | self.log.warn("Error in loading extension: %s" % ext) | |
457 | self.shell.showtraceback() |
|
560 | self.shell.showtraceback() | |
458 | except: |
|
561 | except: | |
459 | self.log.warn("Unknown error in loading extensions:") |
|
562 | self.log.warn("Unknown error in loading extensions:") | |
460 | self.shell.showtraceback() |
|
563 | self.shell.showtraceback() | |
461 |
|
564 | |||
462 | def _run_exec_lines(self): |
|
565 | def _run_exec_lines(self): | |
463 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
566 | """Run lines of code in Global.exec_lines in the user's namespace.""" | |
464 | try: |
|
567 | try: | |
465 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
568 | if hasattr(self.master_config.Global, 'exec_lines'): | |
466 | self.log.debug("Running code from Global.exec_lines...") |
|
569 | self.log.debug("Running code from Global.exec_lines...") | |
467 | exec_lines = self.master_config.Global.exec_lines |
|
570 | exec_lines = self.master_config.Global.exec_lines | |
468 | for line in exec_lines: |
|
571 | for line in exec_lines: | |
469 | try: |
|
572 | try: | |
470 | self.log.info("Running code in user namespace: %s" % line) |
|
573 | self.log.info("Running code in user namespace: %s" % line) | |
471 | self.shell.runlines(line) |
|
574 | self.shell.runlines(line) | |
472 | except: |
|
575 | except: | |
473 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
576 | self.log.warn("Error in executing line in user namespace: %s" % line) | |
474 | self.shell.showtraceback() |
|
577 | self.shell.showtraceback() | |
475 | except: |
|
578 | except: | |
476 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
579 | self.log.warn("Unknown error in handling Global.exec_lines:") | |
477 | self.shell.showtraceback() |
|
580 | self.shell.showtraceback() | |
478 |
|
581 | |||
479 | def _exec_file(self, fname): |
|
582 | def _exec_file(self, fname): | |
480 | full_filename = filefind(fname, ['.', self.ipythondir]) |
|
583 | full_filename = filefind(fname, [u'.', self.ipython_dir]) | |
481 | if os.path.isfile(full_filename): |
|
584 | if os.path.isfile(full_filename): | |
482 | if full_filename.endswith('.py'): |
|
585 | if full_filename.endswith(u'.py'): | |
483 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
586 | self.log.info("Running file in user namespace: %s" % full_filename) | |
484 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
587 | self.shell.safe_execfile(full_filename, self.shell.user_ns) | |
485 | elif full_filename.endswith('.ipy'): |
|
588 | elif full_filename.endswith('.ipy'): | |
486 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
589 | self.log.info("Running file in user namespace: %s" % full_filename) | |
487 | self.shell.safe_execfile_ipy(full_filename) |
|
590 | self.shell.safe_execfile_ipy(full_filename) | |
488 | else: |
|
591 | else: | |
489 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) |
|
592 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) | |
490 |
|
593 | |||
491 | def _run_exec_files(self): |
|
594 | def _run_exec_files(self): | |
492 | try: |
|
595 | try: | |
493 | if hasattr(self.master_config.Global, 'exec_files'): |
|
596 | if hasattr(self.master_config.Global, 'exec_files'): | |
494 | self.log.debug("Running files in Global.exec_files...") |
|
597 | self.log.debug("Running files in Global.exec_files...") | |
495 | exec_files = self.master_config.Global.exec_files |
|
598 | exec_files = self.master_config.Global.exec_files | |
496 | for fname in exec_files: |
|
599 | for fname in exec_files: | |
497 | self._exec_file(fname) |
|
600 | self._exec_file(fname) | |
498 | except: |
|
601 | except: | |
499 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
602 | self.log.warn("Unknown error in handling Global.exec_files:") | |
500 | self.shell.showtraceback() |
|
603 | self.shell.showtraceback() | |
501 |
|
604 | |||
502 | def _run_cmd_line_code(self): |
|
605 | def _run_cmd_line_code(self): | |
503 | if hasattr(self.master_config.Global, 'code_to_run'): |
|
606 | if hasattr(self.master_config.Global, 'code_to_run'): | |
504 | line = self.master_config.Global.code_to_run |
|
607 | line = self.master_config.Global.code_to_run | |
505 | try: |
|
608 | try: | |
506 | self.log.info("Running code given at command line (-c): %s" % line) |
|
609 | self.log.info("Running code given at command line (-c): %s" % line) | |
507 | self.shell.runlines(line) |
|
610 | self.shell.runlines(line) | |
508 | except: |
|
611 | except: | |
509 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
612 | self.log.warn("Error in executing line in user namespace: %s" % line) | |
510 | self.shell.showtraceback() |
|
613 | self.shell.showtraceback() | |
511 | return |
|
614 | return | |
512 | # Like Python itself, ignore the second if the first of these is present |
|
615 | # Like Python itself, ignore the second if the first of these is present | |
513 | try: |
|
616 | try: | |
514 | fname = self.extra_args[0] |
|
617 | fname = self.extra_args[0] | |
515 | except: |
|
618 | except: | |
516 | pass |
|
619 | pass | |
517 | else: |
|
620 | else: | |
518 | try: |
|
621 | try: | |
519 | self._exec_file(fname) |
|
622 | self._exec_file(fname) | |
520 | except: |
|
623 | except: | |
521 | self.log.warn("Error in executing file in user namespace: %s" % fname) |
|
624 | self.log.warn("Error in executing file in user namespace: %s" % fname) | |
522 | self.shell.showtraceback() |
|
625 | self.shell.showtraceback() | |
523 |
|
626 | |||
|
627 | def _configure_xmode(self): | |||
|
628 | # XXX - shouldn't this be read from the config? I'm still a little | |||
|
629 | # lost with all the details of handling the new config guys... | |||
|
630 | self.shell.InteractiveTB.set_mode(mode=self.shell.xmode) | |||
|
631 | ||||
524 | def start_app(self): |
|
632 | def start_app(self): | |
525 | if self.master_config.Global.interact: |
|
633 | if self.master_config.Global.interact: | |
526 | self.log.debug("Starting IPython's mainloop...") |
|
634 | self.log.debug("Starting IPython's mainloop...") | |
527 | self.shell.mainloop() |
|
635 | self.shell.mainloop() | |
|
636 | else: | |||
|
637 | self.log.debug("IPython not interactive, start_app is no-op...") | |||
528 |
|
638 | |||
529 |
|
639 | |||
530 | def load_default_config(ipythondir=None): |
|
640 | def load_default_config(ipython_dir=None): | |
531 | """Load the default config file from the default ipythondir. |
|
641 | """Load the default config file from the default ipython_dir. | |
532 |
|
642 | |||
533 | This is useful for embedded shells. |
|
643 | This is useful for embedded shells. | |
534 | """ |
|
644 | """ | |
535 | if ipythondir is None: |
|
645 | if ipython_dir is None: | |
536 | ipythondir = get_ipython_dir() |
|
646 | ipython_dir = get_ipython_dir() | |
537 |
cl = PyFileConfigLoader( |
|
647 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) | |
538 | config = cl.load_config() |
|
648 | config = cl.load_config() | |
539 | return config |
|
649 | return config | |
540 |
|
650 | |||
541 |
|
651 | |||
542 | def launch_new_instance(): |
|
652 | def launch_new_instance(): | |
543 | """Create a run a full blown IPython instance""" |
|
653 | """Create and run a full blown IPython instance""" | |
544 | app = IPythonApp() |
|
654 | app = IPythonApp() | |
545 | app.start() |
|
655 | app.start() | |
546 |
|
@@ -1,2470 +1,2527 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Main IPython Component |
|
3 | Main IPython Component | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | # Copyright (C) 2008-2009 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | from __future__ import with_statement |
|
19 | from __future__ import with_statement | |
|
20 | from __future__ import absolute_import | |||
20 |
|
21 | |||
21 | import __builtin__ |
|
22 | import __builtin__ | |
22 | import StringIO |
|
23 | import StringIO | |
23 | import bdb |
|
24 | import bdb | |
24 | import codeop |
|
25 | import codeop | |
25 | import exceptions |
|
26 | import exceptions | |
26 | import new |
|
27 | import new | |
27 | import os |
|
28 | import os | |
28 | import re |
|
29 | import re | |
29 | import string |
|
30 | import string | |
30 | import sys |
|
31 | import sys | |
31 | import tempfile |
|
32 | import tempfile | |
32 | from contextlib import nested |
|
33 | from contextlib import nested | |
33 |
|
34 | |||
34 | from IPython.core import ultratb |
|
|||
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import shadowns |
|
|||
37 | from IPython.core import history as ipcorehist |
|
36 | from IPython.core import history as ipcorehist | |
38 | from IPython.core import prefilter |
|
37 | from IPython.core import prefilter | |
|
38 | from IPython.core import shadowns | |||
|
39 | from IPython.core import ultratb | |||
39 | from IPython.core.alias import AliasManager |
|
40 | from IPython.core.alias import AliasManager | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
41 | from IPython.core.builtin_trap import BuiltinTrap | |
|
42 | from IPython.core.component import Component | |||
41 | from IPython.core.display_trap import DisplayTrap |
|
43 | from IPython.core.display_trap import DisplayTrap | |
|
44 | from IPython.core.error import TryNext, UsageError | |||
42 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
45 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
43 | from IPython.core.logger import Logger |
|
46 | from IPython.core.logger import Logger | |
44 | from IPython.core.magic import Magic |
|
47 | from IPython.core.magic import Magic | |
45 | from IPython.core.prompts import CachedOutput |
|
|||
46 | from IPython.core.prefilter import PrefilterManager |
|
48 | from IPython.core.prefilter import PrefilterManager | |
47 |
from IPython.core. |
|
49 | from IPython.core.prompts import CachedOutput | |
|
50 | from IPython.core.pylabtools import pylab_activate | |||
48 | from IPython.core.usage import interactive_usage, default_banner |
|
51 | from IPython.core.usage import interactive_usage, default_banner | |
49 | from IPython.core.error import TryNext, UsageError |
|
|||
50 |
|
||||
51 | from IPython.utils import pickleshare |
|
|||
52 | from IPython.external.Itpl import ItplNS |
|
52 | from IPython.external.Itpl import ItplNS | |
|
53 | from IPython.lib.inputhook import enable_gui | |||
53 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
54 | from IPython.lib.backgroundjobs import BackgroundJobManager | |
54 | from IPython.utils.ipstruct import Struct |
|
|||
55 | from IPython.utils import PyColorize |
|
55 | from IPython.utils import PyColorize | |
56 |
from IPython.utils |
|
56 | from IPython.utils import pickleshare | |
57 | from IPython.utils.genutils import get_ipython_dir |
|
57 | from IPython.utils.genutils import get_ipython_dir | |
|
58 | from IPython.utils.ipstruct import Struct | |||
58 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
59 | from IPython.utils.platutils import toggle_set_term_title, set_term_title | |
59 | from IPython.utils.strdispatch import StrDispatch |
|
60 | from IPython.utils.strdispatch import StrDispatch | |
60 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
61 | from IPython.utils.syspathcontext import prepended_to_syspath | |
61 |
|
62 | |||
|
63 | # XXX - need to clean up this import * line | |||
|
64 | from IPython.utils.genutils import * | |||
|
65 | ||||
62 | # from IPython.utils import growl |
|
66 | # from IPython.utils import growl | |
63 | # growl.start("IPython") |
|
67 | # growl.start("IPython") | |
64 |
|
68 | |||
65 | from IPython.utils.traitlets import ( |
|
69 | from IPython.utils.traitlets import ( | |
66 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
70 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode | |
67 | ) |
|
71 | ) | |
68 |
|
72 | |||
69 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
70 | # Globals |
|
74 | # Globals | |
71 | #----------------------------------------------------------------------------- |
|
75 | #----------------------------------------------------------------------------- | |
72 |
|
76 | |||
73 |
|
||||
74 | # store the builtin raw_input globally, and use this always, in case user code |
|
77 | # store the builtin raw_input globally, and use this always, in case user code | |
75 | # overwrites it (like wx.py.PyShell does) |
|
78 | # overwrites it (like wx.py.PyShell does) | |
76 | raw_input_original = raw_input |
|
79 | raw_input_original = raw_input | |
77 |
|
80 | |||
78 | # compiled regexps for autoindent management |
|
81 | # compiled regexps for autoindent management | |
79 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
80 |
|
83 | |||
81 |
|
||||
82 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
83 | # Utilities |
|
85 | # Utilities | |
84 | #----------------------------------------------------------------------------- |
|
86 | #----------------------------------------------------------------------------- | |
85 |
|
87 | |||
86 |
|
||||
87 | ini_spaces_re = re.compile(r'^(\s+)') |
|
88 | ini_spaces_re = re.compile(r'^(\s+)') | |
88 |
|
89 | |||
89 |
|
90 | |||
90 | def num_ini_spaces(strng): |
|
91 | def num_ini_spaces(strng): | |
91 | """Return the number of initial spaces in a string""" |
|
92 | """Return the number of initial spaces in a string""" | |
92 |
|
93 | |||
93 | ini_spaces = ini_spaces_re.match(strng) |
|
94 | ini_spaces = ini_spaces_re.match(strng) | |
94 | if ini_spaces: |
|
95 | if ini_spaces: | |
95 | return ini_spaces.end() |
|
96 | return ini_spaces.end() | |
96 | else: |
|
97 | else: | |
97 | return 0 |
|
98 | return 0 | |
98 |
|
99 | |||
99 |
|
100 | |||
100 | def softspace(file, newvalue): |
|
101 | def softspace(file, newvalue): | |
101 | """Copied from code.py, to remove the dependency""" |
|
102 | """Copied from code.py, to remove the dependency""" | |
102 |
|
103 | |||
103 | oldvalue = 0 |
|
104 | oldvalue = 0 | |
104 | try: |
|
105 | try: | |
105 | oldvalue = file.softspace |
|
106 | oldvalue = file.softspace | |
106 | except AttributeError: |
|
107 | except AttributeError: | |
107 | pass |
|
108 | pass | |
108 | try: |
|
109 | try: | |
109 | file.softspace = newvalue |
|
110 | file.softspace = newvalue | |
110 | except (AttributeError, TypeError): |
|
111 | except (AttributeError, TypeError): | |
111 | # "attribute-less object" or "read-only attributes" |
|
112 | # "attribute-less object" or "read-only attributes" | |
112 | pass |
|
113 | pass | |
113 | return oldvalue |
|
114 | return oldvalue | |
114 |
|
115 | |||
115 |
|
116 | |||
|
117 | def no_op(*a, **kw): pass | |||
|
118 | ||||
116 | class SpaceInInput(exceptions.Exception): pass |
|
119 | class SpaceInInput(exceptions.Exception): pass | |
117 |
|
120 | |||
118 | class Bunch: pass |
|
121 | class Bunch: pass | |
119 |
|
122 | |||
120 | class InputList(list): |
|
123 | class InputList(list): | |
121 | """Class to store user input. |
|
124 | """Class to store user input. | |
122 |
|
125 | |||
123 | It's basically a list, but slices return a string instead of a list, thus |
|
126 | It's basically a list, but slices return a string instead of a list, thus | |
124 | allowing things like (assuming 'In' is an instance): |
|
127 | allowing things like (assuming 'In' is an instance): | |
125 |
|
128 | |||
126 | exec In[4:7] |
|
129 | exec In[4:7] | |
127 |
|
130 | |||
128 | or |
|
131 | or | |
129 |
|
132 | |||
130 | exec In[5:9] + In[14] + In[21:25]""" |
|
133 | exec In[5:9] + In[14] + In[21:25]""" | |
131 |
|
134 | |||
132 | def __getslice__(self,i,j): |
|
135 | def __getslice__(self,i,j): | |
133 | return ''.join(list.__getslice__(self,i,j)) |
|
136 | return ''.join(list.__getslice__(self,i,j)) | |
134 |
|
137 | |||
135 |
|
138 | |||
136 | class SyntaxTB(ultratb.ListTB): |
|
139 | class SyntaxTB(ultratb.ListTB): | |
137 | """Extension which holds some state: the last exception value""" |
|
140 | """Extension which holds some state: the last exception value""" | |
138 |
|
141 | |||
139 | def __init__(self,color_scheme = 'NoColor'): |
|
142 | def __init__(self,color_scheme = 'NoColor'): | |
140 | ultratb.ListTB.__init__(self,color_scheme) |
|
143 | ultratb.ListTB.__init__(self,color_scheme) | |
141 | self.last_syntax_error = None |
|
144 | self.last_syntax_error = None | |
142 |
|
145 | |||
143 | def __call__(self, etype, value, elist): |
|
146 | def __call__(self, etype, value, elist): | |
144 | self.last_syntax_error = value |
|
147 | self.last_syntax_error = value | |
145 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
148 | ultratb.ListTB.__call__(self,etype,value,elist) | |
146 |
|
149 | |||
147 | def clear_err_state(self): |
|
150 | def clear_err_state(self): | |
148 | """Return the current error state and clear it""" |
|
151 | """Return the current error state and clear it""" | |
149 | e = self.last_syntax_error |
|
152 | e = self.last_syntax_error | |
150 | self.last_syntax_error = None |
|
153 | self.last_syntax_error = None | |
151 | return e |
|
154 | return e | |
152 |
|
155 | |||
153 |
|
156 | |||
154 | def get_default_editor(): |
|
157 | def get_default_editor(): | |
155 | try: |
|
158 | try: | |
156 | ed = os.environ['EDITOR'] |
|
159 | ed = os.environ['EDITOR'] | |
157 | except KeyError: |
|
160 | except KeyError: | |
158 | if os.name == 'posix': |
|
161 | if os.name == 'posix': | |
159 | ed = 'vi' # the only one guaranteed to be there! |
|
162 | ed = 'vi' # the only one guaranteed to be there! | |
160 | else: |
|
163 | else: | |
161 | ed = 'notepad' # same in Windows! |
|
164 | ed = 'notepad' # same in Windows! | |
162 | return ed |
|
165 | return ed | |
163 |
|
166 | |||
164 |
|
167 | |||
|
168 | def get_default_colors(): | |||
|
169 | if sys.platform=='darwin': | |||
|
170 | return "LightBG" | |||
|
171 | elif os.name=='nt': | |||
|
172 | return 'Linux' | |||
|
173 | else: | |||
|
174 | return 'Linux' | |||
|
175 | ||||
|
176 | ||||
165 | class SeparateStr(Str): |
|
177 | class SeparateStr(Str): | |
166 | """A Str subclass to validate separate_in, separate_out, etc. |
|
178 | """A Str subclass to validate separate_in, separate_out, etc. | |
167 |
|
179 | |||
168 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
180 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
169 | """ |
|
181 | """ | |
170 |
|
182 | |||
171 | def validate(self, obj, value): |
|
183 | def validate(self, obj, value): | |
172 | if value == '0': value = '' |
|
184 | if value == '0': value = '' | |
173 | value = value.replace('\\n','\n') |
|
185 | value = value.replace('\\n','\n') | |
174 | return super(SeparateStr, self).validate(obj, value) |
|
186 | return super(SeparateStr, self).validate(obj, value) | |
175 |
|
187 | |||
176 |
|
188 | |||
|
189 | def make_user_namespaces(user_ns=None, user_global_ns=None): | |||
|
190 | """Return a valid local and global user interactive namespaces. | |||
|
191 | ||||
|
192 | This builds a dict with the minimal information needed to operate as a | |||
|
193 | valid IPython user namespace, which you can pass to the various | |||
|
194 | embedding classes in ipython. The default implementation returns the | |||
|
195 | same dict for both the locals and the globals to allow functions to | |||
|
196 | refer to variables in the namespace. Customized implementations can | |||
|
197 | return different dicts. The locals dictionary can actually be anything | |||
|
198 | following the basic mapping protocol of a dict, but the globals dict | |||
|
199 | must be a true dict, not even a subclass. It is recommended that any | |||
|
200 | custom object for the locals namespace synchronize with the globals | |||
|
201 | dict somehow. | |||
|
202 | ||||
|
203 | Raises TypeError if the provided globals namespace is not a true dict. | |||
|
204 | ||||
|
205 | Parameters | |||
|
206 | ---------- | |||
|
207 | user_ns : dict-like, optional | |||
|
208 | The current user namespace. The items in this namespace should | |||
|
209 | be included in the output. If None, an appropriate blank | |||
|
210 | namespace should be created. | |||
|
211 | user_global_ns : dict, optional | |||
|
212 | The current user global namespace. The items in this namespace | |||
|
213 | should be included in the output. If None, an appropriate | |||
|
214 | blank namespace should be created. | |||
|
215 | ||||
|
216 | Returns | |||
|
217 | ------- | |||
|
218 | A pair of dictionary-like object to be used as the local namespace | |||
|
219 | of the interpreter and a dict to be used as the global namespace. | |||
|
220 | """ | |||
|
221 | ||||
|
222 | if user_ns is None: | |||
|
223 | # Set __name__ to __main__ to better match the behavior of the | |||
|
224 | # normal interpreter. | |||
|
225 | user_ns = {'__name__' :'__main__', | |||
|
226 | '__builtins__' : __builtin__, | |||
|
227 | } | |||
|
228 | else: | |||
|
229 | user_ns.setdefault('__name__','__main__') | |||
|
230 | user_ns.setdefault('__builtins__',__builtin__) | |||
|
231 | ||||
|
232 | if user_global_ns is None: | |||
|
233 | user_global_ns = user_ns | |||
|
234 | if type(user_global_ns) is not dict: | |||
|
235 | raise TypeError("user_global_ns must be a true dict; got %r" | |||
|
236 | % type(user_global_ns)) | |||
|
237 | ||||
|
238 | return user_ns, user_global_ns | |||
|
239 | ||||
177 | #----------------------------------------------------------------------------- |
|
240 | #----------------------------------------------------------------------------- | |
178 | # Main IPython class |
|
241 | # Main IPython class | |
179 | #----------------------------------------------------------------------------- |
|
242 | #----------------------------------------------------------------------------- | |
180 |
|
243 | |||
181 |
|
244 | |||
182 | class InteractiveShell(Component, Magic): |
|
245 | class InteractiveShell(Component, Magic): | |
183 | """An enhanced, interactive shell for Python.""" |
|
246 | """An enhanced, interactive shell for Python.""" | |
184 |
|
247 | |||
185 | autocall = Enum((0,1,2), config=True) |
|
248 | autocall = Enum((0,1,2), default_value=1, config=True) | |
186 | autoedit_syntax = CBool(False, config=True) |
|
249 | autoedit_syntax = CBool(False, config=True) | |
187 | autoindent = CBool(True, config=True) |
|
250 | autoindent = CBool(True, config=True) | |
188 | automagic = CBool(True, config=True) |
|
251 | automagic = CBool(True, config=True) | |
189 | banner = Str('') |
|
252 | banner = Str('') | |
190 | banner1 = Str(default_banner, config=True) |
|
253 | banner1 = Str(default_banner, config=True) | |
191 | banner2 = Str('', config=True) |
|
254 | banner2 = Str('', config=True) | |
192 | cache_size = Int(1000, config=True) |
|
255 | cache_size = Int(1000, config=True) | |
193 | color_info = CBool(True, config=True) |
|
256 | color_info = CBool(True, config=True) | |
194 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
195 |
default_value= |
|
258 | default_value=get_default_colors(), config=True) | |
196 | confirm_exit = CBool(True, config=True) |
|
259 | confirm_exit = CBool(True, config=True) | |
197 | debug = CBool(False, config=True) |
|
260 | debug = CBool(False, config=True) | |
198 | deep_reload = CBool(False, config=True) |
|
261 | deep_reload = CBool(False, config=True) | |
199 | # This display_banner only controls whether or not self.show_banner() |
|
262 | # This display_banner only controls whether or not self.show_banner() | |
200 | # is called when mainloop/interact are called. The default is False |
|
263 | # is called when mainloop/interact are called. The default is False | |
201 | # because for the terminal based application, the banner behavior |
|
264 | # because for the terminal based application, the banner behavior | |
202 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
265 | # is controlled by Global.display_banner, which IPythonApp looks at | |
203 | # to determine if *it* should call show_banner() by hand or not. |
|
266 | # to determine if *it* should call show_banner() by hand or not. | |
204 | display_banner = CBool(False) # This isn't configurable! |
|
267 | display_banner = CBool(False) # This isn't configurable! | |
205 | embedded = CBool(False) |
|
268 | embedded = CBool(False) | |
206 | embedded_active = CBool(False) |
|
269 | embedded_active = CBool(False) | |
207 | editor = Str(get_default_editor(), config=True) |
|
270 | editor = Str(get_default_editor(), config=True) | |
208 | filename = Str("<ipython console>") |
|
271 | filename = Str("<ipython console>") | |
209 | ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
272 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
210 | logstart = CBool(False, config=True) |
|
273 | logstart = CBool(False, config=True) | |
211 | logfile = Str('', config=True) |
|
274 | logfile = Str('', config=True) | |
212 | logappend = Str('', config=True) |
|
275 | logappend = Str('', config=True) | |
213 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
276 | object_info_string_level = Enum((0,1,2), default_value=0, | |
214 | config=True) |
|
277 | config=True) | |
215 | pager = Str('less', config=True) |
|
278 | pager = Str('less', config=True) | |
216 | pdb = CBool(False, config=True) |
|
279 | pdb = CBool(False, config=True) | |
217 | pprint = CBool(True, config=True) |
|
280 | pprint = CBool(True, config=True) | |
218 | profile = Str('', config=True) |
|
281 | profile = Str('', config=True) | |
219 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
282 | prompt_in1 = Str('In [\\#]: ', config=True) | |
220 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
283 | prompt_in2 = Str(' .\\D.: ', config=True) | |
221 | prompt_out = Str('Out[\\#]: ', config=True) |
|
284 | prompt_out = Str('Out[\\#]: ', config=True) | |
222 | prompts_pad_left = CBool(True, config=True) |
|
285 | prompts_pad_left = CBool(True, config=True) | |
223 | quiet = CBool(False, config=True) |
|
286 | quiet = CBool(False, config=True) | |
224 |
|
287 | |||
225 | readline_use = CBool(True, config=True) |
|
288 | readline_use = CBool(True, config=True) | |
226 | readline_merge_completions = CBool(True, config=True) |
|
289 | readline_merge_completions = CBool(True, config=True) | |
227 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
290 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
228 | readline_remove_delims = Str('-/~', config=True) |
|
291 | readline_remove_delims = Str('-/~', config=True) | |
229 | readline_parse_and_bind = List([ |
|
292 | readline_parse_and_bind = List([ | |
230 | 'tab: complete', |
|
293 | 'tab: complete', | |
231 | '"\C-l": possible-completions', |
|
294 | '"\C-l": possible-completions', | |
232 | 'set show-all-if-ambiguous on', |
|
295 | 'set show-all-if-ambiguous on', | |
233 | '"\C-o": tab-insert', |
|
296 | '"\C-o": tab-insert', | |
234 | '"\M-i": " "', |
|
297 | '"\M-i": " "', | |
235 | '"\M-o": "\d\d\d\d"', |
|
298 | '"\M-o": "\d\d\d\d"', | |
236 | '"\M-I": "\d\d\d\d"', |
|
299 | '"\M-I": "\d\d\d\d"', | |
237 | '"\C-r": reverse-search-history', |
|
300 | '"\C-r": reverse-search-history', | |
238 | '"\C-s": forward-search-history', |
|
301 | '"\C-s": forward-search-history', | |
239 | '"\C-p": history-search-backward', |
|
302 | '"\C-p": history-search-backward', | |
240 | '"\C-n": history-search-forward', |
|
303 | '"\C-n": history-search-forward', | |
241 | '"\e[A": history-search-backward', |
|
304 | '"\e[A": history-search-backward', | |
242 | '"\e[B": history-search-forward', |
|
305 | '"\e[B": history-search-forward', | |
243 | '"\C-k": kill-line', |
|
306 | '"\C-k": kill-line', | |
244 | '"\C-u": unix-line-discard', |
|
307 | '"\C-u": unix-line-discard', | |
245 | ], allow_none=False, config=True) |
|
308 | ], allow_none=False, config=True) | |
246 |
|
309 | |||
247 | screen_length = Int(0, config=True) |
|
310 | screen_length = Int(0, config=True) | |
248 |
|
311 | |||
249 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
312 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
250 | separate_in = SeparateStr('\n', config=True) |
|
313 | separate_in = SeparateStr('\n', config=True) | |
251 | separate_out = SeparateStr('', config=True) |
|
314 | separate_out = SeparateStr('', config=True) | |
252 | separate_out2 = SeparateStr('', config=True) |
|
315 | separate_out2 = SeparateStr('', config=True) | |
253 |
|
316 | |||
254 | system_header = Str('IPython system call: ', config=True) |
|
317 | system_header = Str('IPython system call: ', config=True) | |
255 | system_verbose = CBool(False, config=True) |
|
318 | system_verbose = CBool(False, config=True) | |
256 | term_title = CBool(False, config=True) |
|
319 | term_title = CBool(False, config=True) | |
257 | wildcards_case_sensitive = CBool(True, config=True) |
|
320 | wildcards_case_sensitive = CBool(True, config=True) | |
258 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
321 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
259 | default_value='Context', config=True) |
|
322 | default_value='Context', config=True) | |
260 |
|
323 | |||
261 | autoexec = List(allow_none=False) |
|
324 | autoexec = List(allow_none=False) | |
262 |
|
325 | |||
263 | # class attribute to indicate whether the class supports threads or not. |
|
326 | # class attribute to indicate whether the class supports threads or not. | |
264 | # Subclasses with thread support should override this as needed. |
|
327 | # Subclasses with thread support should override this as needed. | |
265 | isthreaded = False |
|
328 | isthreaded = False | |
266 |
|
329 | |||
267 | def __init__(self, parent=None, config=None, ipythondir=None, usage=None, |
|
330 | def __init__(self, parent=None, config=None, ipython_dir=None, usage=None, | |
268 | user_ns=None, user_global_ns=None, |
|
331 | user_ns=None, user_global_ns=None, | |
269 | banner1=None, banner2=None, display_banner=None, |
|
332 | banner1=None, banner2=None, display_banner=None, | |
270 | custom_exceptions=((),None)): |
|
333 | custom_exceptions=((),None)): | |
271 |
|
334 | |||
272 | # This is where traits with a config_key argument are updated |
|
335 | # This is where traits with a config_key argument are updated | |
273 | # from the values on config. |
|
336 | # from the values on config. | |
274 | super(InteractiveShell, self).__init__(parent, config=config) |
|
337 | super(InteractiveShell, self).__init__(parent, config=config) | |
275 |
|
338 | |||
276 | # These are relatively independent and stateless |
|
339 | # These are relatively independent and stateless | |
277 | self.init_ipythondir(ipythondir) |
|
340 | self.init_ipython_dir(ipython_dir) | |
278 | self.init_instance_attrs() |
|
341 | self.init_instance_attrs() | |
279 | self.init_term_title() |
|
342 | self.init_term_title() | |
280 | self.init_usage(usage) |
|
343 | self.init_usage(usage) | |
281 | self.init_banner(banner1, banner2, display_banner) |
|
344 | self.init_banner(banner1, banner2, display_banner) | |
282 |
|
345 | |||
283 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
346 | # Create namespaces (user_ns, user_global_ns, etc.) | |
284 | self.init_create_namespaces(user_ns, user_global_ns) |
|
347 | self.init_create_namespaces(user_ns, user_global_ns) | |
285 | # This has to be done after init_create_namespaces because it uses |
|
348 | # This has to be done after init_create_namespaces because it uses | |
286 | # something in self.user_ns, but before init_sys_modules, which |
|
349 | # something in self.user_ns, but before init_sys_modules, which | |
287 | # is the first thing to modify sys. |
|
350 | # is the first thing to modify sys. | |
288 | self.save_sys_module_state() |
|
351 | self.save_sys_module_state() | |
289 | self.init_sys_modules() |
|
352 | self.init_sys_modules() | |
290 |
|
353 | |||
291 | self.init_history() |
|
354 | self.init_history() | |
292 | self.init_encoding() |
|
355 | self.init_encoding() | |
293 | self.init_prefilter() |
|
356 | self.init_prefilter() | |
294 |
|
357 | |||
295 | Magic.__init__(self, self) |
|
358 | Magic.__init__(self, self) | |
296 |
|
359 | |||
297 | self.init_syntax_highlighting() |
|
360 | self.init_syntax_highlighting() | |
298 | self.init_hooks() |
|
361 | self.init_hooks() | |
299 | self.init_pushd_popd_magic() |
|
362 | self.init_pushd_popd_magic() | |
300 | self.init_traceback_handlers(custom_exceptions) |
|
363 | self.init_traceback_handlers(custom_exceptions) | |
301 | self.init_user_ns() |
|
364 | self.init_user_ns() | |
302 | self.init_logger() |
|
365 | self.init_logger() | |
303 | self.init_alias() |
|
366 | self.init_alias() | |
304 | self.init_builtins() |
|
367 | self.init_builtins() | |
305 |
|
368 | |||
306 | # pre_config_initialization |
|
369 | # pre_config_initialization | |
307 | self.init_shadow_hist() |
|
370 | self.init_shadow_hist() | |
308 |
|
371 | |||
309 | # The next section should contain averything that was in ipmaker. |
|
372 | # The next section should contain averything that was in ipmaker. | |
310 | self.init_logstart() |
|
373 | self.init_logstart() | |
311 |
|
374 | |||
312 | # The following was in post_config_initialization |
|
375 | # The following was in post_config_initialization | |
313 | self.init_inspector() |
|
376 | self.init_inspector() | |
314 | self.init_readline() |
|
377 | self.init_readline() | |
315 | self.init_prompts() |
|
378 | self.init_prompts() | |
316 | self.init_displayhook() |
|
379 | self.init_displayhook() | |
317 | self.init_reload_doctest() |
|
380 | self.init_reload_doctest() | |
318 | self.init_magics() |
|
381 | self.init_magics() | |
319 | self.init_pdb() |
|
382 | self.init_pdb() | |
320 | self.hooks.late_startup_hook() |
|
383 | self.hooks.late_startup_hook() | |
321 |
|
384 | |||
322 | def get_ipython(self): |
|
385 | def get_ipython(self): | |
|
386 | """Return the currently running IPython instance.""" | |||
323 | return self |
|
387 | return self | |
324 |
|
388 | |||
325 | #------------------------------------------------------------------------- |
|
389 | #------------------------------------------------------------------------- | |
326 | # Trait changed handlers |
|
390 | # Trait changed handlers | |
327 | #------------------------------------------------------------------------- |
|
391 | #------------------------------------------------------------------------- | |
328 |
|
392 | |||
329 | def _banner1_changed(self): |
|
393 | def _banner1_changed(self): | |
330 | self.compute_banner() |
|
394 | self.compute_banner() | |
331 |
|
395 | |||
332 | def _banner2_changed(self): |
|
396 | def _banner2_changed(self): | |
333 | self.compute_banner() |
|
397 | self.compute_banner() | |
334 |
|
398 | |||
335 | def _ipythondir_changed(self, name, new): |
|
399 | def _ipython_dir_changed(self, name, new): | |
336 | if not os.path.isdir(new): |
|
400 | if not os.path.isdir(new): | |
337 | os.makedirs(new, mode = 0777) |
|
401 | os.makedirs(new, mode = 0777) | |
338 | if not os.path.isdir(self.ipython_extension_dir): |
|
402 | if not os.path.isdir(self.ipython_extension_dir): | |
339 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
403 | os.makedirs(self.ipython_extension_dir, mode = 0777) | |
340 |
|
404 | |||
341 | @property |
|
405 | @property | |
342 | def ipython_extension_dir(self): |
|
406 | def ipython_extension_dir(self): | |
343 | return os.path.join(self.ipythondir, 'extensions') |
|
407 | return os.path.join(self.ipython_dir, 'extensions') | |
344 |
|
408 | |||
345 | @property |
|
409 | @property | |
346 | def usable_screen_length(self): |
|
410 | def usable_screen_length(self): | |
347 | if self.screen_length == 0: |
|
411 | if self.screen_length == 0: | |
348 | return 0 |
|
412 | return 0 | |
349 | else: |
|
413 | else: | |
350 | num_lines_bot = self.separate_in.count('\n')+1 |
|
414 | num_lines_bot = self.separate_in.count('\n')+1 | |
351 | return self.screen_length - num_lines_bot |
|
415 | return self.screen_length - num_lines_bot | |
352 |
|
416 | |||
353 | def _term_title_changed(self, name, new_value): |
|
417 | def _term_title_changed(self, name, new_value): | |
354 | self.init_term_title() |
|
418 | self.init_term_title() | |
355 |
|
419 | |||
356 | def set_autoindent(self,value=None): |
|
420 | def set_autoindent(self,value=None): | |
357 | """Set the autoindent flag, checking for readline support. |
|
421 | """Set the autoindent flag, checking for readline support. | |
358 |
|
422 | |||
359 | If called with no arguments, it acts as a toggle.""" |
|
423 | If called with no arguments, it acts as a toggle.""" | |
360 |
|
424 | |||
361 | if not self.has_readline: |
|
425 | if not self.has_readline: | |
362 | if os.name == 'posix': |
|
426 | if os.name == 'posix': | |
363 | warn("The auto-indent feature requires the readline library") |
|
427 | warn("The auto-indent feature requires the readline library") | |
364 | self.autoindent = 0 |
|
428 | self.autoindent = 0 | |
365 | return |
|
429 | return | |
366 | if value is None: |
|
430 | if value is None: | |
367 | self.autoindent = not self.autoindent |
|
431 | self.autoindent = not self.autoindent | |
368 | else: |
|
432 | else: | |
369 | self.autoindent = value |
|
433 | self.autoindent = value | |
370 |
|
434 | |||
371 | #------------------------------------------------------------------------- |
|
435 | #------------------------------------------------------------------------- | |
372 | # init_* methods called by __init__ |
|
436 | # init_* methods called by __init__ | |
373 | #------------------------------------------------------------------------- |
|
437 | #------------------------------------------------------------------------- | |
374 |
|
438 | |||
375 | def init_ipythondir(self, ipythondir): |
|
439 | def init_ipython_dir(self, ipython_dir): | |
376 | if ipythondir is not None: |
|
440 | if ipython_dir is not None: | |
377 | self.ipythondir = ipythondir |
|
441 | self.ipython_dir = ipython_dir | |
378 | self.config.Global.ipythondir = self.ipythondir |
|
442 | self.config.Global.ipython_dir = self.ipython_dir | |
379 | return |
|
443 | return | |
380 |
|
444 | |||
381 | if hasattr(self.config.Global, 'ipythondir'): |
|
445 | if hasattr(self.config.Global, 'ipython_dir'): | |
382 | self.ipythondir = self.config.Global.ipythondir |
|
446 | self.ipython_dir = self.config.Global.ipython_dir | |
383 | else: |
|
447 | else: | |
384 | self.ipythondir = get_ipython_dir() |
|
448 | self.ipython_dir = get_ipython_dir() | |
385 |
|
449 | |||
386 | # All children can just read this |
|
450 | # All children can just read this | |
387 | self.config.Global.ipythondir = self.ipythondir |
|
451 | self.config.Global.ipython_dir = self.ipython_dir | |
388 |
|
452 | |||
389 | def init_instance_attrs(self): |
|
453 | def init_instance_attrs(self): | |
390 | self.jobs = BackgroundJobManager() |
|
454 | self.jobs = BackgroundJobManager() | |
391 | self.more = False |
|
455 | self.more = False | |
392 |
|
456 | |||
393 | # command compiler |
|
457 | # command compiler | |
394 | self.compile = codeop.CommandCompiler() |
|
458 | self.compile = codeop.CommandCompiler() | |
395 |
|
459 | |||
396 | # User input buffer |
|
460 | # User input buffer | |
397 | self.buffer = [] |
|
461 | self.buffer = [] | |
398 |
|
462 | |||
399 | # Make an empty namespace, which extension writers can rely on both |
|
463 | # Make an empty namespace, which extension writers can rely on both | |
400 | # existing and NEVER being used by ipython itself. This gives them a |
|
464 | # existing and NEVER being used by ipython itself. This gives them a | |
401 | # convenient location for storing additional information and state |
|
465 | # convenient location for storing additional information and state | |
402 | # their extensions may require, without fear of collisions with other |
|
466 | # their extensions may require, without fear of collisions with other | |
403 | # ipython names that may develop later. |
|
467 | # ipython names that may develop later. | |
404 | self.meta = Struct() |
|
468 | self.meta = Struct() | |
405 |
|
469 | |||
406 | # Object variable to store code object waiting execution. This is |
|
470 | # Object variable to store code object waiting execution. This is | |
407 | # used mainly by the multithreaded shells, but it can come in handy in |
|
471 | # used mainly by the multithreaded shells, but it can come in handy in | |
408 | # other situations. No need to use a Queue here, since it's a single |
|
472 | # other situations. No need to use a Queue here, since it's a single | |
409 | # item which gets cleared once run. |
|
473 | # item which gets cleared once run. | |
410 | self.code_to_run = None |
|
474 | self.code_to_run = None | |
411 |
|
475 | |||
412 | # Flag to mark unconditional exit |
|
476 | # Flag to mark unconditional exit | |
413 | self.exit_now = False |
|
477 | self.exit_now = False | |
414 |
|
478 | |||
415 | # Temporary files used for various purposes. Deleted at exit. |
|
479 | # Temporary files used for various purposes. Deleted at exit. | |
416 | self.tempfiles = [] |
|
480 | self.tempfiles = [] | |
417 |
|
481 | |||
418 | # Keep track of readline usage (later set by init_readline) |
|
482 | # Keep track of readline usage (later set by init_readline) | |
419 | self.has_readline = False |
|
483 | self.has_readline = False | |
420 |
|
484 | |||
421 | # keep track of where we started running (mainly for crash post-mortem) |
|
485 | # keep track of where we started running (mainly for crash post-mortem) | |
422 | # This is not being used anywhere currently. |
|
486 | # This is not being used anywhere currently. | |
423 | self.starting_dir = os.getcwd() |
|
487 | self.starting_dir = os.getcwd() | |
424 |
|
488 | |||
425 | # Indentation management |
|
489 | # Indentation management | |
426 | self.indent_current_nsp = 0 |
|
490 | self.indent_current_nsp = 0 | |
427 |
|
491 | |||
428 | def init_term_title(self): |
|
492 | def init_term_title(self): | |
429 | # Enable or disable the terminal title. |
|
493 | # Enable or disable the terminal title. | |
430 | if self.term_title: |
|
494 | if self.term_title: | |
431 | toggle_set_term_title(True) |
|
495 | toggle_set_term_title(True) | |
432 | set_term_title('IPython: ' + abbrev_cwd()) |
|
496 | set_term_title('IPython: ' + abbrev_cwd()) | |
433 | else: |
|
497 | else: | |
434 | toggle_set_term_title(False) |
|
498 | toggle_set_term_title(False) | |
435 |
|
499 | |||
436 | def init_usage(self, usage=None): |
|
500 | def init_usage(self, usage=None): | |
437 | if usage is None: |
|
501 | if usage is None: | |
438 | self.usage = interactive_usage |
|
502 | self.usage = interactive_usage | |
439 | else: |
|
503 | else: | |
440 | self.usage = usage |
|
504 | self.usage = usage | |
441 |
|
505 | |||
442 | def init_encoding(self): |
|
506 | def init_encoding(self): | |
443 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
507 | # Get system encoding at startup time. Certain terminals (like Emacs | |
444 | # under Win32 have it set to None, and we need to have a known valid |
|
508 | # under Win32 have it set to None, and we need to have a known valid | |
445 | # encoding to use in the raw_input() method |
|
509 | # encoding to use in the raw_input() method | |
446 | try: |
|
510 | try: | |
447 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
511 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
448 | except AttributeError: |
|
512 | except AttributeError: | |
449 | self.stdin_encoding = 'ascii' |
|
513 | self.stdin_encoding = 'ascii' | |
450 |
|
514 | |||
451 | def init_syntax_highlighting(self): |
|
515 | def init_syntax_highlighting(self): | |
452 | # Python source parser/formatter for syntax highlighting |
|
516 | # Python source parser/formatter for syntax highlighting | |
453 | pyformat = PyColorize.Parser().format |
|
517 | pyformat = PyColorize.Parser().format | |
454 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
518 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
455 |
|
519 | |||
456 | def init_pushd_popd_magic(self): |
|
520 | def init_pushd_popd_magic(self): | |
457 | # for pushd/popd management |
|
521 | # for pushd/popd management | |
458 | try: |
|
522 | try: | |
459 | self.home_dir = get_home_dir() |
|
523 | self.home_dir = get_home_dir() | |
460 | except HomeDirError, msg: |
|
524 | except HomeDirError, msg: | |
461 | fatal(msg) |
|
525 | fatal(msg) | |
462 |
|
526 | |||
463 | self.dir_stack = [] |
|
527 | self.dir_stack = [] | |
464 |
|
528 | |||
465 | def init_logger(self): |
|
529 | def init_logger(self): | |
466 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
530 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
467 | # local shortcut, this is used a LOT |
|
531 | # local shortcut, this is used a LOT | |
468 | self.log = self.logger.log |
|
532 | self.log = self.logger.log | |
469 |
|
533 | |||
470 | def init_logstart(self): |
|
534 | def init_logstart(self): | |
471 | if self.logappend: |
|
535 | if self.logappend: | |
472 | self.magic_logstart(self.logappend + ' append') |
|
536 | self.magic_logstart(self.logappend + ' append') | |
473 | elif self.logfile: |
|
537 | elif self.logfile: | |
474 | self.magic_logstart(self.logfile) |
|
538 | self.magic_logstart(self.logfile) | |
475 | elif self.logstart: |
|
539 | elif self.logstart: | |
476 | self.magic_logstart() |
|
540 | self.magic_logstart() | |
477 |
|
541 | |||
478 | def init_builtins(self): |
|
542 | def init_builtins(self): | |
479 | self.builtin_trap = BuiltinTrap(self) |
|
543 | self.builtin_trap = BuiltinTrap(self) | |
480 |
|
544 | |||
481 | def init_inspector(self): |
|
545 | def init_inspector(self): | |
482 | # Object inspector |
|
546 | # Object inspector | |
483 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
547 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
484 | PyColorize.ANSICodeColors, |
|
548 | PyColorize.ANSICodeColors, | |
485 | 'NoColor', |
|
549 | 'NoColor', | |
486 | self.object_info_string_level) |
|
550 | self.object_info_string_level) | |
487 |
|
551 | |||
488 | def init_prompts(self): |
|
552 | def init_prompts(self): | |
489 | # Initialize cache, set in/out prompts and printing system |
|
553 | # Initialize cache, set in/out prompts and printing system | |
490 | self.outputcache = CachedOutput(self, |
|
554 | self.outputcache = CachedOutput(self, | |
491 | self.cache_size, |
|
555 | self.cache_size, | |
492 | self.pprint, |
|
556 | self.pprint, | |
493 | input_sep = self.separate_in, |
|
557 | input_sep = self.separate_in, | |
494 | output_sep = self.separate_out, |
|
558 | output_sep = self.separate_out, | |
495 | output_sep2 = self.separate_out2, |
|
559 | output_sep2 = self.separate_out2, | |
496 | ps1 = self.prompt_in1, |
|
560 | ps1 = self.prompt_in1, | |
497 | ps2 = self.prompt_in2, |
|
561 | ps2 = self.prompt_in2, | |
498 | ps_out = self.prompt_out, |
|
562 | ps_out = self.prompt_out, | |
499 | pad_left = self.prompts_pad_left) |
|
563 | pad_left = self.prompts_pad_left) | |
500 |
|
564 | |||
501 | # user may have over-ridden the default print hook: |
|
565 | # user may have over-ridden the default print hook: | |
502 | try: |
|
566 | try: | |
503 | self.outputcache.__class__.display = self.hooks.display |
|
567 | self.outputcache.__class__.display = self.hooks.display | |
504 | except AttributeError: |
|
568 | except AttributeError: | |
505 | pass |
|
569 | pass | |
506 |
|
570 | |||
507 | def init_displayhook(self): |
|
571 | def init_displayhook(self): | |
508 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
572 | self.display_trap = DisplayTrap(self, self.outputcache) | |
509 |
|
573 | |||
510 | def init_reload_doctest(self): |
|
574 | def init_reload_doctest(self): | |
511 | # Do a proper resetting of doctest, including the necessary displayhook |
|
575 | # Do a proper resetting of doctest, including the necessary displayhook | |
512 | # monkeypatching |
|
576 | # monkeypatching | |
513 | try: |
|
577 | try: | |
514 | doctest_reload() |
|
578 | doctest_reload() | |
515 | except ImportError: |
|
579 | except ImportError: | |
516 | warn("doctest module does not exist.") |
|
580 | warn("doctest module does not exist.") | |
517 |
|
581 | |||
518 | #------------------------------------------------------------------------- |
|
582 | #------------------------------------------------------------------------- | |
519 | # Things related to the banner |
|
583 | # Things related to the banner | |
520 | #------------------------------------------------------------------------- |
|
584 | #------------------------------------------------------------------------- | |
521 |
|
585 | |||
522 | def init_banner(self, banner1, banner2, display_banner): |
|
586 | def init_banner(self, banner1, banner2, display_banner): | |
523 | if banner1 is not None: |
|
587 | if banner1 is not None: | |
524 | self.banner1 = banner1 |
|
588 | self.banner1 = banner1 | |
525 | if banner2 is not None: |
|
589 | if banner2 is not None: | |
526 | self.banner2 = banner2 |
|
590 | self.banner2 = banner2 | |
527 | if display_banner is not None: |
|
591 | if display_banner is not None: | |
528 | self.display_banner = display_banner |
|
592 | self.display_banner = display_banner | |
529 | self.compute_banner() |
|
593 | self.compute_banner() | |
530 |
|
594 | |||
531 | def show_banner(self, banner=None): |
|
595 | def show_banner(self, banner=None): | |
532 | if banner is None: |
|
596 | if banner is None: | |
533 | banner = self.banner |
|
597 | banner = self.banner | |
534 | self.write(banner) |
|
598 | self.write(banner) | |
535 |
|
599 | |||
536 | def compute_banner(self): |
|
600 | def compute_banner(self): | |
537 | self.banner = self.banner1 + '\n' |
|
601 | self.banner = self.banner1 + '\n' | |
538 | if self.profile: |
|
602 | if self.profile: | |
539 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
603 | self.banner += '\nIPython profile: %s\n' % self.profile | |
540 | if self.banner2: |
|
604 | if self.banner2: | |
541 | self.banner += '\n' + self.banner2 + '\n' |
|
605 | self.banner += '\n' + self.banner2 + '\n' | |
542 |
|
606 | |||
543 | #------------------------------------------------------------------------- |
|
607 | #------------------------------------------------------------------------- | |
544 | # Things related to injections into the sys module |
|
608 | # Things related to injections into the sys module | |
545 | #------------------------------------------------------------------------- |
|
609 | #------------------------------------------------------------------------- | |
546 |
|
610 | |||
547 | def save_sys_module_state(self): |
|
611 | def save_sys_module_state(self): | |
548 | """Save the state of hooks in the sys module. |
|
612 | """Save the state of hooks in the sys module. | |
549 |
|
613 | |||
550 | This has to be called after self.user_ns is created. |
|
614 | This has to be called after self.user_ns is created. | |
551 | """ |
|
615 | """ | |
552 | self._orig_sys_module_state = {} |
|
616 | self._orig_sys_module_state = {} | |
553 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
617 | self._orig_sys_module_state['stdin'] = sys.stdin | |
554 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
618 | self._orig_sys_module_state['stdout'] = sys.stdout | |
555 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
619 | self._orig_sys_module_state['stderr'] = sys.stderr | |
556 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
620 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
557 | try: |
|
621 | try: | |
558 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
622 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
559 | except KeyError: |
|
623 | except KeyError: | |
560 | pass |
|
624 | pass | |
561 |
|
625 | |||
562 | def restore_sys_module_state(self): |
|
626 | def restore_sys_module_state(self): | |
563 | """Restore the state of the sys module.""" |
|
627 | """Restore the state of the sys module.""" | |
564 | try: |
|
628 | try: | |
565 | for k, v in self._orig_sys_module_state.items(): |
|
629 | for k, v in self._orig_sys_module_state.items(): | |
566 | setattr(sys, k, v) |
|
630 | setattr(sys, k, v) | |
567 | except AttributeError: |
|
631 | except AttributeError: | |
568 | pass |
|
632 | pass | |
569 | try: |
|
633 | try: | |
570 | delattr(sys, 'ipcompleter') |
|
634 | delattr(sys, 'ipcompleter') | |
571 | except AttributeError: |
|
635 | except AttributeError: | |
572 | pass |
|
636 | pass | |
573 | # Reset what what done in self.init_sys_modules |
|
637 | # Reset what what done in self.init_sys_modules | |
574 | try: |
|
638 | try: | |
575 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
639 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
576 | except (AttributeError, KeyError): |
|
640 | except (AttributeError, KeyError): | |
577 | pass |
|
641 | pass | |
578 |
|
642 | |||
579 | #------------------------------------------------------------------------- |
|
643 | #------------------------------------------------------------------------- | |
580 | # Things related to hooks |
|
644 | # Things related to hooks | |
581 | #------------------------------------------------------------------------- |
|
645 | #------------------------------------------------------------------------- | |
582 |
|
646 | |||
583 | def init_hooks(self): |
|
647 | def init_hooks(self): | |
584 | # hooks holds pointers used for user-side customizations |
|
648 | # hooks holds pointers used for user-side customizations | |
585 | self.hooks = Struct() |
|
649 | self.hooks = Struct() | |
586 |
|
650 | |||
587 | self.strdispatchers = {} |
|
651 | self.strdispatchers = {} | |
588 |
|
652 | |||
589 | # Set all default hooks, defined in the IPython.hooks module. |
|
653 | # Set all default hooks, defined in the IPython.hooks module. | |
590 | import IPython.core.hooks |
|
654 | import IPython.core.hooks | |
591 | hooks = IPython.core.hooks |
|
655 | hooks = IPython.core.hooks | |
592 | for hook_name in hooks.__all__: |
|
656 | for hook_name in hooks.__all__: | |
593 | # default hooks have priority 100, i.e. low; user hooks should have |
|
657 | # default hooks have priority 100, i.e. low; user hooks should have | |
594 | # 0-100 priority |
|
658 | # 0-100 priority | |
595 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
659 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
596 |
|
660 | |||
597 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
661 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
598 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
662 | """set_hook(name,hook) -> sets an internal IPython hook. | |
599 |
|
663 | |||
600 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
664 | IPython exposes some of its internal API as user-modifiable hooks. By | |
601 | adding your function to one of these hooks, you can modify IPython's |
|
665 | adding your function to one of these hooks, you can modify IPython's | |
602 | behavior to call at runtime your own routines.""" |
|
666 | behavior to call at runtime your own routines.""" | |
603 |
|
667 | |||
604 | # At some point in the future, this should validate the hook before it |
|
668 | # At some point in the future, this should validate the hook before it | |
605 | # accepts it. Probably at least check that the hook takes the number |
|
669 | # accepts it. Probably at least check that the hook takes the number | |
606 | # of args it's supposed to. |
|
670 | # of args it's supposed to. | |
607 |
|
671 | |||
608 | f = new.instancemethod(hook,self,self.__class__) |
|
672 | f = new.instancemethod(hook,self,self.__class__) | |
609 |
|
673 | |||
610 | # check if the hook is for strdispatcher first |
|
674 | # check if the hook is for strdispatcher first | |
611 | if str_key is not None: |
|
675 | if str_key is not None: | |
612 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
676 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
613 | sdp.add_s(str_key, f, priority ) |
|
677 | sdp.add_s(str_key, f, priority ) | |
614 | self.strdispatchers[name] = sdp |
|
678 | self.strdispatchers[name] = sdp | |
615 | return |
|
679 | return | |
616 | if re_key is not None: |
|
680 | if re_key is not None: | |
617 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
681 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
618 | sdp.add_re(re.compile(re_key), f, priority ) |
|
682 | sdp.add_re(re.compile(re_key), f, priority ) | |
619 | self.strdispatchers[name] = sdp |
|
683 | self.strdispatchers[name] = sdp | |
620 | return |
|
684 | return | |
621 |
|
685 | |||
622 | dp = getattr(self.hooks, name, None) |
|
686 | dp = getattr(self.hooks, name, None) | |
623 | if name not in IPython.core.hooks.__all__: |
|
687 | if name not in IPython.core.hooks.__all__: | |
624 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
688 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) | |
625 | if not dp: |
|
689 | if not dp: | |
626 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
690 | dp = IPython.core.hooks.CommandChainDispatcher() | |
627 |
|
691 | |||
628 | try: |
|
692 | try: | |
629 | dp.add(f,priority) |
|
693 | dp.add(f,priority) | |
630 | except AttributeError: |
|
694 | except AttributeError: | |
631 | # it was not commandchain, plain old func - replace |
|
695 | # it was not commandchain, plain old func - replace | |
632 | dp = f |
|
696 | dp = f | |
633 |
|
697 | |||
634 | setattr(self.hooks,name, dp) |
|
698 | setattr(self.hooks,name, dp) | |
635 |
|
699 | |||
636 | #------------------------------------------------------------------------- |
|
700 | #------------------------------------------------------------------------- | |
637 | # Things related to the "main" module |
|
701 | # Things related to the "main" module | |
638 | #------------------------------------------------------------------------- |
|
702 | #------------------------------------------------------------------------- | |
639 |
|
703 | |||
640 | def new_main_mod(self,ns=None): |
|
704 | def new_main_mod(self,ns=None): | |
641 | """Return a new 'main' module object for user code execution. |
|
705 | """Return a new 'main' module object for user code execution. | |
642 | """ |
|
706 | """ | |
643 | main_mod = self._user_main_module |
|
707 | main_mod = self._user_main_module | |
644 | init_fakemod_dict(main_mod,ns) |
|
708 | init_fakemod_dict(main_mod,ns) | |
645 | return main_mod |
|
709 | return main_mod | |
646 |
|
710 | |||
647 | def cache_main_mod(self,ns,fname): |
|
711 | def cache_main_mod(self,ns,fname): | |
648 | """Cache a main module's namespace. |
|
712 | """Cache a main module's namespace. | |
649 |
|
713 | |||
650 | When scripts are executed via %run, we must keep a reference to the |
|
714 | When scripts are executed via %run, we must keep a reference to the | |
651 | namespace of their __main__ module (a FakeModule instance) around so |
|
715 | namespace of their __main__ module (a FakeModule instance) around so | |
652 | that Python doesn't clear it, rendering objects defined therein |
|
716 | that Python doesn't clear it, rendering objects defined therein | |
653 | useless. |
|
717 | useless. | |
654 |
|
718 | |||
655 | This method keeps said reference in a private dict, keyed by the |
|
719 | This method keeps said reference in a private dict, keyed by the | |
656 | absolute path of the module object (which corresponds to the script |
|
720 | absolute path of the module object (which corresponds to the script | |
657 | path). This way, for multiple executions of the same script we only |
|
721 | path). This way, for multiple executions of the same script we only | |
658 | keep one copy of the namespace (the last one), thus preventing memory |
|
722 | keep one copy of the namespace (the last one), thus preventing memory | |
659 | leaks from old references while allowing the objects from the last |
|
723 | leaks from old references while allowing the objects from the last | |
660 | execution to be accessible. |
|
724 | execution to be accessible. | |
661 |
|
725 | |||
662 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
726 | Note: we can not allow the actual FakeModule instances to be deleted, | |
663 | because of how Python tears down modules (it hard-sets all their |
|
727 | because of how Python tears down modules (it hard-sets all their | |
664 | references to None without regard for reference counts). This method |
|
728 | references to None without regard for reference counts). This method | |
665 | must therefore make a *copy* of the given namespace, to allow the |
|
729 | must therefore make a *copy* of the given namespace, to allow the | |
666 | original module's __dict__ to be cleared and reused. |
|
730 | original module's __dict__ to be cleared and reused. | |
667 |
|
731 | |||
668 |
|
732 | |||
669 | Parameters |
|
733 | Parameters | |
670 | ---------- |
|
734 | ---------- | |
671 | ns : a namespace (a dict, typically) |
|
735 | ns : a namespace (a dict, typically) | |
672 |
|
736 | |||
673 | fname : str |
|
737 | fname : str | |
674 | Filename associated with the namespace. |
|
738 | Filename associated with the namespace. | |
675 |
|
739 | |||
676 | Examples |
|
740 | Examples | |
677 | -------- |
|
741 | -------- | |
678 |
|
742 | |||
679 | In [10]: import IPython |
|
743 | In [10]: import IPython | |
680 |
|
744 | |||
681 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
745 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
682 |
|
746 | |||
683 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
747 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
684 | Out[12]: True |
|
748 | Out[12]: True | |
685 | """ |
|
749 | """ | |
686 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
750 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
687 |
|
751 | |||
688 | def clear_main_mod_cache(self): |
|
752 | def clear_main_mod_cache(self): | |
689 | """Clear the cache of main modules. |
|
753 | """Clear the cache of main modules. | |
690 |
|
754 | |||
691 | Mainly for use by utilities like %reset. |
|
755 | Mainly for use by utilities like %reset. | |
692 |
|
756 | |||
693 | Examples |
|
757 | Examples | |
694 | -------- |
|
758 | -------- | |
695 |
|
759 | |||
696 | In [15]: import IPython |
|
760 | In [15]: import IPython | |
697 |
|
761 | |||
698 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
762 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
699 |
|
763 | |||
700 | In [17]: len(_ip._main_ns_cache) > 0 |
|
764 | In [17]: len(_ip._main_ns_cache) > 0 | |
701 | Out[17]: True |
|
765 | Out[17]: True | |
702 |
|
766 | |||
703 | In [18]: _ip.clear_main_mod_cache() |
|
767 | In [18]: _ip.clear_main_mod_cache() | |
704 |
|
768 | |||
705 | In [19]: len(_ip._main_ns_cache) == 0 |
|
769 | In [19]: len(_ip._main_ns_cache) == 0 | |
706 | Out[19]: True |
|
770 | Out[19]: True | |
707 | """ |
|
771 | """ | |
708 | self._main_ns_cache.clear() |
|
772 | self._main_ns_cache.clear() | |
709 |
|
773 | |||
710 | #------------------------------------------------------------------------- |
|
774 | #------------------------------------------------------------------------- | |
711 | # Things related to debugging |
|
775 | # Things related to debugging | |
712 | #------------------------------------------------------------------------- |
|
776 | #------------------------------------------------------------------------- | |
713 |
|
777 | |||
714 | def init_pdb(self): |
|
778 | def init_pdb(self): | |
715 | # Set calling of pdb on exceptions |
|
779 | # Set calling of pdb on exceptions | |
716 | # self.call_pdb is a property |
|
780 | # self.call_pdb is a property | |
717 | self.call_pdb = self.pdb |
|
781 | self.call_pdb = self.pdb | |
718 |
|
782 | |||
719 | def _get_call_pdb(self): |
|
783 | def _get_call_pdb(self): | |
720 | return self._call_pdb |
|
784 | return self._call_pdb | |
721 |
|
785 | |||
722 | def _set_call_pdb(self,val): |
|
786 | def _set_call_pdb(self,val): | |
723 |
|
787 | |||
724 | if val not in (0,1,False,True): |
|
788 | if val not in (0,1,False,True): | |
725 | raise ValueError,'new call_pdb value must be boolean' |
|
789 | raise ValueError,'new call_pdb value must be boolean' | |
726 |
|
790 | |||
727 | # store value in instance |
|
791 | # store value in instance | |
728 | self._call_pdb = val |
|
792 | self._call_pdb = val | |
729 |
|
793 | |||
730 | # notify the actual exception handlers |
|
794 | # notify the actual exception handlers | |
731 | self.InteractiveTB.call_pdb = val |
|
795 | self.InteractiveTB.call_pdb = val | |
732 | if self.isthreaded: |
|
796 | if self.isthreaded: | |
733 | try: |
|
797 | try: | |
734 | self.sys_excepthook.call_pdb = val |
|
798 | self.sys_excepthook.call_pdb = val | |
735 | except: |
|
799 | except: | |
736 | warn('Failed to activate pdb for threaded exception handler') |
|
800 | warn('Failed to activate pdb for threaded exception handler') | |
737 |
|
801 | |||
738 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
802 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
739 | 'Control auto-activation of pdb at exceptions') |
|
803 | 'Control auto-activation of pdb at exceptions') | |
740 |
|
804 | |||
741 | def debugger(self,force=False): |
|
805 | def debugger(self,force=False): | |
742 | """Call the pydb/pdb debugger. |
|
806 | """Call the pydb/pdb debugger. | |
743 |
|
807 | |||
744 | Keywords: |
|
808 | Keywords: | |
745 |
|
809 | |||
746 | - force(False): by default, this routine checks the instance call_pdb |
|
810 | - force(False): by default, this routine checks the instance call_pdb | |
747 | flag and does not actually invoke the debugger if the flag is false. |
|
811 | flag and does not actually invoke the debugger if the flag is false. | |
748 | The 'force' option forces the debugger to activate even if the flag |
|
812 | The 'force' option forces the debugger to activate even if the flag | |
749 | is false. |
|
813 | is false. | |
750 | """ |
|
814 | """ | |
751 |
|
815 | |||
752 | if not (force or self.call_pdb): |
|
816 | if not (force or self.call_pdb): | |
753 | return |
|
817 | return | |
754 |
|
818 | |||
755 | if not hasattr(sys,'last_traceback'): |
|
819 | if not hasattr(sys,'last_traceback'): | |
756 | error('No traceback has been produced, nothing to debug.') |
|
820 | error('No traceback has been produced, nothing to debug.') | |
757 | return |
|
821 | return | |
758 |
|
822 | |||
759 | # use pydb if available |
|
823 | # use pydb if available | |
760 | if debugger.has_pydb: |
|
824 | if debugger.has_pydb: | |
761 | from pydb import pm |
|
825 | from pydb import pm | |
762 | else: |
|
826 | else: | |
763 | # fallback to our internal debugger |
|
827 | # fallback to our internal debugger | |
764 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
828 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
765 | self.history_saving_wrapper(pm)() |
|
829 | self.history_saving_wrapper(pm)() | |
766 |
|
830 | |||
767 | #------------------------------------------------------------------------- |
|
831 | #------------------------------------------------------------------------- | |
768 | # Things related to IPython's various namespaces |
|
832 | # Things related to IPython's various namespaces | |
769 | #------------------------------------------------------------------------- |
|
833 | #------------------------------------------------------------------------- | |
770 |
|
834 | |||
771 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
835 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
772 | # Create the namespace where the user will operate. user_ns is |
|
836 | # Create the namespace where the user will operate. user_ns is | |
773 | # normally the only one used, and it is passed to the exec calls as |
|
837 | # normally the only one used, and it is passed to the exec calls as | |
774 | # the locals argument. But we do carry a user_global_ns namespace |
|
838 | # the locals argument. But we do carry a user_global_ns namespace | |
775 | # given as the exec 'globals' argument, This is useful in embedding |
|
839 | # given as the exec 'globals' argument, This is useful in embedding | |
776 | # situations where the ipython shell opens in a context where the |
|
840 | # situations where the ipython shell opens in a context where the | |
777 | # distinction between locals and globals is meaningful. For |
|
841 | # distinction between locals and globals is meaningful. For | |
778 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
842 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
779 |
|
843 | |||
780 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
844 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
781 | # level as a dict instead of a module. This is a manual fix, but I |
|
845 | # level as a dict instead of a module. This is a manual fix, but I | |
782 | # should really track down where the problem is coming from. Alex |
|
846 | # should really track down where the problem is coming from. Alex | |
783 | # Schmolck reported this problem first. |
|
847 | # Schmolck reported this problem first. | |
784 |
|
848 | |||
785 | # A useful post by Alex Martelli on this topic: |
|
849 | # A useful post by Alex Martelli on this topic: | |
786 | # Re: inconsistent value from __builtins__ |
|
850 | # Re: inconsistent value from __builtins__ | |
787 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
851 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
788 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
852 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
789 | # Gruppen: comp.lang.python |
|
853 | # Gruppen: comp.lang.python | |
790 |
|
854 | |||
791 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
855 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
792 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
856 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
793 | # > <type 'dict'> |
|
857 | # > <type 'dict'> | |
794 | # > >>> print type(__builtins__) |
|
858 | # > >>> print type(__builtins__) | |
795 | # > <type 'module'> |
|
859 | # > <type 'module'> | |
796 | # > Is this difference in return value intentional? |
|
860 | # > Is this difference in return value intentional? | |
797 |
|
861 | |||
798 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
862 | # Well, it's documented that '__builtins__' can be either a dictionary | |
799 | # or a module, and it's been that way for a long time. Whether it's |
|
863 | # or a module, and it's been that way for a long time. Whether it's | |
800 | # intentional (or sensible), I don't know. In any case, the idea is |
|
864 | # intentional (or sensible), I don't know. In any case, the idea is | |
801 | # that if you need to access the built-in namespace directly, you |
|
865 | # that if you need to access the built-in namespace directly, you | |
802 | # should start with "import __builtin__" (note, no 's') which will |
|
866 | # should start with "import __builtin__" (note, no 's') which will | |
803 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
867 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
804 |
|
868 | |||
805 | # These routines return properly built dicts as needed by the rest of |
|
869 | # These routines return properly built dicts as needed by the rest of | |
806 | # the code, and can also be used by extension writers to generate |
|
870 | # the code, and can also be used by extension writers to generate | |
807 | # properly initialized namespaces. |
|
871 | # properly initialized namespaces. | |
808 |
user_ns, user_global_ns = |
|
872 | user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns) | |
809 | user_global_ns) |
|
|||
810 |
|
873 | |||
811 | # Assign namespaces |
|
874 | # Assign namespaces | |
812 | # This is the namespace where all normal user variables live |
|
875 | # This is the namespace where all normal user variables live | |
813 | self.user_ns = user_ns |
|
876 | self.user_ns = user_ns | |
814 | self.user_global_ns = user_global_ns |
|
877 | self.user_global_ns = user_global_ns | |
815 |
|
878 | |||
816 | # An auxiliary namespace that checks what parts of the user_ns were |
|
879 | # An auxiliary namespace that checks what parts of the user_ns were | |
817 | # loaded at startup, so we can list later only variables defined in |
|
880 | # loaded at startup, so we can list later only variables defined in | |
818 | # actual interactive use. Since it is always a subset of user_ns, it |
|
881 | # actual interactive use. Since it is always a subset of user_ns, it | |
819 |
# doesn't need to be se |
|
882 | # doesn't need to be separately tracked in the ns_table. | |
820 | self.user_config_ns = {} |
|
883 | self.user_config_ns = {} | |
821 |
|
884 | |||
822 | # A namespace to keep track of internal data structures to prevent |
|
885 | # A namespace to keep track of internal data structures to prevent | |
823 | # them from cluttering user-visible stuff. Will be updated later |
|
886 | # them from cluttering user-visible stuff. Will be updated later | |
824 | self.internal_ns = {} |
|
887 | self.internal_ns = {} | |
825 |
|
888 | |||
826 | # Now that FakeModule produces a real module, we've run into a nasty |
|
889 | # Now that FakeModule produces a real module, we've run into a nasty | |
827 | # problem: after script execution (via %run), the module where the user |
|
890 | # problem: after script execution (via %run), the module where the user | |
828 | # code ran is deleted. Now that this object is a true module (needed |
|
891 | # code ran is deleted. Now that this object is a true module (needed | |
829 | # so docetst and other tools work correctly), the Python module |
|
892 | # so docetst and other tools work correctly), the Python module | |
830 | # teardown mechanism runs over it, and sets to None every variable |
|
893 | # teardown mechanism runs over it, and sets to None every variable | |
831 | # present in that module. Top-level references to objects from the |
|
894 | # present in that module. Top-level references to objects from the | |
832 | # script survive, because the user_ns is updated with them. However, |
|
895 | # script survive, because the user_ns is updated with them. However, | |
833 | # calling functions defined in the script that use other things from |
|
896 | # calling functions defined in the script that use other things from | |
834 | # the script will fail, because the function's closure had references |
|
897 | # the script will fail, because the function's closure had references | |
835 | # to the original objects, which are now all None. So we must protect |
|
898 | # to the original objects, which are now all None. So we must protect | |
836 | # these modules from deletion by keeping a cache. |
|
899 | # these modules from deletion by keeping a cache. | |
837 | # |
|
900 | # | |
838 | # To avoid keeping stale modules around (we only need the one from the |
|
901 | # To avoid keeping stale modules around (we only need the one from the | |
839 | # last run), we use a dict keyed with the full path to the script, so |
|
902 | # last run), we use a dict keyed with the full path to the script, so | |
840 | # only the last version of the module is held in the cache. Note, |
|
903 | # only the last version of the module is held in the cache. Note, | |
841 | # however, that we must cache the module *namespace contents* (their |
|
904 | # however, that we must cache the module *namespace contents* (their | |
842 | # __dict__). Because if we try to cache the actual modules, old ones |
|
905 | # __dict__). Because if we try to cache the actual modules, old ones | |
843 | # (uncached) could be destroyed while still holding references (such as |
|
906 | # (uncached) could be destroyed while still holding references (such as | |
844 | # those held by GUI objects that tend to be long-lived)> |
|
907 | # those held by GUI objects that tend to be long-lived)> | |
845 | # |
|
908 | # | |
846 | # The %reset command will flush this cache. See the cache_main_mod() |
|
909 | # The %reset command will flush this cache. See the cache_main_mod() | |
847 | # and clear_main_mod_cache() methods for details on use. |
|
910 | # and clear_main_mod_cache() methods for details on use. | |
848 |
|
911 | |||
849 | # This is the cache used for 'main' namespaces |
|
912 | # This is the cache used for 'main' namespaces | |
850 | self._main_ns_cache = {} |
|
913 | self._main_ns_cache = {} | |
851 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
914 | # And this is the single instance of FakeModule whose __dict__ we keep | |
852 | # copying and clearing for reuse on each %run |
|
915 | # copying and clearing for reuse on each %run | |
853 | self._user_main_module = FakeModule() |
|
916 | self._user_main_module = FakeModule() | |
854 |
|
917 | |||
855 | # A table holding all the namespaces IPython deals with, so that |
|
918 | # A table holding all the namespaces IPython deals with, so that | |
856 | # introspection facilities can search easily. |
|
919 | # introspection facilities can search easily. | |
857 | self.ns_table = {'user':user_ns, |
|
920 | self.ns_table = {'user':user_ns, | |
858 | 'user_global':user_global_ns, |
|
921 | 'user_global':user_global_ns, | |
859 | 'internal':self.internal_ns, |
|
922 | 'internal':self.internal_ns, | |
860 | 'builtin':__builtin__.__dict__ |
|
923 | 'builtin':__builtin__.__dict__ | |
861 | } |
|
924 | } | |
862 |
|
925 | |||
863 | # Similarly, track all namespaces where references can be held and that |
|
926 | # Similarly, track all namespaces where references can be held and that | |
864 | # we can safely clear (so it can NOT include builtin). This one can be |
|
927 | # we can safely clear (so it can NOT include builtin). This one can be | |
865 | # a simple list. |
|
928 | # a simple list. | |
866 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
929 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, | |
867 | self.internal_ns, self._main_ns_cache ] |
|
930 | self.internal_ns, self._main_ns_cache ] | |
868 |
|
931 | |||
869 | def init_sys_modules(self): |
|
932 | def init_sys_modules(self): | |
870 | # We need to insert into sys.modules something that looks like a |
|
933 | # We need to insert into sys.modules something that looks like a | |
871 | # module but which accesses the IPython namespace, for shelve and |
|
934 | # module but which accesses the IPython namespace, for shelve and | |
872 | # pickle to work interactively. Normally they rely on getting |
|
935 | # pickle to work interactively. Normally they rely on getting | |
873 | # everything out of __main__, but for embedding purposes each IPython |
|
936 | # everything out of __main__, but for embedding purposes each IPython | |
874 | # instance has its own private namespace, so we can't go shoving |
|
937 | # instance has its own private namespace, so we can't go shoving | |
875 | # everything into __main__. |
|
938 | # everything into __main__. | |
876 |
|
939 | |||
877 | # note, however, that we should only do this for non-embedded |
|
940 | # note, however, that we should only do this for non-embedded | |
878 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
941 | # ipythons, which really mimic the __main__.__dict__ with their own | |
879 | # namespace. Embedded instances, on the other hand, should not do |
|
942 | # namespace. Embedded instances, on the other hand, should not do | |
880 | # this because they need to manage the user local/global namespaces |
|
943 | # this because they need to manage the user local/global namespaces | |
881 | # only, but they live within a 'normal' __main__ (meaning, they |
|
944 | # only, but they live within a 'normal' __main__ (meaning, they | |
882 | # shouldn't overtake the execution environment of the script they're |
|
945 | # shouldn't overtake the execution environment of the script they're | |
883 | # embedded in). |
|
946 | # embedded in). | |
884 |
|
947 | |||
885 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
948 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
886 |
|
949 | |||
887 | try: |
|
950 | try: | |
888 | main_name = self.user_ns['__name__'] |
|
951 | main_name = self.user_ns['__name__'] | |
889 | except KeyError: |
|
952 | except KeyError: | |
890 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
953 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
891 | else: |
|
954 | else: | |
892 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
955 | sys.modules[main_name] = FakeModule(self.user_ns) | |
893 |
|
956 | |||
894 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
|||
895 | """Return a valid local and global user interactive namespaces. |
|
|||
896 |
|
||||
897 | This builds a dict with the minimal information needed to operate as a |
|
|||
898 | valid IPython user namespace, which you can pass to the various |
|
|||
899 | embedding classes in ipython. The default implementation returns the |
|
|||
900 | same dict for both the locals and the globals to allow functions to |
|
|||
901 | refer to variables in the namespace. Customized implementations can |
|
|||
902 | return different dicts. The locals dictionary can actually be anything |
|
|||
903 | following the basic mapping protocol of a dict, but the globals dict |
|
|||
904 | must be a true dict, not even a subclass. It is recommended that any |
|
|||
905 | custom object for the locals namespace synchronize with the globals |
|
|||
906 | dict somehow. |
|
|||
907 |
|
||||
908 | Raises TypeError if the provided globals namespace is not a true dict. |
|
|||
909 |
|
||||
910 | :Parameters: |
|
|||
911 | user_ns : dict-like, optional |
|
|||
912 | The current user namespace. The items in this namespace should |
|
|||
913 | be included in the output. If None, an appropriate blank |
|
|||
914 | namespace should be created. |
|
|||
915 | user_global_ns : dict, optional |
|
|||
916 | The current user global namespace. The items in this namespace |
|
|||
917 | should be included in the output. If None, an appropriate |
|
|||
918 | blank namespace should be created. |
|
|||
919 |
|
||||
920 | :Returns: |
|
|||
921 | A tuple pair of dictionary-like object to be used as the local namespace |
|
|||
922 | of the interpreter and a dict to be used as the global namespace. |
|
|||
923 | """ |
|
|||
924 |
|
||||
925 | if user_ns is None: |
|
|||
926 | # Set __name__ to __main__ to better match the behavior of the |
|
|||
927 | # normal interpreter. |
|
|||
928 | user_ns = {'__name__' :'__main__', |
|
|||
929 | '__builtins__' : __builtin__, |
|
|||
930 | } |
|
|||
931 | else: |
|
|||
932 | user_ns.setdefault('__name__','__main__') |
|
|||
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_user_ns(self): |
|
957 | def init_user_ns(self): | |
944 | """Initialize all user-visible namespaces to their minimum defaults. |
|
958 | """Initialize all user-visible namespaces to their minimum defaults. | |
945 |
|
959 | |||
946 | Certain history lists are also initialized here, as they effectively |
|
960 | Certain history lists are also initialized here, as they effectively | |
947 | act as user namespaces. |
|
961 | act as user namespaces. | |
948 |
|
962 | |||
949 | Notes |
|
963 | Notes | |
950 | ----- |
|
964 | ----- | |
951 | All data structures here are only filled in, they are NOT reset by this |
|
965 | All data structures here are only filled in, they are NOT reset by this | |
952 | method. If they were not empty before, data will simply be added to |
|
966 | method. If they were not empty before, data will simply be added to | |
953 | therm. |
|
967 | therm. | |
954 | """ |
|
968 | """ | |
955 | # Store myself as the public api!!! |
|
969 | # This function works in two parts: first we put a few things in | |
956 | self.user_ns['get_ipython'] = self.get_ipython |
|
970 | # user_ns, and we sync that contents into user_config_ns so that these | |
|
971 | # initial variables aren't shown by %who. After the sync, we add the | |||
|
972 | # rest of what we *do* want the user to see with %who even on a new | |||
|
973 | # session. | |||
|
974 | ns = {} | |||
|
975 | ||||
|
976 | # Put 'help' in the user namespace | |||
|
977 | try: | |||
|
978 | from site import _Helper | |||
|
979 | ns['help'] = _Helper() | |||
|
980 | except ImportError: | |||
|
981 | warn('help() not available - check site.py') | |||
957 |
|
982 | |||
958 | # make global variables for user access to the histories |
|
983 | # make global variables for user access to the histories | |
959 |
|
|
984 | ns['_ih'] = self.input_hist | |
960 |
|
|
985 | ns['_oh'] = self.output_hist | |
961 |
|
|
986 | ns['_dh'] = self.dir_hist | |
|
987 | ||||
|
988 | ns['_sh'] = shadowns | |||
|
989 | ||||
|
990 | # Sync what we've added so far to user_config_ns so these aren't seen | |||
|
991 | # by %who | |||
|
992 | self.user_config_ns.update(ns) | |||
|
993 | ||||
|
994 | # Now, continue adding more contents | |||
962 |
|
995 | |||
963 | # user aliases to input and output histories |
|
996 | # user aliases to input and output histories | |
964 |
|
|
997 | ns['In'] = self.input_hist | |
965 |
|
|
998 | ns['Out'] = self.output_hist | |
966 |
|
999 | |||
967 | self.user_ns['_sh'] = shadowns |
|
1000 | # Store myself as the public api!!! | |
|
1001 | ns['get_ipython'] = self.get_ipython | |||
|
1002 | ||||
|
1003 | # And update the real user's namespace | |||
|
1004 | self.user_ns.update(ns) | |||
968 |
|
1005 | |||
969 | # Put 'help' in the user namespace |
|
|||
970 | try: |
|
|||
971 | from site import _Helper |
|
|||
972 | self.user_ns['help'] = _Helper() |
|
|||
973 | except ImportError: |
|
|||
974 | warn('help() not available - check site.py') |
|
|||
975 |
|
1006 | |||
976 | def reset(self): |
|
1007 | def reset(self): | |
977 | """Clear all internal namespaces. |
|
1008 | """Clear all internal namespaces. | |
978 |
|
1009 | |||
979 | Note that this is much more aggressive than %reset, since it clears |
|
1010 | Note that this is much more aggressive than %reset, since it clears | |
980 | fully all namespaces, as well as all input/output lists. |
|
1011 | fully all namespaces, as well as all input/output lists. | |
981 | """ |
|
1012 | """ | |
982 | for ns in self.ns_refs_table: |
|
1013 | for ns in self.ns_refs_table: | |
983 | ns.clear() |
|
1014 | ns.clear() | |
984 |
|
1015 | |||
985 | self.alias_manager.clear_aliases() |
|
1016 | self.alias_manager.clear_aliases() | |
986 |
|
1017 | |||
987 | # Clear input and output histories |
|
1018 | # Clear input and output histories | |
988 | self.input_hist[:] = [] |
|
1019 | self.input_hist[:] = [] | |
989 | self.input_hist_raw[:] = [] |
|
1020 | self.input_hist_raw[:] = [] | |
990 | self.output_hist.clear() |
|
1021 | self.output_hist.clear() | |
991 |
|
1022 | |||
992 | # Restore the user namespaces to minimal usability |
|
1023 | # Restore the user namespaces to minimal usability | |
993 | self.init_user_ns() |
|
1024 | self.init_user_ns() | |
994 |
|
1025 | |||
995 | # Restore the default and user aliases |
|
1026 | # Restore the default and user aliases | |
996 | self.alias_manager.init_aliases() |
|
1027 | self.alias_manager.init_aliases() | |
997 |
|
1028 | |||
998 | def push(self, variables, interactive=True): |
|
1029 | def push(self, variables, interactive=True): | |
999 | """Inject a group of variables into the IPython user namespace. |
|
1030 | """Inject a group of variables into the IPython user namespace. | |
1000 |
|
1031 | |||
1001 | Parameters |
|
1032 | Parameters | |
1002 | ---------- |
|
1033 | ---------- | |
1003 | variables : dict, str or list/tuple of str |
|
1034 | variables : dict, str or list/tuple of str | |
1004 | The variables to inject into the user's namespace. If a dict, |
|
1035 | The variables to inject into the user's namespace. If a dict, | |
1005 | a simple update is done. If a str, the string is assumed to |
|
1036 | a simple update is done. If a str, the string is assumed to | |
1006 | have variable names separated by spaces. A list/tuple of str |
|
1037 | have variable names separated by spaces. A list/tuple of str | |
1007 | can also be used to give the variable names. If just the variable |
|
1038 | can also be used to give the variable names. If just the variable | |
1008 | names are give (list/tuple/str) then the variable values looked |
|
1039 | names are give (list/tuple/str) then the variable values looked | |
1009 | up in the callers frame. |
|
1040 | up in the callers frame. | |
1010 | interactive : bool |
|
1041 | interactive : bool | |
1011 | If True (default), the variables will be listed with the ``who`` |
|
1042 | If True (default), the variables will be listed with the ``who`` | |
1012 | magic. |
|
1043 | magic. | |
1013 | """ |
|
1044 | """ | |
1014 | vdict = None |
|
1045 | vdict = None | |
1015 |
|
1046 | |||
1016 | # We need a dict of name/value pairs to do namespace updates. |
|
1047 | # We need a dict of name/value pairs to do namespace updates. | |
1017 | if isinstance(variables, dict): |
|
1048 | if isinstance(variables, dict): | |
1018 | vdict = variables |
|
1049 | vdict = variables | |
1019 | elif isinstance(variables, (basestring, list, tuple)): |
|
1050 | elif isinstance(variables, (basestring, list, tuple)): | |
1020 | if isinstance(variables, basestring): |
|
1051 | if isinstance(variables, basestring): | |
1021 | vlist = variables.split() |
|
1052 | vlist = variables.split() | |
1022 | else: |
|
1053 | else: | |
1023 | vlist = variables |
|
1054 | vlist = variables | |
1024 | vdict = {} |
|
1055 | vdict = {} | |
1025 | cf = sys._getframe(1) |
|
1056 | cf = sys._getframe(1) | |
1026 | for name in vlist: |
|
1057 | for name in vlist: | |
1027 | try: |
|
1058 | try: | |
1028 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1059 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1029 | except: |
|
1060 | except: | |
1030 | print ('Could not get variable %s from %s' % |
|
1061 | print ('Could not get variable %s from %s' % | |
1031 | (name,cf.f_code.co_name)) |
|
1062 | (name,cf.f_code.co_name)) | |
1032 | else: |
|
1063 | else: | |
1033 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1064 | raise ValueError('variables must be a dict/str/list/tuple') | |
1034 |
|
1065 | |||
1035 | # Propagate variables to user namespace |
|
1066 | # Propagate variables to user namespace | |
1036 | self.user_ns.update(vdict) |
|
1067 | self.user_ns.update(vdict) | |
1037 |
|
1068 | |||
1038 | # And configure interactive visibility |
|
1069 | # And configure interactive visibility | |
1039 | config_ns = self.user_config_ns |
|
1070 | config_ns = self.user_config_ns | |
1040 | if interactive: |
|
1071 | if interactive: | |
1041 | for name, val in vdict.iteritems(): |
|
1072 | for name, val in vdict.iteritems(): | |
1042 | config_ns.pop(name, None) |
|
1073 | config_ns.pop(name, None) | |
1043 | else: |
|
1074 | else: | |
1044 | for name,val in vdict.iteritems(): |
|
1075 | for name,val in vdict.iteritems(): | |
1045 | config_ns[name] = val |
|
1076 | config_ns[name] = val | |
1046 |
|
1077 | |||
1047 | #------------------------------------------------------------------------- |
|
1078 | #------------------------------------------------------------------------- | |
1048 | # Things related to history management |
|
1079 | # Things related to history management | |
1049 | #------------------------------------------------------------------------- |
|
1080 | #------------------------------------------------------------------------- | |
1050 |
|
1081 | |||
1051 | def init_history(self): |
|
1082 | def init_history(self): | |
1052 | # List of input with multi-line handling. |
|
1083 | # List of input with multi-line handling. | |
1053 | self.input_hist = InputList() |
|
1084 | self.input_hist = InputList() | |
1054 | # This one will hold the 'raw' input history, without any |
|
1085 | # This one will hold the 'raw' input history, without any | |
1055 | # pre-processing. This will allow users to retrieve the input just as |
|
1086 | # pre-processing. This will allow users to retrieve the input just as | |
1056 | # it was exactly typed in by the user, with %hist -r. |
|
1087 | # it was exactly typed in by the user, with %hist -r. | |
1057 | self.input_hist_raw = InputList() |
|
1088 | self.input_hist_raw = InputList() | |
1058 |
|
1089 | |||
1059 | # list of visited directories |
|
1090 | # list of visited directories | |
1060 | try: |
|
1091 | try: | |
1061 | self.dir_hist = [os.getcwd()] |
|
1092 | self.dir_hist = [os.getcwd()] | |
1062 | except OSError: |
|
1093 | except OSError: | |
1063 | self.dir_hist = [] |
|
1094 | self.dir_hist = [] | |
1064 |
|
1095 | |||
1065 | # dict of output history |
|
1096 | # dict of output history | |
1066 | self.output_hist = {} |
|
1097 | self.output_hist = {} | |
1067 |
|
1098 | |||
1068 | # Now the history file |
|
1099 | # Now the history file | |
1069 | if self.profile: |
|
1100 | if self.profile: | |
1070 | histfname = 'history-%s' % self.profile |
|
1101 | histfname = 'history-%s' % self.profile | |
1071 | else: |
|
1102 | else: | |
1072 | histfname = 'history' |
|
1103 | histfname = 'history' | |
1073 | self.histfile = os.path.join(self.ipythondir, histfname) |
|
1104 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1074 |
|
1105 | |||
1075 | # Fill the history zero entry, user counter starts at 1 |
|
1106 | # Fill the history zero entry, user counter starts at 1 | |
1076 | self.input_hist.append('\n') |
|
1107 | self.input_hist.append('\n') | |
1077 | self.input_hist_raw.append('\n') |
|
1108 | self.input_hist_raw.append('\n') | |
1078 |
|
1109 | |||
1079 | def init_shadow_hist(self): |
|
1110 | def init_shadow_hist(self): | |
1080 | try: |
|
1111 | try: | |
1081 | self.db = pickleshare.PickleShareDB(self.ipythondir + "/db") |
|
1112 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1082 | except exceptions.UnicodeDecodeError: |
|
1113 | except exceptions.UnicodeDecodeError: | |
1083 | print "Your ipythondir can't be decoded to unicode!" |
|
1114 | print "Your ipython_dir can't be decoded to unicode!" | |
1084 | print "Please set HOME environment variable to something that" |
|
1115 | print "Please set HOME environment variable to something that" | |
1085 | print r"only has ASCII characters, e.g. c:\home" |
|
1116 | print r"only has ASCII characters, e.g. c:\home" | |
1086 | print "Now it is", self.ipythondir |
|
1117 | print "Now it is", self.ipython_dir | |
1087 | sys.exit() |
|
1118 | sys.exit() | |
1088 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1119 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1089 |
|
1120 | |||
1090 | def savehist(self): |
|
1121 | def savehist(self): | |
1091 | """Save input history to a file (via readline library).""" |
|
1122 | """Save input history to a file (via readline library).""" | |
1092 |
|
1123 | |||
1093 | if not self.has_readline: |
|
|||
1094 | return |
|
|||
1095 |
|
||||
1096 | try: |
|
1124 | try: | |
1097 | self.readline.write_history_file(self.histfile) |
|
1125 | self.readline.write_history_file(self.histfile) | |
1098 | except: |
|
1126 | except: | |
1099 | print 'Unable to save IPython command history to file: ' + \ |
|
1127 | print 'Unable to save IPython command history to file: ' + \ | |
1100 | `self.histfile` |
|
1128 | `self.histfile` | |
1101 |
|
1129 | |||
1102 | def reloadhist(self): |
|
1130 | def reloadhist(self): | |
1103 | """Reload the input history from disk file.""" |
|
1131 | """Reload the input history from disk file.""" | |
1104 |
|
1132 | |||
1105 | if self.has_readline: |
|
1133 | try: | |
1106 | try: |
|
1134 | self.readline.clear_history() | |
1107 |
|
|
1135 | self.readline.read_history_file(self.shell.histfile) | |
1108 | self.readline.read_history_file(self.shell.histfile) |
|
1136 | except AttributeError: | |
1109 | except AttributeError: |
|
1137 | pass | |
1110 | pass |
|
|||
1111 |
|
1138 | |||
1112 | def history_saving_wrapper(self, func): |
|
1139 | def history_saving_wrapper(self, func): | |
1113 | """ Wrap func for readline history saving |
|
1140 | """ Wrap func for readline history saving | |
1114 |
|
1141 | |||
1115 | Convert func into callable that saves & restores |
|
1142 | Convert func into callable that saves & restores | |
1116 | history around the call """ |
|
1143 | history around the call """ | |
1117 |
|
1144 | |||
1118 | if not self.has_readline: |
|
1145 | if not self.has_readline: | |
1119 | return func |
|
1146 | return func | |
1120 |
|
1147 | |||
1121 | def wrapper(): |
|
1148 | def wrapper(): | |
1122 | self.savehist() |
|
1149 | self.savehist() | |
1123 | try: |
|
1150 | try: | |
1124 | func() |
|
1151 | func() | |
1125 | finally: |
|
1152 | finally: | |
1126 | readline.read_history_file(self.histfile) |
|
1153 | readline.read_history_file(self.histfile) | |
1127 | return wrapper |
|
1154 | return wrapper | |
1128 |
|
1155 | |||
1129 | #------------------------------------------------------------------------- |
|
1156 | #------------------------------------------------------------------------- | |
1130 | # Things related to exception handling and tracebacks (not debugging) |
|
1157 | # Things related to exception handling and tracebacks (not debugging) | |
1131 | #------------------------------------------------------------------------- |
|
1158 | #------------------------------------------------------------------------- | |
1132 |
|
1159 | |||
1133 | def init_traceback_handlers(self, custom_exceptions): |
|
1160 | def init_traceback_handlers(self, custom_exceptions): | |
1134 | # Syntax error handler. |
|
1161 | # Syntax error handler. | |
1135 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1162 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') | |
1136 |
|
1163 | |||
1137 | # The interactive one is initialized with an offset, meaning we always |
|
1164 | # The interactive one is initialized with an offset, meaning we always | |
1138 | # want to remove the topmost item in the traceback, which is our own |
|
1165 | # want to remove the topmost item in the traceback, which is our own | |
1139 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1166 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1140 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1167 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1141 | color_scheme='NoColor', |
|
1168 | color_scheme='NoColor', | |
1142 | tb_offset = 1) |
|
1169 | tb_offset = 1) | |
1143 |
|
1170 | |||
1144 | # IPython itself shouldn't crash. This will produce a detailed |
|
1171 | # The instance will store a pointer to the system-wide exception hook, | |
1145 | # post-mortem if it does. But we only install the crash handler for |
|
1172 | # so that runtime code (such as magics) can access it. This is because | |
1146 | # non-threaded shells, the threaded ones use a normal verbose reporter |
|
1173 | # during the read-eval loop, it may get temporarily overwritten. | |
1147 | # and lose the crash handler. This is because exceptions in the main |
|
1174 | self.sys_excepthook = sys.excepthook | |
1148 | # thread (such as in GUI code) propagate directly to sys.excepthook, |
|
|||
1149 | # and there's no point in printing crash dumps for every user exception. |
|
|||
1150 | if self.isthreaded: |
|
|||
1151 | ipCrashHandler = ultratb.FormattedTB() |
|
|||
1152 | else: |
|
|||
1153 | from IPython.core import crashhandler |
|
|||
1154 | ipCrashHandler = crashhandler.IPythonCrashHandler(self) |
|
|||
1155 | self.set_crash_handler(ipCrashHandler) |
|
|||
1156 |
|
1175 | |||
1157 | # and add any custom exception handlers the user may have specified |
|
1176 | # and add any custom exception handlers the user may have specified | |
1158 | self.set_custom_exc(*custom_exceptions) |
|
1177 | self.set_custom_exc(*custom_exceptions) | |
1159 |
|
1178 | |||
1160 | def set_crash_handler(self, crashHandler): |
|
|||
1161 | """Set the IPython crash handler. |
|
|||
1162 |
|
||||
1163 | This must be a callable with a signature suitable for use as |
|
|||
1164 | sys.excepthook.""" |
|
|||
1165 |
|
||||
1166 | # Install the given crash handler as the Python exception hook |
|
|||
1167 | sys.excepthook = crashHandler |
|
|||
1168 |
|
||||
1169 | # The instance will store a pointer to this, so that runtime code |
|
|||
1170 | # (such as magics) can access it. This is because during the |
|
|||
1171 | # read-eval loop, it gets temporarily overwritten (to deal with GUI |
|
|||
1172 | # frameworks). |
|
|||
1173 | self.sys_excepthook = sys.excepthook |
|
|||
1174 |
|
||||
1175 | def set_custom_exc(self,exc_tuple,handler): |
|
1179 | def set_custom_exc(self,exc_tuple,handler): | |
1176 | """set_custom_exc(exc_tuple,handler) |
|
1180 | """set_custom_exc(exc_tuple,handler) | |
1177 |
|
1181 | |||
1178 | Set a custom exception handler, which will be called if any of the |
|
1182 | Set a custom exception handler, which will be called if any of the | |
1179 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1183 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1180 | runcode() method. |
|
1184 | runcode() method. | |
1181 |
|
1185 | |||
1182 | Inputs: |
|
1186 | Inputs: | |
1183 |
|
1187 | |||
1184 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1188 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1185 | handler for. It is very important that you use a tuple, and NOT A |
|
1189 | handler for. It is very important that you use a tuple, and NOT A | |
1186 | LIST here, because of the way Python's except statement works. If |
|
1190 | LIST here, because of the way Python's except statement works. If | |
1187 | you only want to trap a single exception, use a singleton tuple: |
|
1191 | you only want to trap a single exception, use a singleton tuple: | |
1188 |
|
1192 | |||
1189 | exc_tuple == (MyCustomException,) |
|
1193 | exc_tuple == (MyCustomException,) | |
1190 |
|
1194 | |||
1191 | - handler: this must be defined as a function with the following |
|
1195 | - handler: this must be defined as a function with the following | |
1192 | basic interface: def my_handler(self,etype,value,tb). |
|
1196 | basic interface: def my_handler(self,etype,value,tb). | |
1193 |
|
1197 | |||
1194 | This will be made into an instance method (via new.instancemethod) |
|
1198 | This will be made into an instance method (via new.instancemethod) | |
1195 | of IPython itself, and it will be called if any of the exceptions |
|
1199 | of IPython itself, and it will be called if any of the exceptions | |
1196 | listed in the exc_tuple are caught. If the handler is None, an |
|
1200 | listed in the exc_tuple are caught. If the handler is None, an | |
1197 | internal basic one is used, which just prints basic info. |
|
1201 | internal basic one is used, which just prints basic info. | |
1198 |
|
1202 | |||
1199 | WARNING: by putting in your own exception handler into IPython's main |
|
1203 | WARNING: by putting in your own exception handler into IPython's main | |
1200 | execution loop, you run a very good chance of nasty crashes. This |
|
1204 | execution loop, you run a very good chance of nasty crashes. This | |
1201 | facility should only be used if you really know what you are doing.""" |
|
1205 | facility should only be used if you really know what you are doing.""" | |
1202 |
|
1206 | |||
1203 | assert type(exc_tuple)==type(()) , \ |
|
1207 | assert type(exc_tuple)==type(()) , \ | |
1204 | "The custom exceptions must be given AS A TUPLE." |
|
1208 | "The custom exceptions must be given AS A TUPLE." | |
1205 |
|
1209 | |||
1206 | def dummy_handler(self,etype,value,tb): |
|
1210 | def dummy_handler(self,etype,value,tb): | |
1207 | print '*** Simple custom exception handler ***' |
|
1211 | print '*** Simple custom exception handler ***' | |
1208 | print 'Exception type :',etype |
|
1212 | print 'Exception type :',etype | |
1209 | print 'Exception value:',value |
|
1213 | print 'Exception value:',value | |
1210 | print 'Traceback :',tb |
|
1214 | print 'Traceback :',tb | |
1211 | print 'Source code :','\n'.join(self.buffer) |
|
1215 | print 'Source code :','\n'.join(self.buffer) | |
1212 |
|
1216 | |||
1213 | if handler is None: handler = dummy_handler |
|
1217 | if handler is None: handler = dummy_handler | |
1214 |
|
1218 | |||
1215 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1219 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1216 | self.custom_exceptions = exc_tuple |
|
1220 | self.custom_exceptions = exc_tuple | |
1217 |
|
1221 | |||
1218 | def excepthook(self, etype, value, tb): |
|
1222 | def excepthook(self, etype, value, tb): | |
1219 | """One more defense for GUI apps that call sys.excepthook. |
|
1223 | """One more defense for GUI apps that call sys.excepthook. | |
1220 |
|
1224 | |||
1221 | GUI frameworks like wxPython trap exceptions and call |
|
1225 | GUI frameworks like wxPython trap exceptions and call | |
1222 | sys.excepthook themselves. I guess this is a feature that |
|
1226 | sys.excepthook themselves. I guess this is a feature that | |
1223 | enables them to keep running after exceptions that would |
|
1227 | enables them to keep running after exceptions that would | |
1224 | otherwise kill their mainloop. This is a bother for IPython |
|
1228 | otherwise kill their mainloop. This is a bother for IPython | |
1225 | which excepts to catch all of the program exceptions with a try: |
|
1229 | which excepts to catch all of the program exceptions with a try: | |
1226 | except: statement. |
|
1230 | except: statement. | |
1227 |
|
1231 | |||
1228 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1232 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1229 | any app directly invokes sys.excepthook, it will look to the user like |
|
1233 | any app directly invokes sys.excepthook, it will look to the user like | |
1230 | IPython crashed. In order to work around this, we can disable the |
|
1234 | IPython crashed. In order to work around this, we can disable the | |
1231 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1235 | CrashHandler and replace it with this excepthook instead, which prints a | |
1232 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1236 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1233 | call sys.excepthook will generate a regular-looking exception from |
|
1237 | call sys.excepthook will generate a regular-looking exception from | |
1234 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1238 | IPython, and the CrashHandler will only be triggered by real IPython | |
1235 | crashes. |
|
1239 | crashes. | |
1236 |
|
1240 | |||
1237 | This hook should be used sparingly, only in places which are not likely |
|
1241 | This hook should be used sparingly, only in places which are not likely | |
1238 | to be true IPython errors. |
|
1242 | to be true IPython errors. | |
1239 | """ |
|
1243 | """ | |
1240 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1244 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1241 |
|
1245 | |||
1242 |
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None |
|
1246 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
|
1247 | exception_only=False): | |||
1243 | """Display the exception that just occurred. |
|
1248 | """Display the exception that just occurred. | |
1244 |
|
1249 | |||
1245 | If nothing is known about the exception, this is the method which |
|
1250 | If nothing is known about the exception, this is the method which | |
1246 | should be used throughout the code for presenting user tracebacks, |
|
1251 | should be used throughout the code for presenting user tracebacks, | |
1247 | rather than directly invoking the InteractiveTB object. |
|
1252 | rather than directly invoking the InteractiveTB object. | |
1248 |
|
1253 | |||
1249 | A specific showsyntaxerror() also exists, but this method can take |
|
1254 | A specific showsyntaxerror() also exists, but this method can take | |
1250 | care of calling it if needed, so unless you are explicitly catching a |
|
1255 | care of calling it if needed, so unless you are explicitly catching a | |
1251 | SyntaxError exception, don't try to analyze the stack manually and |
|
1256 | SyntaxError exception, don't try to analyze the stack manually and | |
1252 | simply call this method.""" |
|
1257 | simply call this method.""" | |
1253 |
|
||||
1254 |
|
||||
1255 | # Though this won't be called by syntax errors in the input line, |
|
|||
1256 | # there may be SyntaxError cases whith imported code. |
|
|||
1257 |
|
1258 | |||
1258 | try: |
|
1259 | try: | |
1259 | if exc_tuple is None: |
|
1260 | if exc_tuple is None: | |
1260 | etype, value, tb = sys.exc_info() |
|
1261 | etype, value, tb = sys.exc_info() | |
1261 | else: |
|
1262 | else: | |
1262 | etype, value, tb = exc_tuple |
|
1263 | etype, value, tb = exc_tuple | |
|
1264 | ||||
|
1265 | if etype is None: | |||
|
1266 | if hasattr(sys, 'last_type'): | |||
|
1267 | etype, value, tb = sys.last_type, sys.last_value, \ | |||
|
1268 | sys.last_traceback | |||
|
1269 | else: | |||
|
1270 | self.write('No traceback available to show.\n') | |||
|
1271 | return | |||
1263 |
|
1272 | |||
1264 | if etype is SyntaxError: |
|
1273 | if etype is SyntaxError: | |
|
1274 | # Though this won't be called by syntax errors in the input | |||
|
1275 | # line, there may be SyntaxError cases whith imported code. | |||
1265 | self.showsyntaxerror(filename) |
|
1276 | self.showsyntaxerror(filename) | |
1266 | elif etype is UsageError: |
|
1277 | elif etype is UsageError: | |
1267 | print "UsageError:", value |
|
1278 | print "UsageError:", value | |
1268 | else: |
|
1279 | else: | |
1269 | # WARNING: these variables are somewhat deprecated and not |
|
1280 | # WARNING: these variables are somewhat deprecated and not | |
1270 | # necessarily safe to use in a threaded environment, but tools |
|
1281 | # necessarily safe to use in a threaded environment, but tools | |
1271 | # like pdb depend on their existence, so let's set them. If we |
|
1282 | # like pdb depend on their existence, so let's set them. If we | |
1272 | # find problems in the field, we'll need to revisit their use. |
|
1283 | # find problems in the field, we'll need to revisit their use. | |
1273 | sys.last_type = etype |
|
1284 | sys.last_type = etype | |
1274 | sys.last_value = value |
|
1285 | sys.last_value = value | |
1275 | sys.last_traceback = tb |
|
1286 | sys.last_traceback = tb | |
1276 |
|
1287 | |||
1277 | if etype in self.custom_exceptions: |
|
1288 | if etype in self.custom_exceptions: | |
1278 | self.CustomTB(etype,value,tb) |
|
1289 | self.CustomTB(etype,value,tb) | |
1279 | else: |
|
1290 | else: | |
1280 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1291 | if exception_only: | |
1281 | if self.InteractiveTB.call_pdb and self.has_readline: |
|
1292 | m = ('An exception has occurred, use %tb to see the ' | |
1282 |
|
|
1293 | 'full traceback.') | |
1283 |
|
|
1294 | print m | |
|
1295 | self.InteractiveTB.show_exception_only(etype, value) | |||
|
1296 | else: | |||
|
1297 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |||
|
1298 | if self.InteractiveTB.call_pdb: | |||
|
1299 | # pdb mucks up readline, fix it back | |||
|
1300 | self.set_completer() | |||
|
1301 | ||||
1284 | except KeyboardInterrupt: |
|
1302 | except KeyboardInterrupt: | |
1285 | self.write("\nKeyboardInterrupt\n") |
|
1303 | self.write("\nKeyboardInterrupt\n") | |
|
1304 | ||||
1286 |
|
1305 | |||
1287 | def showsyntaxerror(self, filename=None): |
|
1306 | def showsyntaxerror(self, filename=None): | |
1288 | """Display the syntax error that just occurred. |
|
1307 | """Display the syntax error that just occurred. | |
1289 |
|
1308 | |||
1290 | This doesn't display a stack trace because there isn't one. |
|
1309 | This doesn't display a stack trace because there isn't one. | |
1291 |
|
1310 | |||
1292 | If a filename is given, it is stuffed in the exception instead |
|
1311 | If a filename is given, it is stuffed in the exception instead | |
1293 | of what was there before (because Python's parser always uses |
|
1312 | of what was there before (because Python's parser always uses | |
1294 | "<string>" when reading from a string). |
|
1313 | "<string>" when reading from a string). | |
1295 | """ |
|
1314 | """ | |
1296 | etype, value, last_traceback = sys.exc_info() |
|
1315 | etype, value, last_traceback = sys.exc_info() | |
1297 |
|
1316 | |||
1298 |
# See note about these variables in showtraceback() |
|
1317 | # See note about these variables in showtraceback() above | |
1299 | sys.last_type = etype |
|
1318 | sys.last_type = etype | |
1300 | sys.last_value = value |
|
1319 | sys.last_value = value | |
1301 | sys.last_traceback = last_traceback |
|
1320 | sys.last_traceback = last_traceback | |
1302 |
|
1321 | |||
1303 | if filename and etype is SyntaxError: |
|
1322 | if filename and etype is SyntaxError: | |
1304 | # Work hard to stuff the correct filename in the exception |
|
1323 | # Work hard to stuff the correct filename in the exception | |
1305 | try: |
|
1324 | try: | |
1306 | msg, (dummy_filename, lineno, offset, line) = value |
|
1325 | msg, (dummy_filename, lineno, offset, line) = value | |
1307 | except: |
|
1326 | except: | |
1308 | # Not the format we expect; leave it alone |
|
1327 | # Not the format we expect; leave it alone | |
1309 | pass |
|
1328 | pass | |
1310 | else: |
|
1329 | else: | |
1311 | # Stuff in the right filename |
|
1330 | # Stuff in the right filename | |
1312 | try: |
|
1331 | try: | |
1313 | # Assume SyntaxError is a class exception |
|
1332 | # Assume SyntaxError is a class exception | |
1314 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1333 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1315 | except: |
|
1334 | except: | |
1316 | # If that failed, assume SyntaxError is a string |
|
1335 | # If that failed, assume SyntaxError is a string | |
1317 | value = msg, (filename, lineno, offset, line) |
|
1336 | value = msg, (filename, lineno, offset, line) | |
1318 | self.SyntaxTB(etype,value,[]) |
|
1337 | self.SyntaxTB(etype,value,[]) | |
1319 |
|
1338 | |||
1320 | def edit_syntax_error(self): |
|
1339 | def edit_syntax_error(self): | |
1321 | """The bottom half of the syntax error handler called in the main loop. |
|
1340 | """The bottom half of the syntax error handler called in the main loop. | |
1322 |
|
1341 | |||
1323 | Loop until syntax error is fixed or user cancels. |
|
1342 | Loop until syntax error is fixed or user cancels. | |
1324 | """ |
|
1343 | """ | |
1325 |
|
1344 | |||
1326 | while self.SyntaxTB.last_syntax_error: |
|
1345 | while self.SyntaxTB.last_syntax_error: | |
1327 | # copy and clear last_syntax_error |
|
1346 | # copy and clear last_syntax_error | |
1328 | err = self.SyntaxTB.clear_err_state() |
|
1347 | err = self.SyntaxTB.clear_err_state() | |
1329 | if not self._should_recompile(err): |
|
1348 | if not self._should_recompile(err): | |
1330 | return |
|
1349 | return | |
1331 | try: |
|
1350 | try: | |
1332 | # may set last_syntax_error again if a SyntaxError is raised |
|
1351 | # may set last_syntax_error again if a SyntaxError is raised | |
1333 | self.safe_execfile(err.filename,self.user_ns) |
|
1352 | self.safe_execfile(err.filename,self.user_ns) | |
1334 | except: |
|
1353 | except: | |
1335 | self.showtraceback() |
|
1354 | self.showtraceback() | |
1336 | else: |
|
1355 | else: | |
1337 | try: |
|
1356 | try: | |
1338 | f = file(err.filename) |
|
1357 | f = file(err.filename) | |
1339 | try: |
|
1358 | try: | |
1340 | # This should be inside a display_trap block and I |
|
1359 | # This should be inside a display_trap block and I | |
1341 | # think it is. |
|
1360 | # think it is. | |
1342 | sys.displayhook(f.read()) |
|
1361 | sys.displayhook(f.read()) | |
1343 | finally: |
|
1362 | finally: | |
1344 | f.close() |
|
1363 | f.close() | |
1345 | except: |
|
1364 | except: | |
1346 | self.showtraceback() |
|
1365 | self.showtraceback() | |
1347 |
|
1366 | |||
1348 | def _should_recompile(self,e): |
|
1367 | def _should_recompile(self,e): | |
1349 | """Utility routine for edit_syntax_error""" |
|
1368 | """Utility routine for edit_syntax_error""" | |
1350 |
|
1369 | |||
1351 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1370 | if e.filename in ('<ipython console>','<input>','<string>', | |
1352 | '<console>','<BackgroundJob compilation>', |
|
1371 | '<console>','<BackgroundJob compilation>', | |
1353 | None): |
|
1372 | None): | |
1354 |
|
1373 | |||
1355 | return False |
|
1374 | return False | |
1356 | try: |
|
1375 | try: | |
1357 | if (self.autoedit_syntax and |
|
1376 | if (self.autoedit_syntax and | |
1358 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1377 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
1359 | '[Y/n] ','y')): |
|
1378 | '[Y/n] ','y')): | |
1360 | return False |
|
1379 | return False | |
1361 | except EOFError: |
|
1380 | except EOFError: | |
1362 | return False |
|
1381 | return False | |
1363 |
|
1382 | |||
1364 | def int0(x): |
|
1383 | def int0(x): | |
1365 | try: |
|
1384 | try: | |
1366 | return int(x) |
|
1385 | return int(x) | |
1367 | except TypeError: |
|
1386 | except TypeError: | |
1368 | return 0 |
|
1387 | return 0 | |
1369 | # always pass integer line and offset values to editor hook |
|
1388 | # always pass integer line and offset values to editor hook | |
1370 | try: |
|
1389 | try: | |
1371 | self.hooks.fix_error_editor(e.filename, |
|
1390 | self.hooks.fix_error_editor(e.filename, | |
1372 | int0(e.lineno),int0(e.offset),e.msg) |
|
1391 | int0(e.lineno),int0(e.offset),e.msg) | |
1373 | except TryNext: |
|
1392 | except TryNext: | |
1374 | warn('Could not open editor') |
|
1393 | warn('Could not open editor') | |
1375 | return False |
|
1394 | return False | |
1376 | return True |
|
1395 | return True | |
1377 |
|
1396 | |||
1378 | #------------------------------------------------------------------------- |
|
1397 | #------------------------------------------------------------------------- | |
1379 | # Things related to tab completion |
|
1398 | # Things related to tab completion | |
1380 | #------------------------------------------------------------------------- |
|
1399 | #------------------------------------------------------------------------- | |
1381 |
|
1400 | |||
1382 | def complete(self, text): |
|
1401 | def complete(self, text): | |
1383 | """Return a sorted list of all possible completions on text. |
|
1402 | """Return a sorted list of all possible completions on text. | |
1384 |
|
1403 | |||
1385 | Inputs: |
|
1404 | Inputs: | |
1386 |
|
1405 | |||
1387 | - text: a string of text to be completed on. |
|
1406 | - text: a string of text to be completed on. | |
1388 |
|
1407 | |||
1389 | This is a wrapper around the completion mechanism, similar to what |
|
1408 | This is a wrapper around the completion mechanism, similar to what | |
1390 | readline does at the command line when the TAB key is hit. By |
|
1409 | readline does at the command line when the TAB key is hit. By | |
1391 | exposing it as a method, it can be used by other non-readline |
|
1410 | exposing it as a method, it can be used by other non-readline | |
1392 | environments (such as GUIs) for text completion. |
|
1411 | environments (such as GUIs) for text completion. | |
1393 |
|
1412 | |||
1394 | Simple usage example: |
|
1413 | Simple usage example: | |
1395 |
|
1414 | |||
1396 | In [7]: x = 'hello' |
|
1415 | In [7]: x = 'hello' | |
1397 |
|
1416 | |||
1398 | In [8]: x |
|
1417 | In [8]: x | |
1399 | Out[8]: 'hello' |
|
1418 | Out[8]: 'hello' | |
1400 |
|
1419 | |||
1401 | In [9]: print x |
|
1420 | In [9]: print x | |
1402 | hello |
|
1421 | hello | |
1403 |
|
1422 | |||
1404 | In [10]: _ip.complete('x.l') |
|
1423 | In [10]: _ip.complete('x.l') | |
1405 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1424 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] | |
1406 | """ |
|
1425 | """ | |
1407 |
|
1426 | |||
1408 | # Inject names into __builtin__ so we can complete on the added names. |
|
1427 | # Inject names into __builtin__ so we can complete on the added names. | |
1409 | with self.builtin_trap: |
|
1428 | with self.builtin_trap: | |
1410 | complete = self.Completer.complete |
|
1429 | complete = self.Completer.complete | |
1411 | state = 0 |
|
1430 | state = 0 | |
1412 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1431 | # use a dict so we get unique keys, since ipyhton's multiple | |
1413 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1432 | # completers can return duplicates. When we make 2.4 a requirement, | |
1414 | # start using sets instead, which are faster. |
|
1433 | # start using sets instead, which are faster. | |
1415 | comps = {} |
|
1434 | comps = {} | |
1416 | while True: |
|
1435 | while True: | |
1417 | newcomp = complete(text,state,line_buffer=text) |
|
1436 | newcomp = complete(text,state,line_buffer=text) | |
1418 | if newcomp is None: |
|
1437 | if newcomp is None: | |
1419 | break |
|
1438 | break | |
1420 | comps[newcomp] = 1 |
|
1439 | comps[newcomp] = 1 | |
1421 | state += 1 |
|
1440 | state += 1 | |
1422 | outcomps = comps.keys() |
|
1441 | outcomps = comps.keys() | |
1423 | outcomps.sort() |
|
1442 | outcomps.sort() | |
1424 | #print "T:",text,"OC:",outcomps # dbg |
|
1443 | #print "T:",text,"OC:",outcomps # dbg | |
1425 | #print "vars:",self.user_ns.keys() |
|
1444 | #print "vars:",self.user_ns.keys() | |
1426 | return outcomps |
|
1445 | return outcomps | |
1427 |
|
1446 | |||
1428 | def set_custom_completer(self,completer,pos=0): |
|
1447 | def set_custom_completer(self,completer,pos=0): | |
1429 |
""" |
|
1448 | """Adds a new custom completer function. | |
1430 |
|
||||
1431 | Adds a new custom completer function. |
|
|||
1432 |
|
1449 | |||
1433 | The position argument (defaults to 0) is the index in the completers |
|
1450 | The position argument (defaults to 0) is the index in the completers | |
1434 | list where you want the completer to be inserted.""" |
|
1451 | list where you want the completer to be inserted.""" | |
1435 |
|
1452 | |||
1436 | newcomp = new.instancemethod(completer,self.Completer, |
|
1453 | newcomp = new.instancemethod(completer,self.Completer, | |
1437 | self.Completer.__class__) |
|
1454 | self.Completer.__class__) | |
1438 | self.Completer.matchers.insert(pos,newcomp) |
|
1455 | self.Completer.matchers.insert(pos,newcomp) | |
1439 |
|
1456 | |||
1440 | def set_completer(self): |
|
1457 | def set_completer(self): | |
1441 |
""" |
|
1458 | """Reset readline's completer to be our own.""" | |
1442 | self.readline.set_completer(self.Completer.complete) |
|
1459 | self.readline.set_completer(self.Completer.complete) | |
1443 |
|
1460 | |||
|
1461 | def set_completer_frame(self, frame=None): | |||
|
1462 | """Set the frame of the completer.""" | |||
|
1463 | if frame: | |||
|
1464 | self.Completer.namespace = frame.f_locals | |||
|
1465 | self.Completer.global_namespace = frame.f_globals | |||
|
1466 | else: | |||
|
1467 | self.Completer.namespace = self.user_ns | |||
|
1468 | self.Completer.global_namespace = self.user_global_ns | |||
|
1469 | ||||
1444 | #------------------------------------------------------------------------- |
|
1470 | #------------------------------------------------------------------------- | |
1445 | # Things related to readline |
|
1471 | # Things related to readline | |
1446 | #------------------------------------------------------------------------- |
|
1472 | #------------------------------------------------------------------------- | |
1447 |
|
1473 | |||
1448 | def init_readline(self): |
|
1474 | def init_readline(self): | |
1449 | """Command history completion/saving/reloading.""" |
|
1475 | """Command history completion/saving/reloading.""" | |
1450 |
|
1476 | |||
|
1477 | if self.readline_use: | |||
|
1478 | import IPython.utils.rlineimpl as readline | |||
|
1479 | ||||
1451 | self.rl_next_input = None |
|
1480 | self.rl_next_input = None | |
1452 | self.rl_do_indent = False |
|
1481 | self.rl_do_indent = False | |
1453 |
|
1482 | |||
1454 | if not self.readline_use: |
|
1483 | if not self.readline_use or not readline.have_readline: | |
1455 | return |
|
1484 | self.has_readline = False | |
1456 |
|
||||
1457 | import IPython.utils.rlineimpl as readline |
|
|||
1458 |
|
||||
1459 | if not readline.have_readline: |
|
|||
1460 | self.has_readline = 0 |
|
|||
1461 | self.readline = None |
|
1485 | self.readline = None | |
1462 | # no point in bugging windows users with this every time: |
|
1486 | # Set a number of methods that depend on readline to be no-op | |
1463 | warn('Readline services not available on this platform.') |
|
1487 | self.savehist = no_op | |
|
1488 | self.reloadhist = no_op | |||
|
1489 | self.set_completer = no_op | |||
|
1490 | self.set_custom_completer = no_op | |||
|
1491 | self.set_completer_frame = no_op | |||
|
1492 | warn('Readline services not available or not loaded.') | |||
1464 | else: |
|
1493 | else: | |
|
1494 | self.has_readline = True | |||
|
1495 | self.readline = readline | |||
1465 | sys.modules['readline'] = readline |
|
1496 | sys.modules['readline'] = readline | |
1466 | import atexit |
|
1497 | import atexit | |
1467 | from IPython.core.completer import IPCompleter |
|
1498 | from IPython.core.completer import IPCompleter | |
1468 | self.Completer = IPCompleter(self, |
|
1499 | self.Completer = IPCompleter(self, | |
1469 | self.user_ns, |
|
1500 | self.user_ns, | |
1470 | self.user_global_ns, |
|
1501 | self.user_global_ns, | |
1471 | self.readline_omit__names, |
|
1502 | self.readline_omit__names, | |
1472 | self.alias_manager.alias_table) |
|
1503 | self.alias_manager.alias_table) | |
1473 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1504 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1474 | self.strdispatchers['complete_command'] = sdisp |
|
1505 | self.strdispatchers['complete_command'] = sdisp | |
1475 | self.Completer.custom_completers = sdisp |
|
1506 | self.Completer.custom_completers = sdisp | |
1476 | # Platform-specific configuration |
|
1507 | # Platform-specific configuration | |
1477 | if os.name == 'nt': |
|
1508 | if os.name == 'nt': | |
1478 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1509 | self.readline_startup_hook = readline.set_pre_input_hook | |
1479 | else: |
|
1510 | else: | |
1480 | self.readline_startup_hook = readline.set_startup_hook |
|
1511 | self.readline_startup_hook = readline.set_startup_hook | |
1481 |
|
1512 | |||
1482 | # Load user's initrc file (readline config) |
|
1513 | # Load user's initrc file (readline config) | |
1483 | # Or if libedit is used, load editrc. |
|
1514 | # Or if libedit is used, load editrc. | |
1484 | inputrc_name = os.environ.get('INPUTRC') |
|
1515 | inputrc_name = os.environ.get('INPUTRC') | |
1485 | if inputrc_name is None: |
|
1516 | if inputrc_name is None: | |
1486 | home_dir = get_home_dir() |
|
1517 | home_dir = get_home_dir() | |
1487 | if home_dir is not None: |
|
1518 | if home_dir is not None: | |
1488 | inputrc_name = '.inputrc' |
|
1519 | inputrc_name = '.inputrc' | |
1489 | if readline.uses_libedit: |
|
1520 | if readline.uses_libedit: | |
1490 | inputrc_name = '.editrc' |
|
1521 | inputrc_name = '.editrc' | |
1491 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1522 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1492 | if os.path.isfile(inputrc_name): |
|
1523 | if os.path.isfile(inputrc_name): | |
1493 | try: |
|
1524 | try: | |
1494 | readline.read_init_file(inputrc_name) |
|
1525 | readline.read_init_file(inputrc_name) | |
1495 | except: |
|
1526 | except: | |
1496 | warn('Problems reading readline initialization file <%s>' |
|
1527 | warn('Problems reading readline initialization file <%s>' | |
1497 | % inputrc_name) |
|
1528 | % inputrc_name) | |
1498 |
|
1529 | |||
1499 | self.has_readline = 1 |
|
|||
1500 | self.readline = readline |
|
|||
1501 | # save this in sys so embedded copies can restore it properly |
|
1530 | # save this in sys so embedded copies can restore it properly | |
1502 | sys.ipcompleter = self.Completer.complete |
|
1531 | sys.ipcompleter = self.Completer.complete | |
1503 | self.set_completer() |
|
1532 | self.set_completer() | |
1504 |
|
1533 | |||
1505 | # Configure readline according to user's prefs |
|
1534 | # Configure readline according to user's prefs | |
1506 | # This is only done if GNU readline is being used. If libedit |
|
1535 | # This is only done if GNU readline is being used. If libedit | |
1507 | # is being used (as on Leopard) the readline config is |
|
1536 | # is being used (as on Leopard) the readline config is | |
1508 | # not run as the syntax for libedit is different. |
|
1537 | # not run as the syntax for libedit is different. | |
1509 | if not readline.uses_libedit: |
|
1538 | if not readline.uses_libedit: | |
1510 | for rlcommand in self.readline_parse_and_bind: |
|
1539 | for rlcommand in self.readline_parse_and_bind: | |
1511 | #print "loading rl:",rlcommand # dbg |
|
1540 | #print "loading rl:",rlcommand # dbg | |
1512 | readline.parse_and_bind(rlcommand) |
|
1541 | readline.parse_and_bind(rlcommand) | |
1513 |
|
1542 | |||
1514 | # Remove some chars from the delimiters list. If we encounter |
|
1543 | # Remove some chars from the delimiters list. If we encounter | |
1515 | # unicode chars, discard them. |
|
1544 | # unicode chars, discard them. | |
1516 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1545 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1517 | delims = delims.translate(string._idmap, |
|
1546 | delims = delims.translate(string._idmap, | |
1518 | self.readline_remove_delims) |
|
1547 | self.readline_remove_delims) | |
1519 | readline.set_completer_delims(delims) |
|
1548 | readline.set_completer_delims(delims) | |
1520 | # otherwise we end up with a monster history after a while: |
|
1549 | # otherwise we end up with a monster history after a while: | |
1521 | readline.set_history_length(1000) |
|
1550 | readline.set_history_length(1000) | |
1522 | try: |
|
1551 | try: | |
1523 | #print '*** Reading readline history' # dbg |
|
1552 | #print '*** Reading readline history' # dbg | |
1524 | readline.read_history_file(self.histfile) |
|
1553 | readline.read_history_file(self.histfile) | |
1525 | except IOError: |
|
1554 | except IOError: | |
1526 | pass # It doesn't exist yet. |
|
1555 | pass # It doesn't exist yet. | |
1527 |
|
1556 | |||
1528 | atexit.register(self.atexit_operations) |
|
1557 | atexit.register(self.atexit_operations) | |
1529 | del atexit |
|
1558 | del atexit | |
1530 |
|
1559 | |||
1531 | # Configure auto-indent for all platforms |
|
1560 | # Configure auto-indent for all platforms | |
1532 | self.set_autoindent(self.autoindent) |
|
1561 | self.set_autoindent(self.autoindent) | |
1533 |
|
1562 | |||
1534 | def set_next_input(self, s): |
|
1563 | def set_next_input(self, s): | |
1535 | """ Sets the 'default' input string for the next command line. |
|
1564 | """ Sets the 'default' input string for the next command line. | |
1536 |
|
1565 | |||
1537 | Requires readline. |
|
1566 | Requires readline. | |
1538 |
|
1567 | |||
1539 | Example: |
|
1568 | Example: | |
1540 |
|
1569 | |||
1541 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1570 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1542 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1571 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1543 | """ |
|
1572 | """ | |
1544 |
|
1573 | |||
1545 | self.rl_next_input = s |
|
1574 | self.rl_next_input = s | |
1546 |
|
1575 | |||
1547 | def pre_readline(self): |
|
1576 | def pre_readline(self): | |
1548 | """readline hook to be used at the start of each line. |
|
1577 | """readline hook to be used at the start of each line. | |
1549 |
|
1578 | |||
1550 | Currently it handles auto-indent only.""" |
|
1579 | Currently it handles auto-indent only.""" | |
1551 |
|
1580 | |||
1552 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1581 | #debugx('self.indent_current_nsp','pre_readline:') | |
1553 |
|
1582 | |||
1554 | if self.rl_do_indent: |
|
1583 | if self.rl_do_indent: | |
1555 | self.readline.insert_text(self._indent_current_str()) |
|
1584 | self.readline.insert_text(self._indent_current_str()) | |
1556 | if self.rl_next_input is not None: |
|
1585 | if self.rl_next_input is not None: | |
1557 | self.readline.insert_text(self.rl_next_input) |
|
1586 | self.readline.insert_text(self.rl_next_input) | |
1558 | self.rl_next_input = None |
|
1587 | self.rl_next_input = None | |
1559 |
|
1588 | |||
1560 | def _indent_current_str(self): |
|
1589 | def _indent_current_str(self): | |
1561 | """return the current level of indentation as a string""" |
|
1590 | """return the current level of indentation as a string""" | |
1562 | return self.indent_current_nsp * ' ' |
|
1591 | return self.indent_current_nsp * ' ' | |
1563 |
|
1592 | |||
1564 | #------------------------------------------------------------------------- |
|
1593 | #------------------------------------------------------------------------- | |
1565 | # Things related to magics |
|
1594 | # Things related to magics | |
1566 | #------------------------------------------------------------------------- |
|
1595 | #------------------------------------------------------------------------- | |
1567 |
|
1596 | |||
1568 | def init_magics(self): |
|
1597 | def init_magics(self): | |
1569 | # Set user colors (don't do it in the constructor above so that it |
|
1598 | # Set user colors (don't do it in the constructor above so that it | |
1570 | # doesn't crash if colors option is invalid) |
|
1599 | # doesn't crash if colors option is invalid) | |
1571 | self.magic_colors(self.colors) |
|
1600 | self.magic_colors(self.colors) | |
|
1601 | # History was moved to a separate module | |||
|
1602 | from . import history | |||
|
1603 | history.init_ipython(self) | |||
1572 |
|
1604 | |||
1573 | def magic(self,arg_s): |
|
1605 | def magic(self,arg_s): | |
1574 | """Call a magic function by name. |
|
1606 | """Call a magic function by name. | |
1575 |
|
1607 | |||
1576 | Input: a string containing the name of the magic function to call and any |
|
1608 | Input: a string containing the name of the magic function to call and any | |
1577 | additional arguments to be passed to the magic. |
|
1609 | additional arguments to be passed to the magic. | |
1578 |
|
1610 | |||
1579 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1611 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1580 | prompt: |
|
1612 | prompt: | |
1581 |
|
1613 | |||
1582 | In[1]: %name -opt foo bar |
|
1614 | In[1]: %name -opt foo bar | |
1583 |
|
1615 | |||
1584 | To call a magic without arguments, simply use magic('name'). |
|
1616 | To call a magic without arguments, simply use magic('name'). | |
1585 |
|
1617 | |||
1586 | This provides a proper Python function to call IPython's magics in any |
|
1618 | This provides a proper Python function to call IPython's magics in any | |
1587 | valid Python code you can type at the interpreter, including loops and |
|
1619 | valid Python code you can type at the interpreter, including loops and | |
1588 | compound statements. |
|
1620 | compound statements. | |
1589 | """ |
|
1621 | """ | |
1590 |
|
||||
1591 | args = arg_s.split(' ',1) |
|
1622 | args = arg_s.split(' ',1) | |
1592 | magic_name = args[0] |
|
1623 | magic_name = args[0] | |
1593 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1624 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1594 |
|
1625 | |||
1595 | try: |
|
1626 | try: | |
1596 | magic_args = args[1] |
|
1627 | magic_args = args[1] | |
1597 | except IndexError: |
|
1628 | except IndexError: | |
1598 | magic_args = '' |
|
1629 | magic_args = '' | |
1599 | fn = getattr(self,'magic_'+magic_name,None) |
|
1630 | fn = getattr(self,'magic_'+magic_name,None) | |
1600 | if fn is None: |
|
1631 | if fn is None: | |
1601 | error("Magic function `%s` not found." % magic_name) |
|
1632 | error("Magic function `%s` not found." % magic_name) | |
1602 | else: |
|
1633 | else: | |
1603 | magic_args = self.var_expand(magic_args,1) |
|
1634 | magic_args = self.var_expand(magic_args,1) | |
1604 | with nested(self.builtin_trap,): |
|
1635 | with nested(self.builtin_trap,): | |
1605 | result = fn(magic_args) |
|
1636 | result = fn(magic_args) | |
1606 | return result |
|
1637 | return result | |
1607 |
|
1638 | |||
1608 | def define_magic(self, magicname, func): |
|
1639 | def define_magic(self, magicname, func): | |
1609 | """Expose own function as magic function for ipython |
|
1640 | """Expose own function as magic function for ipython | |
1610 |
|
1641 | |||
1611 | def foo_impl(self,parameter_s=''): |
|
1642 | def foo_impl(self,parameter_s=''): | |
1612 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1643 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1613 | print 'Magic function. Passed parameter is between < >:' |
|
1644 | print 'Magic function. Passed parameter is between < >:' | |
1614 | print '<%s>' % parameter_s |
|
1645 | print '<%s>' % parameter_s | |
1615 | print 'The self object is:',self |
|
1646 | print 'The self object is:',self | |
1616 |
|
1647 | |||
1617 | self.define_magic('foo',foo_impl) |
|
1648 | self.define_magic('foo',foo_impl) | |
1618 | """ |
|
1649 | """ | |
1619 |
|
1650 | |||
1620 | import new |
|
1651 | import new | |
1621 | im = new.instancemethod(func,self, self.__class__) |
|
1652 | im = new.instancemethod(func,self, self.__class__) | |
1622 | old = getattr(self, "magic_" + magicname, None) |
|
1653 | old = getattr(self, "magic_" + magicname, None) | |
1623 | setattr(self, "magic_" + magicname, im) |
|
1654 | setattr(self, "magic_" + magicname, im) | |
1624 | return old |
|
1655 | return old | |
1625 |
|
1656 | |||
1626 | #------------------------------------------------------------------------- |
|
1657 | #------------------------------------------------------------------------- | |
1627 | # Things related to macros |
|
1658 | # Things related to macros | |
1628 | #------------------------------------------------------------------------- |
|
1659 | #------------------------------------------------------------------------- | |
1629 |
|
1660 | |||
1630 | def define_macro(self, name, themacro): |
|
1661 | def define_macro(self, name, themacro): | |
1631 | """Define a new macro |
|
1662 | """Define a new macro | |
1632 |
|
1663 | |||
1633 | Parameters |
|
1664 | Parameters | |
1634 | ---------- |
|
1665 | ---------- | |
1635 | name : str |
|
1666 | name : str | |
1636 | The name of the macro. |
|
1667 | The name of the macro. | |
1637 | themacro : str or Macro |
|
1668 | themacro : str or Macro | |
1638 | The action to do upon invoking the macro. If a string, a new |
|
1669 | The action to do upon invoking the macro. If a string, a new | |
1639 | Macro object is created by passing the string to it. |
|
1670 | Macro object is created by passing the string to it. | |
1640 | """ |
|
1671 | """ | |
1641 |
|
1672 | |||
1642 | from IPython.core import macro |
|
1673 | from IPython.core import macro | |
1643 |
|
1674 | |||
1644 | if isinstance(themacro, basestring): |
|
1675 | if isinstance(themacro, basestring): | |
1645 | themacro = macro.Macro(themacro) |
|
1676 | themacro = macro.Macro(themacro) | |
1646 | if not isinstance(themacro, macro.Macro): |
|
1677 | if not isinstance(themacro, macro.Macro): | |
1647 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1678 | raise ValueError('A macro must be a string or a Macro instance.') | |
1648 | self.user_ns[name] = themacro |
|
1679 | self.user_ns[name] = themacro | |
1649 |
|
1680 | |||
1650 | #------------------------------------------------------------------------- |
|
1681 | #------------------------------------------------------------------------- | |
1651 | # Things related to the running of system commands |
|
1682 | # Things related to the running of system commands | |
1652 | #------------------------------------------------------------------------- |
|
1683 | #------------------------------------------------------------------------- | |
1653 |
|
1684 | |||
1654 | def system(self, cmd): |
|
1685 | def system(self, cmd): | |
1655 | """Make a system call, using IPython.""" |
|
1686 | """Make a system call, using IPython.""" | |
1656 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1687 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) | |
1657 |
|
1688 | |||
1658 | #------------------------------------------------------------------------- |
|
1689 | #------------------------------------------------------------------------- | |
1659 | # Things related to aliases |
|
1690 | # Things related to aliases | |
1660 | #------------------------------------------------------------------------- |
|
1691 | #------------------------------------------------------------------------- | |
1661 |
|
1692 | |||
1662 | def init_alias(self): |
|
1693 | def init_alias(self): | |
1663 | self.alias_manager = AliasManager(self, config=self.config) |
|
1694 | self.alias_manager = AliasManager(self, config=self.config) | |
1664 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1695 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1665 |
|
1696 | |||
1666 | #------------------------------------------------------------------------- |
|
1697 | #------------------------------------------------------------------------- | |
1667 | # Things related to the running of code |
|
1698 | # Things related to the running of code | |
1668 | #------------------------------------------------------------------------- |
|
1699 | #------------------------------------------------------------------------- | |
1669 |
|
1700 | |||
1670 | def ex(self, cmd): |
|
1701 | def ex(self, cmd): | |
1671 | """Execute a normal python statement in user namespace.""" |
|
1702 | """Execute a normal python statement in user namespace.""" | |
1672 | with nested(self.builtin_trap,): |
|
1703 | with nested(self.builtin_trap,): | |
1673 | exec cmd in self.user_global_ns, self.user_ns |
|
1704 | exec cmd in self.user_global_ns, self.user_ns | |
1674 |
|
1705 | |||
1675 | def ev(self, expr): |
|
1706 | def ev(self, expr): | |
1676 | """Evaluate python expression expr in user namespace. |
|
1707 | """Evaluate python expression expr in user namespace. | |
1677 |
|
1708 | |||
1678 | Returns the result of evaluation |
|
1709 | Returns the result of evaluation | |
1679 | """ |
|
1710 | """ | |
1680 | with nested(self.builtin_trap,): |
|
1711 | with nested(self.builtin_trap,): | |
1681 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1712 | return eval(expr, self.user_global_ns, self.user_ns) | |
1682 |
|
1713 | |||
1683 | def mainloop(self, display_banner=None): |
|
1714 | def mainloop(self, display_banner=None): | |
1684 | """Start the mainloop. |
|
1715 | """Start the mainloop. | |
1685 |
|
1716 | |||
1686 | If an optional banner argument is given, it will override the |
|
1717 | If an optional banner argument is given, it will override the | |
1687 | internally created default banner. |
|
1718 | internally created default banner. | |
1688 | """ |
|
1719 | """ | |
1689 |
|
1720 | |||
1690 | with nested(self.builtin_trap, self.display_trap): |
|
1721 | with nested(self.builtin_trap, self.display_trap): | |
1691 |
|
1722 | |||
1692 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1723 | # if you run stuff with -c <cmd>, raw hist is not updated | |
1693 | # ensure that it's in sync |
|
1724 | # ensure that it's in sync | |
1694 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1725 | if len(self.input_hist) != len (self.input_hist_raw): | |
1695 | self.input_hist_raw = InputList(self.input_hist) |
|
1726 | self.input_hist_raw = InputList(self.input_hist) | |
1696 |
|
1727 | |||
1697 | while 1: |
|
1728 | while 1: | |
1698 | try: |
|
1729 | try: | |
1699 | self.interact(display_banner=display_banner) |
|
1730 | self.interact(display_banner=display_banner) | |
1700 | #self.interact_with_readline() |
|
1731 | #self.interact_with_readline() | |
1701 | # XXX for testing of a readline-decoupled repl loop, call |
|
1732 | # XXX for testing of a readline-decoupled repl loop, call | |
1702 | # interact_with_readline above |
|
1733 | # interact_with_readline above | |
1703 | break |
|
1734 | break | |
1704 | except KeyboardInterrupt: |
|
1735 | except KeyboardInterrupt: | |
1705 | # this should not be necessary, but KeyboardInterrupt |
|
1736 | # this should not be necessary, but KeyboardInterrupt | |
1706 | # handling seems rather unpredictable... |
|
1737 | # handling seems rather unpredictable... | |
1707 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1738 | self.write("\nKeyboardInterrupt in interact()\n") | |
1708 |
|
1739 | |||
1709 | def interact_prompt(self): |
|
1740 | def interact_prompt(self): | |
1710 | """ Print the prompt (in read-eval-print loop) |
|
1741 | """ Print the prompt (in read-eval-print loop) | |
1711 |
|
1742 | |||
1712 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1743 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1713 | used in standard IPython flow. |
|
1744 | used in standard IPython flow. | |
1714 | """ |
|
1745 | """ | |
1715 | if self.more: |
|
1746 | if self.more: | |
1716 | try: |
|
1747 | try: | |
1717 | prompt = self.hooks.generate_prompt(True) |
|
1748 | prompt = self.hooks.generate_prompt(True) | |
1718 | except: |
|
1749 | except: | |
1719 | self.showtraceback() |
|
1750 | self.showtraceback() | |
1720 | if self.autoindent: |
|
1751 | if self.autoindent: | |
1721 | self.rl_do_indent = True |
|
1752 | self.rl_do_indent = True | |
1722 |
|
1753 | |||
1723 | else: |
|
1754 | else: | |
1724 | try: |
|
1755 | try: | |
1725 | prompt = self.hooks.generate_prompt(False) |
|
1756 | prompt = self.hooks.generate_prompt(False) | |
1726 | except: |
|
1757 | except: | |
1727 | self.showtraceback() |
|
1758 | self.showtraceback() | |
1728 | self.write(prompt) |
|
1759 | self.write(prompt) | |
1729 |
|
1760 | |||
1730 | def interact_handle_input(self,line): |
|
1761 | def interact_handle_input(self,line): | |
1731 | """ Handle the input line (in read-eval-print loop) |
|
1762 | """ Handle the input line (in read-eval-print loop) | |
1732 |
|
1763 | |||
1733 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1764 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
1734 | used in standard IPython flow. |
|
1765 | used in standard IPython flow. | |
1735 | """ |
|
1766 | """ | |
1736 | if line.lstrip() == line: |
|
1767 | if line.lstrip() == line: | |
1737 | self.shadowhist.add(line.strip()) |
|
1768 | self.shadowhist.add(line.strip()) | |
1738 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1769 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) | |
1739 |
|
1770 | |||
1740 | if line.strip(): |
|
1771 | if line.strip(): | |
1741 | if self.more: |
|
1772 | if self.more: | |
1742 | self.input_hist_raw[-1] += '%s\n' % line |
|
1773 | self.input_hist_raw[-1] += '%s\n' % line | |
1743 | else: |
|
1774 | else: | |
1744 | self.input_hist_raw.append('%s\n' % line) |
|
1775 | self.input_hist_raw.append('%s\n' % line) | |
1745 |
|
1776 | |||
1746 |
|
1777 | |||
1747 | self.more = self.push_line(lineout) |
|
1778 | self.more = self.push_line(lineout) | |
1748 | if (self.SyntaxTB.last_syntax_error and |
|
1779 | if (self.SyntaxTB.last_syntax_error and | |
1749 | self.autoedit_syntax): |
|
1780 | self.autoedit_syntax): | |
1750 | self.edit_syntax_error() |
|
1781 | self.edit_syntax_error() | |
1751 |
|
1782 | |||
1752 | def interact_with_readline(self): |
|
1783 | def interact_with_readline(self): | |
1753 | """ Demo of using interact_handle_input, interact_prompt |
|
1784 | """ Demo of using interact_handle_input, interact_prompt | |
1754 |
|
1785 | |||
1755 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1786 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
1756 | it should work like this. |
|
1787 | it should work like this. | |
1757 | """ |
|
1788 | """ | |
1758 | self.readline_startup_hook(self.pre_readline) |
|
1789 | self.readline_startup_hook(self.pre_readline) | |
1759 | while not self.exit_now: |
|
1790 | while not self.exit_now: | |
1760 | self.interact_prompt() |
|
1791 | self.interact_prompt() | |
1761 | if self.more: |
|
1792 | if self.more: | |
1762 | self.rl_do_indent = True |
|
1793 | self.rl_do_indent = True | |
1763 | else: |
|
1794 | else: | |
1764 | self.rl_do_indent = False |
|
1795 | self.rl_do_indent = False | |
1765 | line = raw_input_original().decode(self.stdin_encoding) |
|
1796 | line = raw_input_original().decode(self.stdin_encoding) | |
1766 | self.interact_handle_input(line) |
|
1797 | self.interact_handle_input(line) | |
1767 |
|
1798 | |||
1768 | def interact(self, display_banner=None): |
|
1799 | def interact(self, display_banner=None): | |
1769 | """Closely emulate the interactive Python console.""" |
|
1800 | """Closely emulate the interactive Python console.""" | |
1770 |
|
1801 | |||
1771 | # batch run -> do not interact |
|
1802 | # batch run -> do not interact | |
1772 | if self.exit_now: |
|
1803 | if self.exit_now: | |
1773 | return |
|
1804 | return | |
1774 |
|
1805 | |||
1775 | if display_banner is None: |
|
1806 | if display_banner is None: | |
1776 | display_banner = self.display_banner |
|
1807 | display_banner = self.display_banner | |
1777 | if display_banner: |
|
1808 | if display_banner: | |
1778 | self.show_banner() |
|
1809 | self.show_banner() | |
1779 |
|
1810 | |||
1780 | more = 0 |
|
1811 | more = 0 | |
1781 |
|
1812 | |||
1782 | # Mark activity in the builtins |
|
1813 | # Mark activity in the builtins | |
1783 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1814 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
1784 |
|
1815 | |||
1785 | if self.has_readline: |
|
1816 | if self.has_readline: | |
1786 | self.readline_startup_hook(self.pre_readline) |
|
1817 | self.readline_startup_hook(self.pre_readline) | |
1787 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1818 | # exit_now is set by a call to %Exit or %Quit, through the | |
1788 | # ask_exit callback. |
|
1819 | # ask_exit callback. | |
1789 |
|
1820 | |||
1790 | while not self.exit_now: |
|
1821 | while not self.exit_now: | |
1791 | self.hooks.pre_prompt_hook() |
|
1822 | self.hooks.pre_prompt_hook() | |
1792 | if more: |
|
1823 | if more: | |
1793 | try: |
|
1824 | try: | |
1794 | prompt = self.hooks.generate_prompt(True) |
|
1825 | prompt = self.hooks.generate_prompt(True) | |
1795 | except: |
|
1826 | except: | |
1796 | self.showtraceback() |
|
1827 | self.showtraceback() | |
1797 | if self.autoindent: |
|
1828 | if self.autoindent: | |
1798 | self.rl_do_indent = True |
|
1829 | self.rl_do_indent = True | |
1799 |
|
1830 | |||
1800 | else: |
|
1831 | else: | |
1801 | try: |
|
1832 | try: | |
1802 | prompt = self.hooks.generate_prompt(False) |
|
1833 | prompt = self.hooks.generate_prompt(False) | |
1803 | except: |
|
1834 | except: | |
1804 | self.showtraceback() |
|
1835 | self.showtraceback() | |
1805 | try: |
|
1836 | try: | |
1806 | line = self.raw_input(prompt, more) |
|
1837 | line = self.raw_input(prompt, more) | |
1807 | if self.exit_now: |
|
1838 | if self.exit_now: | |
1808 | # quick exit on sys.std[in|out] close |
|
1839 | # quick exit on sys.std[in|out] close | |
1809 | break |
|
1840 | break | |
1810 | if self.autoindent: |
|
1841 | if self.autoindent: | |
1811 | self.rl_do_indent = False |
|
1842 | self.rl_do_indent = False | |
1812 |
|
1843 | |||
1813 | except KeyboardInterrupt: |
|
1844 | except KeyboardInterrupt: | |
1814 | #double-guard against keyboardinterrupts during kbdint handling |
|
1845 | #double-guard against keyboardinterrupts during kbdint handling | |
1815 | try: |
|
1846 | try: | |
1816 | self.write('\nKeyboardInterrupt\n') |
|
1847 | self.write('\nKeyboardInterrupt\n') | |
1817 | self.resetbuffer() |
|
1848 | self.resetbuffer() | |
1818 | # keep cache in sync with the prompt counter: |
|
1849 | # keep cache in sync with the prompt counter: | |
1819 | self.outputcache.prompt_count -= 1 |
|
1850 | self.outputcache.prompt_count -= 1 | |
1820 |
|
1851 | |||
1821 | if self.autoindent: |
|
1852 | if self.autoindent: | |
1822 | self.indent_current_nsp = 0 |
|
1853 | self.indent_current_nsp = 0 | |
1823 | more = 0 |
|
1854 | more = 0 | |
1824 | except KeyboardInterrupt: |
|
1855 | except KeyboardInterrupt: | |
1825 | pass |
|
1856 | pass | |
1826 | except EOFError: |
|
1857 | except EOFError: | |
1827 | if self.autoindent: |
|
1858 | if self.autoindent: | |
1828 | self.rl_do_indent = False |
|
1859 | self.rl_do_indent = False | |
1829 |
self.readline |
|
1860 | if self.has_readline: | |
|
1861 | self.readline_startup_hook(None) | |||
1830 | self.write('\n') |
|
1862 | self.write('\n') | |
1831 | self.exit() |
|
1863 | self.exit() | |
1832 | except bdb.BdbQuit: |
|
1864 | except bdb.BdbQuit: | |
1833 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1865 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
1834 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1866 | 'Because of how pdb handles the stack, it is impossible\n' | |
1835 | 'for IPython to properly format this particular exception.\n' |
|
1867 | 'for IPython to properly format this particular exception.\n' | |
1836 | 'IPython will resume normal operation.') |
|
1868 | 'IPython will resume normal operation.') | |
1837 | except: |
|
1869 | except: | |
1838 | # exceptions here are VERY RARE, but they can be triggered |
|
1870 | # exceptions here are VERY RARE, but they can be triggered | |
1839 | # asynchronously by signal handlers, for example. |
|
1871 | # asynchronously by signal handlers, for example. | |
1840 | self.showtraceback() |
|
1872 | self.showtraceback() | |
1841 | else: |
|
1873 | else: | |
1842 | more = self.push_line(line) |
|
1874 | more = self.push_line(line) | |
1843 | if (self.SyntaxTB.last_syntax_error and |
|
1875 | if (self.SyntaxTB.last_syntax_error and | |
1844 | self.autoedit_syntax): |
|
1876 | self.autoedit_syntax): | |
1845 | self.edit_syntax_error() |
|
1877 | self.edit_syntax_error() | |
1846 |
|
1878 | |||
1847 | # We are off again... |
|
1879 | # We are off again... | |
1848 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
1880 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
1849 |
|
1881 | |||
|
1882 | # Turn off the exit flag, so the mainloop can be restarted if desired | |||
|
1883 | self.exit_now = False | |||
|
1884 | ||||
1850 | def safe_execfile(self, fname, *where, **kw): |
|
1885 | def safe_execfile(self, fname, *where, **kw): | |
1851 | """A safe version of the builtin execfile(). |
|
1886 | """A safe version of the builtin execfile(). | |
1852 |
|
1887 | |||
1853 | This version will never throw an exception, but instead print |
|
1888 | This version will never throw an exception, but instead print | |
1854 | helpful error messages to the screen. This only works on pure |
|
1889 | helpful error messages to the screen. This only works on pure | |
1855 | Python files with the .py extension. |
|
1890 | Python files with the .py extension. | |
1856 |
|
1891 | |||
1857 | Parameters |
|
1892 | Parameters | |
1858 | ---------- |
|
1893 | ---------- | |
1859 | fname : string |
|
1894 | fname : string | |
1860 | The name of the file to be executed. |
|
1895 | The name of the file to be executed. | |
1861 | where : tuple |
|
1896 | where : tuple | |
1862 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1897 | One or two namespaces, passed to execfile() as (globals,locals). | |
1863 | If only one is given, it is passed as both. |
|
1898 | If only one is given, it is passed as both. | |
1864 | exit_ignore : bool (False) |
|
1899 | exit_ignore : bool (False) | |
1865 |
If True, then |
|
1900 | If True, then silence SystemExit for non-zero status (it is always | |
|
1901 | silenced for zero status, as it is so common). | |||
1866 | """ |
|
1902 | """ | |
1867 | kw.setdefault('exit_ignore', False) |
|
1903 | kw.setdefault('exit_ignore', False) | |
1868 |
|
1904 | |||
1869 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1905 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1870 |
|
1906 | |||
1871 | # Make sure we have a .py file |
|
1907 | # Make sure we have a .py file | |
1872 | if not fname.endswith('.py'): |
|
1908 | if not fname.endswith('.py'): | |
1873 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1909 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1874 |
|
1910 | |||
1875 | # Make sure we can open the file |
|
1911 | # Make sure we can open the file | |
1876 | try: |
|
1912 | try: | |
1877 | with open(fname) as thefile: |
|
1913 | with open(fname) as thefile: | |
1878 | pass |
|
1914 | pass | |
1879 | except: |
|
1915 | except: | |
1880 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1916 | warn('Could not open file <%s> for safe execution.' % fname) | |
1881 | return |
|
1917 | return | |
1882 |
|
1918 | |||
1883 | # Find things also in current directory. This is needed to mimic the |
|
1919 | # Find things also in current directory. This is needed to mimic the | |
1884 | # behavior of running a script from the system command line, where |
|
1920 | # behavior of running a script from the system command line, where | |
1885 | # Python inserts the script's directory into sys.path |
|
1921 | # Python inserts the script's directory into sys.path | |
1886 | dname = os.path.dirname(fname) |
|
1922 | dname = os.path.dirname(fname) | |
1887 |
|
1923 | |||
1888 | with prepended_to_syspath(dname): |
|
1924 | with prepended_to_syspath(dname): | |
1889 | try: |
|
1925 | try: | |
1890 | if sys.platform == 'win32' and sys.version_info < (2,5,1): |
|
1926 | execfile(fname,*where) | |
1891 | # Work around a bug in Python for Windows. The bug was |
|
|||
1892 | # fixed in in Python 2.5 r54159 and 54158, but that's still |
|
|||
1893 | # SVN Python as of March/07. For details, see: |
|
|||
1894 | # http://projects.scipy.org/ipython/ipython/ticket/123 |
|
|||
1895 | try: |
|
|||
1896 | globs,locs = where[0:2] |
|
|||
1897 | except: |
|
|||
1898 | try: |
|
|||
1899 | globs = locs = where[0] |
|
|||
1900 | except: |
|
|||
1901 | globs = locs = globals() |
|
|||
1902 | exec file(fname) in globs,locs |
|
|||
1903 | else: |
|
|||
1904 | execfile(fname,*where) |
|
|||
1905 | except SyntaxError: |
|
|||
1906 | self.showsyntaxerror() |
|
|||
1907 | warn('Failure executing file: <%s>' % fname) |
|
|||
1908 | except SystemExit, status: |
|
1927 | except SystemExit, status: | |
1909 | # Code that correctly sets the exit status flag to success (0) |
|
1928 | # If the call was made with 0 or None exit status (sys.exit(0) | |
1910 |
# |
|
1929 | # or sys.exit() ), don't bother showing a traceback, as both of | |
1911 | # sys.exit() does NOT set the message to 0 (it's empty) so that |
|
1930 | # these are considered normal by the OS: | |
1912 | # will still get a traceback. Note that the structure of the |
|
1931 | # > python -c'import sys;sys.exit(0)'; echo $? | |
1913 | # SystemExit exception changed between Python 2.4 and 2.5, so |
|
1932 | # 0 | |
1914 | # the checks must be done in a version-dependent way. |
|
1933 | # > python -c'import sys;sys.exit()'; echo $? | |
1915 |
|
|
1934 | # 0 | |
1916 | if status.message!=0 and not kw['exit_ignore']: |
|
1935 | # For other exit status, we show the exception unless | |
1917 | show = True |
|
1936 | # explicitly silenced, but only in short form. | |
1918 | if show: |
|
1937 | if status.code not in (0, None) and not kw['exit_ignore']: | |
1919 | self.showtraceback() |
|
1938 | self.showtraceback(exception_only=True) | |
1920 | warn('Failure executing file: <%s>' % fname) |
|
|||
1921 | except: |
|
1939 | except: | |
1922 | self.showtraceback() |
|
1940 | self.showtraceback() | |
1923 | warn('Failure executing file: <%s>' % fname) |
|
|||
1924 |
|
1941 | |||
1925 | def safe_execfile_ipy(self, fname): |
|
1942 | def safe_execfile_ipy(self, fname): | |
1926 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1943 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
1927 |
|
1944 | |||
1928 | Parameters |
|
1945 | Parameters | |
1929 | ---------- |
|
1946 | ---------- | |
1930 | fname : str |
|
1947 | fname : str | |
1931 | The name of the file to execute. The filename must have a |
|
1948 | The name of the file to execute. The filename must have a | |
1932 | .ipy extension. |
|
1949 | .ipy extension. | |
1933 | """ |
|
1950 | """ | |
1934 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1951 | fname = os.path.abspath(os.path.expanduser(fname)) | |
1935 |
|
1952 | |||
1936 | # Make sure we have a .py file |
|
1953 | # Make sure we have a .py file | |
1937 | if not fname.endswith('.ipy'): |
|
1954 | if not fname.endswith('.ipy'): | |
1938 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1955 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
1939 |
|
1956 | |||
1940 | # Make sure we can open the file |
|
1957 | # Make sure we can open the file | |
1941 | try: |
|
1958 | try: | |
1942 | with open(fname) as thefile: |
|
1959 | with open(fname) as thefile: | |
1943 | pass |
|
1960 | pass | |
1944 | except: |
|
1961 | except: | |
1945 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1962 | warn('Could not open file <%s> for safe execution.' % fname) | |
1946 | return |
|
1963 | return | |
1947 |
|
1964 | |||
1948 | # Find things also in current directory. This is needed to mimic the |
|
1965 | # Find things also in current directory. This is needed to mimic the | |
1949 | # behavior of running a script from the system command line, where |
|
1966 | # behavior of running a script from the system command line, where | |
1950 | # Python inserts the script's directory into sys.path |
|
1967 | # Python inserts the script's directory into sys.path | |
1951 | dname = os.path.dirname(fname) |
|
1968 | dname = os.path.dirname(fname) | |
1952 |
|
1969 | |||
1953 | with prepended_to_syspath(dname): |
|
1970 | with prepended_to_syspath(dname): | |
1954 | try: |
|
1971 | try: | |
1955 | with open(fname) as thefile: |
|
1972 | with open(fname) as thefile: | |
1956 | script = thefile.read() |
|
1973 | script = thefile.read() | |
1957 | # self.runlines currently captures all exceptions |
|
1974 | # self.runlines currently captures all exceptions | |
1958 | # raise in user code. It would be nice if there were |
|
1975 | # raise in user code. It would be nice if there were | |
1959 | # versions of runlines, execfile that did raise, so |
|
1976 | # versions of runlines, execfile that did raise, so | |
1960 | # we could catch the errors. |
|
1977 | # we could catch the errors. | |
1961 | self.runlines(script, clean=True) |
|
1978 | self.runlines(script, clean=True) | |
1962 | except: |
|
1979 | except: | |
1963 | self.showtraceback() |
|
1980 | self.showtraceback() | |
1964 | warn('Unknown failure executing file: <%s>' % fname) |
|
1981 | warn('Unknown failure executing file: <%s>' % fname) | |
1965 |
|
1982 | |||
1966 | def _is_secondary_block_start(self, s): |
|
1983 | def _is_secondary_block_start(self, s): | |
1967 | if not s.endswith(':'): |
|
1984 | if not s.endswith(':'): | |
1968 | return False |
|
1985 | return False | |
1969 | if (s.startswith('elif') or |
|
1986 | if (s.startswith('elif') or | |
1970 | s.startswith('else') or |
|
1987 | s.startswith('else') or | |
1971 | s.startswith('except') or |
|
1988 | s.startswith('except') or | |
1972 | s.startswith('finally')): |
|
1989 | s.startswith('finally')): | |
1973 | return True |
|
1990 | return True | |
1974 |
|
1991 | |||
1975 | def cleanup_ipy_script(self, script): |
|
1992 | def cleanup_ipy_script(self, script): | |
1976 | """Make a script safe for self.runlines() |
|
1993 | """Make a script safe for self.runlines() | |
1977 |
|
1994 | |||
1978 | Currently, IPython is lines based, with blocks being detected by |
|
1995 | Currently, IPython is lines based, with blocks being detected by | |
1979 | empty lines. This is a problem for block based scripts that may |
|
1996 | empty lines. This is a problem for block based scripts that may | |
1980 | not have empty lines after blocks. This script adds those empty |
|
1997 | not have empty lines after blocks. This script adds those empty | |
1981 | lines to make scripts safe for running in the current line based |
|
1998 | lines to make scripts safe for running in the current line based | |
1982 | IPython. |
|
1999 | IPython. | |
1983 | """ |
|
2000 | """ | |
1984 | res = [] |
|
2001 | res = [] | |
1985 | lines = script.splitlines() |
|
2002 | lines = script.splitlines() | |
1986 | level = 0 |
|
2003 | level = 0 | |
1987 |
|
2004 | |||
1988 | for l in lines: |
|
2005 | for l in lines: | |
1989 | lstripped = l.lstrip() |
|
2006 | lstripped = l.lstrip() | |
1990 | stripped = l.strip() |
|
2007 | stripped = l.strip() | |
1991 | if not stripped: |
|
2008 | if not stripped: | |
1992 | continue |
|
2009 | continue | |
1993 | newlevel = len(l) - len(lstripped) |
|
2010 | newlevel = len(l) - len(lstripped) | |
1994 | if level > 0 and newlevel == 0 and \ |
|
2011 | if level > 0 and newlevel == 0 and \ | |
1995 | not self._is_secondary_block_start(stripped): |
|
2012 | not self._is_secondary_block_start(stripped): | |
1996 | # add empty line |
|
2013 | # add empty line | |
1997 | res.append('') |
|
2014 | res.append('') | |
1998 | res.append(l) |
|
2015 | res.append(l) | |
1999 | level = newlevel |
|
2016 | level = newlevel | |
2000 |
|
2017 | |||
2001 | return '\n'.join(res) + '\n' |
|
2018 | return '\n'.join(res) + '\n' | |
2002 |
|
2019 | |||
2003 | def runlines(self, lines, clean=False): |
|
2020 | def runlines(self, lines, clean=False): | |
2004 | """Run a string of one or more lines of source. |
|
2021 | """Run a string of one or more lines of source. | |
2005 |
|
2022 | |||
2006 | This method is capable of running a string containing multiple source |
|
2023 | This method is capable of running a string containing multiple source | |
2007 | lines, as if they had been entered at the IPython prompt. Since it |
|
2024 | lines, as if they had been entered at the IPython prompt. Since it | |
2008 | exposes IPython's processing machinery, the given strings can contain |
|
2025 | exposes IPython's processing machinery, the given strings can contain | |
2009 | magic calls (%magic), special shell access (!cmd), etc. |
|
2026 | magic calls (%magic), special shell access (!cmd), etc. | |
2010 | """ |
|
2027 | """ | |
2011 |
|
2028 | |||
2012 | if isinstance(lines, (list, tuple)): |
|
2029 | if isinstance(lines, (list, tuple)): | |
2013 | lines = '\n'.join(lines) |
|
2030 | lines = '\n'.join(lines) | |
2014 |
|
2031 | |||
2015 | if clean: |
|
2032 | if clean: | |
2016 | lines = self.cleanup_ipy_script(lines) |
|
2033 | lines = self.cleanup_ipy_script(lines) | |
2017 |
|
2034 | |||
2018 | # We must start with a clean buffer, in case this is run from an |
|
2035 | # We must start with a clean buffer, in case this is run from an | |
2019 | # interactive IPython session (via a magic, for example). |
|
2036 | # interactive IPython session (via a magic, for example). | |
2020 | self.resetbuffer() |
|
2037 | self.resetbuffer() | |
2021 | lines = lines.splitlines() |
|
2038 | lines = lines.splitlines() | |
2022 | more = 0 |
|
2039 | more = 0 | |
2023 |
|
2040 | |||
2024 | with nested(self.builtin_trap, self.display_trap): |
|
2041 | with nested(self.builtin_trap, self.display_trap): | |
2025 | for line in lines: |
|
2042 | for line in lines: | |
2026 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2043 | # skip blank lines so we don't mess up the prompt counter, but do | |
2027 | # NOT skip even a blank line if we are in a code block (more is |
|
2044 | # NOT skip even a blank line if we are in a code block (more is | |
2028 | # true) |
|
2045 | # true) | |
2029 |
|
2046 | |||
2030 | if line or more: |
|
2047 | if line or more: | |
2031 | # push to raw history, so hist line numbers stay in sync |
|
2048 | # push to raw history, so hist line numbers stay in sync | |
2032 | self.input_hist_raw.append("# " + line + "\n") |
|
2049 | self.input_hist_raw.append("# " + line + "\n") | |
2033 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2050 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) | |
2034 | more = self.push_line(prefiltered) |
|
2051 | more = self.push_line(prefiltered) | |
2035 | # IPython's runsource returns None if there was an error |
|
2052 | # IPython's runsource returns None if there was an error | |
2036 | # compiling the code. This allows us to stop processing right |
|
2053 | # compiling the code. This allows us to stop processing right | |
2037 | # away, so the user gets the error message at the right place. |
|
2054 | # away, so the user gets the error message at the right place. | |
2038 | if more is None: |
|
2055 | if more is None: | |
2039 | break |
|
2056 | break | |
2040 | else: |
|
2057 | else: | |
2041 | self.input_hist_raw.append("\n") |
|
2058 | self.input_hist_raw.append("\n") | |
2042 | # final newline in case the input didn't have it, so that the code |
|
2059 | # final newline in case the input didn't have it, so that the code | |
2043 | # actually does get executed |
|
2060 | # actually does get executed | |
2044 | if more: |
|
2061 | if more: | |
2045 | self.push_line('\n') |
|
2062 | self.push_line('\n') | |
2046 |
|
2063 | |||
2047 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2064 | def runsource(self, source, filename='<input>', symbol='single'): | |
2048 | """Compile and run some source in the interpreter. |
|
2065 | """Compile and run some source in the interpreter. | |
2049 |
|
2066 | |||
2050 | Arguments are as for compile_command(). |
|
2067 | Arguments are as for compile_command(). | |
2051 |
|
2068 | |||
2052 | One several things can happen: |
|
2069 | One several things can happen: | |
2053 |
|
2070 | |||
2054 | 1) The input is incorrect; compile_command() raised an |
|
2071 | 1) The input is incorrect; compile_command() raised an | |
2055 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2072 | exception (SyntaxError or OverflowError). A syntax traceback | |
2056 | will be printed by calling the showsyntaxerror() method. |
|
2073 | will be printed by calling the showsyntaxerror() method. | |
2057 |
|
2074 | |||
2058 | 2) The input is incomplete, and more input is required; |
|
2075 | 2) The input is incomplete, and more input is required; | |
2059 | compile_command() returned None. Nothing happens. |
|
2076 | compile_command() returned None. Nothing happens. | |
2060 |
|
2077 | |||
2061 | 3) The input is complete; compile_command() returned a code |
|
2078 | 3) The input is complete; compile_command() returned a code | |
2062 | object. The code is executed by calling self.runcode() (which |
|
2079 | object. The code is executed by calling self.runcode() (which | |
2063 | also handles run-time exceptions, except for SystemExit). |
|
2080 | also handles run-time exceptions, except for SystemExit). | |
2064 |
|
2081 | |||
2065 | The return value is: |
|
2082 | The return value is: | |
2066 |
|
2083 | |||
2067 | - True in case 2 |
|
2084 | - True in case 2 | |
2068 |
|
2085 | |||
2069 | - False in the other cases, unless an exception is raised, where |
|
2086 | - False in the other cases, unless an exception is raised, where | |
2070 | None is returned instead. This can be used by external callers to |
|
2087 | None is returned instead. This can be used by external callers to | |
2071 | know whether to continue feeding input or not. |
|
2088 | know whether to continue feeding input or not. | |
2072 |
|
2089 | |||
2073 | The return value can be used to decide whether to use sys.ps1 or |
|
2090 | The return value can be used to decide whether to use sys.ps1 or | |
2074 | sys.ps2 to prompt the next line.""" |
|
2091 | sys.ps2 to prompt the next line.""" | |
2075 |
|
2092 | |||
2076 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2093 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2077 | # this allows execution of indented pasted code. It is tempting |
|
2094 | # this allows execution of indented pasted code. It is tempting | |
2078 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2095 | # to add '\n' at the end of source to run commands like ' a=1' | |
2079 | # directly, but this fails for more complicated scenarios |
|
2096 | # directly, but this fails for more complicated scenarios | |
2080 | source=source.encode(self.stdin_encoding) |
|
2097 | source=source.encode(self.stdin_encoding) | |
2081 | if source[:1] in [' ', '\t']: |
|
2098 | if source[:1] in [' ', '\t']: | |
2082 | source = 'if 1:\n%s' % source |
|
2099 | source = 'if 1:\n%s' % source | |
2083 |
|
2100 | |||
2084 | try: |
|
2101 | try: | |
2085 | code = self.compile(source,filename,symbol) |
|
2102 | code = self.compile(source,filename,symbol) | |
2086 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2103 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2087 | # Case 1 |
|
2104 | # Case 1 | |
2088 | self.showsyntaxerror(filename) |
|
2105 | self.showsyntaxerror(filename) | |
2089 | return None |
|
2106 | return None | |
2090 |
|
2107 | |||
2091 | if code is None: |
|
2108 | if code is None: | |
2092 | # Case 2 |
|
2109 | # Case 2 | |
2093 | return True |
|
2110 | return True | |
2094 |
|
2111 | |||
2095 | # Case 3 |
|
2112 | # Case 3 | |
2096 | # We store the code object so that threaded shells and |
|
2113 | # We store the code object so that threaded shells and | |
2097 | # custom exception handlers can access all this info if needed. |
|
2114 | # custom exception handlers can access all this info if needed. | |
2098 | # The source corresponding to this can be obtained from the |
|
2115 | # The source corresponding to this can be obtained from the | |
2099 | # buffer attribute as '\n'.join(self.buffer). |
|
2116 | # buffer attribute as '\n'.join(self.buffer). | |
2100 | self.code_to_run = code |
|
2117 | self.code_to_run = code | |
2101 | # now actually execute the code object |
|
2118 | # now actually execute the code object | |
2102 | if self.runcode(code) == 0: |
|
2119 | if self.runcode(code) == 0: | |
2103 | return False |
|
2120 | return False | |
2104 | else: |
|
2121 | else: | |
2105 | return None |
|
2122 | return None | |
2106 |
|
2123 | |||
2107 | def runcode(self,code_obj): |
|
2124 | def runcode(self,code_obj): | |
2108 | """Execute a code object. |
|
2125 | """Execute a code object. | |
2109 |
|
2126 | |||
2110 | When an exception occurs, self.showtraceback() is called to display a |
|
2127 | When an exception occurs, self.showtraceback() is called to display a | |
2111 | traceback. |
|
2128 | traceback. | |
2112 |
|
2129 | |||
2113 | Return value: a flag indicating whether the code to be run completed |
|
2130 | Return value: a flag indicating whether the code to be run completed | |
2114 | successfully: |
|
2131 | successfully: | |
2115 |
|
2132 | |||
2116 | - 0: successful execution. |
|
2133 | - 0: successful execution. | |
2117 | - 1: an error occurred. |
|
2134 | - 1: an error occurred. | |
2118 | """ |
|
2135 | """ | |
2119 |
|
2136 | |||
2120 | # Set our own excepthook in case the user code tries to call it |
|
2137 | # Set our own excepthook in case the user code tries to call it | |
2121 | # directly, so that the IPython crash handler doesn't get triggered |
|
2138 | # directly, so that the IPython crash handler doesn't get triggered | |
2122 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2139 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2123 |
|
2140 | |||
2124 | # we save the original sys.excepthook in the instance, in case config |
|
2141 | # we save the original sys.excepthook in the instance, in case config | |
2125 | # code (such as magics) needs access to it. |
|
2142 | # code (such as magics) needs access to it. | |
2126 | self.sys_excepthook = old_excepthook |
|
2143 | self.sys_excepthook = old_excepthook | |
2127 | outflag = 1 # happens in more places, so it's easier as default |
|
2144 | outflag = 1 # happens in more places, so it's easier as default | |
2128 | try: |
|
2145 | try: | |
2129 | try: |
|
2146 | try: | |
2130 | self.hooks.pre_runcode_hook() |
|
2147 | self.hooks.pre_runcode_hook() | |
2131 | exec code_obj in self.user_global_ns, self.user_ns |
|
2148 | exec code_obj in self.user_global_ns, self.user_ns | |
2132 | finally: |
|
2149 | finally: | |
2133 | # Reset our crash handler in place |
|
2150 | # Reset our crash handler in place | |
2134 | sys.excepthook = old_excepthook |
|
2151 | sys.excepthook = old_excepthook | |
2135 | except SystemExit: |
|
2152 | except SystemExit: | |
2136 | self.resetbuffer() |
|
2153 | self.resetbuffer() | |
2137 | self.showtraceback() |
|
2154 | self.showtraceback(exception_only=True) | |
2138 | warn("Type %exit or %quit to exit IPython " |
|
2155 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2139 | "(%Exit or %Quit do so unconditionally).",level=1) |
|
|||
2140 | except self.custom_exceptions: |
|
2156 | except self.custom_exceptions: | |
2141 | etype,value,tb = sys.exc_info() |
|
2157 | etype,value,tb = sys.exc_info() | |
2142 | self.CustomTB(etype,value,tb) |
|
2158 | self.CustomTB(etype,value,tb) | |
2143 | except: |
|
2159 | except: | |
2144 | self.showtraceback() |
|
2160 | self.showtraceback() | |
2145 | else: |
|
2161 | else: | |
2146 | outflag = 0 |
|
2162 | outflag = 0 | |
2147 | if softspace(sys.stdout, 0): |
|
2163 | if softspace(sys.stdout, 0): | |
2148 |
|
2164 | |||
2149 | # Flush out code object which has been run (and source) |
|
2165 | # Flush out code object which has been run (and source) | |
2150 | self.code_to_run = None |
|
2166 | self.code_to_run = None | |
2151 | return outflag |
|
2167 | return outflag | |
2152 |
|
2168 | |||
2153 | def push_line(self, line): |
|
2169 | def push_line(self, line): | |
2154 | """Push a line to the interpreter. |
|
2170 | """Push a line to the interpreter. | |
2155 |
|
2171 | |||
2156 | The line should not have a trailing newline; it may have |
|
2172 | The line should not have a trailing newline; it may have | |
2157 | internal newlines. The line is appended to a buffer and the |
|
2173 | internal newlines. The line is appended to a buffer and the | |
2158 | interpreter's runsource() method is called with the |
|
2174 | interpreter's runsource() method is called with the | |
2159 | concatenated contents of the buffer as source. If this |
|
2175 | concatenated contents of the buffer as source. If this | |
2160 | indicates that the command was executed or invalid, the buffer |
|
2176 | indicates that the command was executed or invalid, the buffer | |
2161 | is reset; otherwise, the command is incomplete, and the buffer |
|
2177 | is reset; otherwise, the command is incomplete, and the buffer | |
2162 | is left as it was after the line was appended. The return |
|
2178 | is left as it was after the line was appended. The return | |
2163 | value is 1 if more input is required, 0 if the line was dealt |
|
2179 | value is 1 if more input is required, 0 if the line was dealt | |
2164 | with in some way (this is the same as runsource()). |
|
2180 | with in some way (this is the same as runsource()). | |
2165 | """ |
|
2181 | """ | |
2166 |
|
2182 | |||
2167 | # autoindent management should be done here, and not in the |
|
2183 | # autoindent management should be done here, and not in the | |
2168 | # interactive loop, since that one is only seen by keyboard input. We |
|
2184 | # interactive loop, since that one is only seen by keyboard input. We | |
2169 | # need this done correctly even for code run via runlines (which uses |
|
2185 | # need this done correctly even for code run via runlines (which uses | |
2170 | # push). |
|
2186 | # push). | |
2171 |
|
2187 | |||
2172 | #print 'push line: <%s>' % line # dbg |
|
2188 | #print 'push line: <%s>' % line # dbg | |
2173 | for subline in line.splitlines(): |
|
2189 | for subline in line.splitlines(): | |
2174 | self._autoindent_update(subline) |
|
2190 | self._autoindent_update(subline) | |
2175 | self.buffer.append(line) |
|
2191 | self.buffer.append(line) | |
2176 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2192 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2177 | if not more: |
|
2193 | if not more: | |
2178 | self.resetbuffer() |
|
2194 | self.resetbuffer() | |
2179 | return more |
|
2195 | return more | |
2180 |
|
2196 | |||
2181 | def _autoindent_update(self,line): |
|
2197 | def _autoindent_update(self,line): | |
2182 | """Keep track of the indent level.""" |
|
2198 | """Keep track of the indent level.""" | |
2183 |
|
2199 | |||
2184 | #debugx('line') |
|
2200 | #debugx('line') | |
2185 | #debugx('self.indent_current_nsp') |
|
2201 | #debugx('self.indent_current_nsp') | |
2186 | if self.autoindent: |
|
2202 | if self.autoindent: | |
2187 | if line: |
|
2203 | if line: | |
2188 | inisp = num_ini_spaces(line) |
|
2204 | inisp = num_ini_spaces(line) | |
2189 | if inisp < self.indent_current_nsp: |
|
2205 | if inisp < self.indent_current_nsp: | |
2190 | self.indent_current_nsp = inisp |
|
2206 | self.indent_current_nsp = inisp | |
2191 |
|
2207 | |||
2192 | if line[-1] == ':': |
|
2208 | if line[-1] == ':': | |
2193 | self.indent_current_nsp += 4 |
|
2209 | self.indent_current_nsp += 4 | |
2194 | elif dedent_re.match(line): |
|
2210 | elif dedent_re.match(line): | |
2195 | self.indent_current_nsp -= 4 |
|
2211 | self.indent_current_nsp -= 4 | |
2196 | else: |
|
2212 | else: | |
2197 | self.indent_current_nsp = 0 |
|
2213 | self.indent_current_nsp = 0 | |
2198 |
|
2214 | |||
2199 | def resetbuffer(self): |
|
2215 | def resetbuffer(self): | |
2200 | """Reset the input buffer.""" |
|
2216 | """Reset the input buffer.""" | |
2201 | self.buffer[:] = [] |
|
2217 | self.buffer[:] = [] | |
2202 |
|
2218 | |||
2203 | def raw_input(self,prompt='',continue_prompt=False): |
|
2219 | def raw_input(self,prompt='',continue_prompt=False): | |
2204 | """Write a prompt and read a line. |
|
2220 | """Write a prompt and read a line. | |
2205 |
|
2221 | |||
2206 | The returned line does not include the trailing newline. |
|
2222 | The returned line does not include the trailing newline. | |
2207 | When the user enters the EOF key sequence, EOFError is raised. |
|
2223 | When the user enters the EOF key sequence, EOFError is raised. | |
2208 |
|
2224 | |||
2209 | Optional inputs: |
|
2225 | Optional inputs: | |
2210 |
|
2226 | |||
2211 | - prompt(''): a string to be printed to prompt the user. |
|
2227 | - prompt(''): a string to be printed to prompt the user. | |
2212 |
|
2228 | |||
2213 | - continue_prompt(False): whether this line is the first one or a |
|
2229 | - continue_prompt(False): whether this line is the first one or a | |
2214 | continuation in a sequence of inputs. |
|
2230 | continuation in a sequence of inputs. | |
2215 | """ |
|
2231 | """ | |
2216 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2232 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) | |
2217 |
|
2233 | |||
2218 | # Code run by the user may have modified the readline completer state. |
|
2234 | # Code run by the user may have modified the readline completer state. | |
2219 | # We must ensure that our completer is back in place. |
|
2235 | # We must ensure that our completer is back in place. | |
2220 |
|
2236 | |||
2221 | if self.has_readline: |
|
2237 | if self.has_readline: | |
2222 | self.set_completer() |
|
2238 | self.set_completer() | |
2223 |
|
2239 | |||
2224 | try: |
|
2240 | try: | |
2225 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2241 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
2226 | except ValueError: |
|
2242 | except ValueError: | |
2227 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2243 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
2228 | " or sys.stdout.close()!\nExiting IPython!") |
|
2244 | " or sys.stdout.close()!\nExiting IPython!") | |
2229 | self.ask_exit() |
|
2245 | self.ask_exit() | |
2230 | return "" |
|
2246 | return "" | |
2231 |
|
2247 | |||
2232 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2248 | # Try to be reasonably smart about not re-indenting pasted input more | |
2233 | # than necessary. We do this by trimming out the auto-indent initial |
|
2249 | # than necessary. We do this by trimming out the auto-indent initial | |
2234 | # spaces, if the user's actual input started itself with whitespace. |
|
2250 | # spaces, if the user's actual input started itself with whitespace. | |
2235 | #debugx('self.buffer[-1]') |
|
2251 | #debugx('self.buffer[-1]') | |
2236 |
|
2252 | |||
2237 | if self.autoindent: |
|
2253 | if self.autoindent: | |
2238 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2254 | if num_ini_spaces(line) > self.indent_current_nsp: | |
2239 | line = line[self.indent_current_nsp:] |
|
2255 | line = line[self.indent_current_nsp:] | |
2240 | self.indent_current_nsp = 0 |
|
2256 | self.indent_current_nsp = 0 | |
2241 |
|
2257 | |||
2242 | # store the unfiltered input before the user has any chance to modify |
|
2258 | # store the unfiltered input before the user has any chance to modify | |
2243 | # it. |
|
2259 | # it. | |
2244 | if line.strip(): |
|
2260 | if line.strip(): | |
2245 | if continue_prompt: |
|
2261 | if continue_prompt: | |
2246 | self.input_hist_raw[-1] += '%s\n' % line |
|
2262 | self.input_hist_raw[-1] += '%s\n' % line | |
2247 | if self.has_readline and self.readline_use: |
|
2263 | if self.has_readline and self.readline_use: | |
2248 | try: |
|
2264 | try: | |
2249 | histlen = self.readline.get_current_history_length() |
|
2265 | histlen = self.readline.get_current_history_length() | |
2250 | if histlen > 1: |
|
2266 | if histlen > 1: | |
2251 | newhist = self.input_hist_raw[-1].rstrip() |
|
2267 | newhist = self.input_hist_raw[-1].rstrip() | |
2252 | self.readline.remove_history_item(histlen-1) |
|
2268 | self.readline.remove_history_item(histlen-1) | |
2253 | self.readline.replace_history_item(histlen-2, |
|
2269 | self.readline.replace_history_item(histlen-2, | |
2254 | newhist.encode(self.stdin_encoding)) |
|
2270 | newhist.encode(self.stdin_encoding)) | |
2255 | except AttributeError: |
|
2271 | except AttributeError: | |
2256 | pass # re{move,place}_history_item are new in 2.4. |
|
2272 | pass # re{move,place}_history_item are new in 2.4. | |
2257 | else: |
|
2273 | else: | |
2258 | self.input_hist_raw.append('%s\n' % line) |
|
2274 | self.input_hist_raw.append('%s\n' % line) | |
2259 | # only entries starting at first column go to shadow history |
|
2275 | # only entries starting at first column go to shadow history | |
2260 | if line.lstrip() == line: |
|
2276 | if line.lstrip() == line: | |
2261 | self.shadowhist.add(line.strip()) |
|
2277 | self.shadowhist.add(line.strip()) | |
2262 | elif not continue_prompt: |
|
2278 | elif not continue_prompt: | |
2263 | self.input_hist_raw.append('\n') |
|
2279 | self.input_hist_raw.append('\n') | |
2264 | try: |
|
2280 | try: | |
2265 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2281 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
2266 | except: |
|
2282 | except: | |
2267 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2283 | # blanket except, in case a user-defined prefilter crashes, so it | |
2268 | # can't take all of ipython with it. |
|
2284 | # can't take all of ipython with it. | |
2269 | self.showtraceback() |
|
2285 | self.showtraceback() | |
2270 | return '' |
|
2286 | return '' | |
2271 | else: |
|
2287 | else: | |
2272 | return lineout |
|
2288 | return lineout | |
2273 |
|
2289 | |||
2274 | #------------------------------------------------------------------------- |
|
2290 | #------------------------------------------------------------------------- | |
2275 | # Working with components |
|
2291 | # Working with components | |
2276 | #------------------------------------------------------------------------- |
|
2292 | #------------------------------------------------------------------------- | |
2277 |
|
2293 | |||
2278 | def get_component(self, name=None, klass=None): |
|
2294 | def get_component(self, name=None, klass=None): | |
2279 | """Fetch a component by name and klass in my tree.""" |
|
2295 | """Fetch a component by name and klass in my tree.""" | |
2280 | c = Component.get_instances(root=self, name=name, klass=klass) |
|
2296 | c = Component.get_instances(root=self, name=name, klass=klass) | |
|
2297 | if len(c) == 0: | |||
|
2298 | return None | |||
2281 | if len(c) == 1: |
|
2299 | if len(c) == 1: | |
2282 | return c[0] |
|
2300 | return c[0] | |
2283 | else: |
|
2301 | else: | |
2284 | return c |
|
2302 | return c | |
2285 |
|
2303 | |||
2286 | #------------------------------------------------------------------------- |
|
2304 | #------------------------------------------------------------------------- | |
2287 | # IPython extensions |
|
2305 | # IPython extensions | |
2288 | #------------------------------------------------------------------------- |
|
2306 | #------------------------------------------------------------------------- | |
2289 |
|
2307 | |||
2290 | def load_extension(self, module_str): |
|
2308 | def load_extension(self, module_str): | |
2291 | """Load an IPython extension by its module name. |
|
2309 | """Load an IPython extension by its module name. | |
2292 |
|
2310 | |||
2293 | An IPython extension is an importable Python module that has |
|
2311 | An IPython extension is an importable Python module that has | |
2294 | a function with the signature:: |
|
2312 | a function with the signature:: | |
2295 |
|
2313 | |||
2296 | def load_ipython_extension(ipython): |
|
2314 | def load_ipython_extension(ipython): | |
2297 | # Do things with ipython |
|
2315 | # Do things with ipython | |
2298 |
|
2316 | |||
2299 | This function is called after your extension is imported and the |
|
2317 | This function is called after your extension is imported and the | |
2300 | currently active :class:`InteractiveShell` instance is passed as |
|
2318 | currently active :class:`InteractiveShell` instance is passed as | |
2301 | the only argument. You can do anything you want with IPython at |
|
2319 | the only argument. You can do anything you want with IPython at | |
2302 | that point, including defining new magic and aliases, adding new |
|
2320 | that point, including defining new magic and aliases, adding new | |
2303 | components, etc. |
|
2321 | components, etc. | |
2304 |
|
2322 | |||
2305 | The :func:`load_ipython_extension` will be called again is you |
|
2323 | The :func:`load_ipython_extension` will be called again is you | |
2306 | load or reload the extension again. It is up to the extension |
|
2324 | load or reload the extension again. It is up to the extension | |
2307 | author to add code to manage that. |
|
2325 | author to add code to manage that. | |
2308 |
|
2326 | |||
2309 | You can put your extension modules anywhere you want, as long as |
|
2327 | You can put your extension modules anywhere you want, as long as | |
2310 | they can be imported by Python's standard import mechanism. However, |
|
2328 | they can be imported by Python's standard import mechanism. However, | |
2311 | to make it easy to write extensions, you can also put your extensions |
|
2329 | to make it easy to write extensions, you can also put your extensions | |
2312 | in ``os.path.join(self.ipythondir, 'extensions')``. This directory |
|
2330 | in ``os.path.join(self.ipython_dir, 'extensions')``. This directory | |
2313 | is added to ``sys.path`` automatically. |
|
2331 | is added to ``sys.path`` automatically. | |
2314 | """ |
|
2332 | """ | |
2315 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2333 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2316 |
|
2334 | |||
2317 | if module_str not in sys.modules: |
|
2335 | if module_str not in sys.modules: | |
2318 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2336 | with prepended_to_syspath(self.ipython_extension_dir): | |
2319 | __import__(module_str) |
|
2337 | __import__(module_str) | |
2320 | mod = sys.modules[module_str] |
|
2338 | mod = sys.modules[module_str] | |
2321 | self._call_load_ipython_extension(mod) |
|
2339 | return self._call_load_ipython_extension(mod) | |
2322 |
|
2340 | |||
2323 | def unload_extension(self, module_str): |
|
2341 | def unload_extension(self, module_str): | |
2324 | """Unload an IPython extension by its module name. |
|
2342 | """Unload an IPython extension by its module name. | |
2325 |
|
2343 | |||
2326 | This function looks up the extension's name in ``sys.modules`` and |
|
2344 | This function looks up the extension's name in ``sys.modules`` and | |
2327 | simply calls ``mod.unload_ipython_extension(self)``. |
|
2345 | simply calls ``mod.unload_ipython_extension(self)``. | |
2328 | """ |
|
2346 | """ | |
2329 | if module_str in sys.modules: |
|
2347 | if module_str in sys.modules: | |
2330 | mod = sys.modules[module_str] |
|
2348 | mod = sys.modules[module_str] | |
2331 | self._call_unload_ipython_extension(mod) |
|
2349 | self._call_unload_ipython_extension(mod) | |
2332 |
|
2350 | |||
2333 | def reload_extension(self, module_str): |
|
2351 | def reload_extension(self, module_str): | |
2334 | """Reload an IPython extension by calling reload. |
|
2352 | """Reload an IPython extension by calling reload. | |
2335 |
|
2353 | |||
2336 | If the module has not been loaded before, |
|
2354 | If the module has not been loaded before, | |
2337 | :meth:`InteractiveShell.load_extension` is called. Otherwise |
|
2355 | :meth:`InteractiveShell.load_extension` is called. Otherwise | |
2338 | :func:`reload` is called and then the :func:`load_ipython_extension` |
|
2356 | :func:`reload` is called and then the :func:`load_ipython_extension` | |
2339 | function of the module, if it exists is called. |
|
2357 | function of the module, if it exists is called. | |
2340 | """ |
|
2358 | """ | |
2341 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2359 | from IPython.utils.syspathcontext import prepended_to_syspath | |
2342 |
|
2360 | |||
2343 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2361 | with prepended_to_syspath(self.ipython_extension_dir): | |
2344 | if module_str in sys.modules: |
|
2362 | if module_str in sys.modules: | |
2345 | mod = sys.modules[module_str] |
|
2363 | mod = sys.modules[module_str] | |
2346 | reload(mod) |
|
2364 | reload(mod) | |
2347 | self._call_load_ipython_extension(mod) |
|
2365 | self._call_load_ipython_extension(mod) | |
2348 | else: |
|
2366 | else: | |
2349 | self.load_extension(module_str) |
|
2367 | self.load_extension(module_str) | |
2350 |
|
2368 | |||
2351 | def _call_load_ipython_extension(self, mod): |
|
2369 | def _call_load_ipython_extension(self, mod): | |
2352 | if hasattr(mod, 'load_ipython_extension'): |
|
2370 | if hasattr(mod, 'load_ipython_extension'): | |
2353 | mod.load_ipython_extension(self) |
|
2371 | return mod.load_ipython_extension(self) | |
2354 |
|
2372 | |||
2355 | def _call_unload_ipython_extension(self, mod): |
|
2373 | def _call_unload_ipython_extension(self, mod): | |
2356 | if hasattr(mod, 'unload_ipython_extension'): |
|
2374 | if hasattr(mod, 'unload_ipython_extension'): | |
2357 | mod.unload_ipython_extension(self) |
|
2375 | return mod.unload_ipython_extension(self) | |
2358 |
|
2376 | |||
2359 | #------------------------------------------------------------------------- |
|
2377 | #------------------------------------------------------------------------- | |
2360 | # Things related to the prefilter |
|
2378 | # Things related to the prefilter | |
2361 | #------------------------------------------------------------------------- |
|
2379 | #------------------------------------------------------------------------- | |
2362 |
|
2380 | |||
2363 | def init_prefilter(self): |
|
2381 | def init_prefilter(self): | |
2364 | self.prefilter_manager = PrefilterManager(self, config=self.config) |
|
2382 | self.prefilter_manager = PrefilterManager(self, config=self.config) | |
|
2383 | # Ultimately this will be refactored in the new interpreter code, but | |||
|
2384 | # for now, we should expose the main prefilter method (there's legacy | |||
|
2385 | # code out there that may rely on this). | |||
|
2386 | self.prefilter = self.prefilter_manager.prefilter_lines | |||
2365 |
|
2387 | |||
2366 | #------------------------------------------------------------------------- |
|
2388 | #------------------------------------------------------------------------- | |
2367 | # Utilities |
|
2389 | # Utilities | |
2368 | #------------------------------------------------------------------------- |
|
2390 | #------------------------------------------------------------------------- | |
2369 |
|
2391 | |||
2370 | def getoutput(self, cmd): |
|
2392 | def getoutput(self, cmd): | |
2371 | return getoutput(self.var_expand(cmd,depth=2), |
|
2393 | return getoutput(self.var_expand(cmd,depth=2), | |
2372 | header=self.system_header, |
|
2394 | header=self.system_header, | |
2373 | verbose=self.system_verbose) |
|
2395 | verbose=self.system_verbose) | |
2374 |
|
2396 | |||
2375 | def getoutputerror(self, cmd): |
|
2397 | def getoutputerror(self, cmd): | |
2376 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2398 | return getoutputerror(self.var_expand(cmd,depth=2), | |
2377 | header=self.system_header, |
|
2399 | header=self.system_header, | |
2378 | verbose=self.system_verbose) |
|
2400 | verbose=self.system_verbose) | |
2379 |
|
2401 | |||
2380 | def var_expand(self,cmd,depth=0): |
|
2402 | def var_expand(self,cmd,depth=0): | |
2381 | """Expand python variables in a string. |
|
2403 | """Expand python variables in a string. | |
2382 |
|
2404 | |||
2383 | The depth argument indicates how many frames above the caller should |
|
2405 | The depth argument indicates how many frames above the caller should | |
2384 | be walked to look for the local namespace where to expand variables. |
|
2406 | be walked to look for the local namespace where to expand variables. | |
2385 |
|
2407 | |||
2386 | The global namespace for expansion is always the user's interactive |
|
2408 | The global namespace for expansion is always the user's interactive | |
2387 | namespace. |
|
2409 | namespace. | |
2388 | """ |
|
2410 | """ | |
2389 |
|
2411 | |||
2390 | return str(ItplNS(cmd, |
|
2412 | return str(ItplNS(cmd, | |
2391 | self.user_ns, # globals |
|
2413 | self.user_ns, # globals | |
2392 | # Skip our own frame in searching for locals: |
|
2414 | # Skip our own frame in searching for locals: | |
2393 | sys._getframe(depth+1).f_locals # locals |
|
2415 | sys._getframe(depth+1).f_locals # locals | |
2394 | )) |
|
2416 | )) | |
2395 |
|
2417 | |||
2396 | def mktempfile(self,data=None): |
|
2418 | def mktempfile(self,data=None): | |
2397 | """Make a new tempfile and return its filename. |
|
2419 | """Make a new tempfile and return its filename. | |
2398 |
|
2420 | |||
2399 | This makes a call to tempfile.mktemp, but it registers the created |
|
2421 | This makes a call to tempfile.mktemp, but it registers the created | |
2400 | filename internally so ipython cleans it up at exit time. |
|
2422 | filename internally so ipython cleans it up at exit time. | |
2401 |
|
2423 | |||
2402 | Optional inputs: |
|
2424 | Optional inputs: | |
2403 |
|
2425 | |||
2404 | - data(None): if data is given, it gets written out to the temp file |
|
2426 | - data(None): if data is given, it gets written out to the temp file | |
2405 | immediately, and the file is closed again.""" |
|
2427 | immediately, and the file is closed again.""" | |
2406 |
|
2428 | |||
2407 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2429 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2408 | self.tempfiles.append(filename) |
|
2430 | self.tempfiles.append(filename) | |
2409 |
|
2431 | |||
2410 | if data: |
|
2432 | if data: | |
2411 | tmp_file = open(filename,'w') |
|
2433 | tmp_file = open(filename,'w') | |
2412 | tmp_file.write(data) |
|
2434 | tmp_file.write(data) | |
2413 | tmp_file.close() |
|
2435 | tmp_file.close() | |
2414 | return filename |
|
2436 | return filename | |
2415 |
|
2437 | |||
2416 | def write(self,data): |
|
2438 | def write(self,data): | |
2417 | """Write a string to the default output""" |
|
2439 | """Write a string to the default output""" | |
2418 | Term.cout.write(data) |
|
2440 | Term.cout.write(data) | |
2419 |
|
2441 | |||
2420 | def write_err(self,data): |
|
2442 | def write_err(self,data): | |
2421 | """Write a string to the default error output""" |
|
2443 | """Write a string to the default error output""" | |
2422 | Term.cerr.write(data) |
|
2444 | Term.cerr.write(data) | |
2423 |
|
2445 | |||
2424 | def ask_yes_no(self,prompt,default=True): |
|
2446 | def ask_yes_no(self,prompt,default=True): | |
2425 | if self.quiet: |
|
2447 | if self.quiet: | |
2426 | return True |
|
2448 | return True | |
2427 | return ask_yes_no(prompt,default) |
|
2449 | return ask_yes_no(prompt,default) | |
2428 |
|
2450 | |||
2429 | #------------------------------------------------------------------------- |
|
2451 | #------------------------------------------------------------------------- | |
|
2452 | # Things related to GUI support and pylab | |||
|
2453 | #------------------------------------------------------------------------- | |||
|
2454 | ||||
|
2455 | def enable_pylab(self, gui=None): | |||
|
2456 | """Activate pylab support at runtime. | |||
|
2457 | ||||
|
2458 | This turns on support for matplotlib, preloads into the interactive | |||
|
2459 | namespace all of numpy and pylab, and configures IPython to correcdtly | |||
|
2460 | interact with the GUI event loop. The GUI backend to be used can be | |||
|
2461 | optionally selected with the optional :param:`gui` argument. | |||
|
2462 | ||||
|
2463 | Parameters | |||
|
2464 | ---------- | |||
|
2465 | gui : optional, string | |||
|
2466 | ||||
|
2467 | If given, dictates the choice of matplotlib GUI backend to use | |||
|
2468 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |||
|
2469 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |||
|
2470 | dictated by the matplotlib build-time options plus the user's | |||
|
2471 | matplotlibrc configuration file). | |||
|
2472 | """ | |||
|
2473 | # We want to prevent the loading of pylab to pollute the user's | |||
|
2474 | # namespace as shown by the %who* magics, so we execute the activation | |||
|
2475 | # code in an empty namespace, and we update *both* user_ns and | |||
|
2476 | # user_config_ns with this information. | |||
|
2477 | ns = {} | |||
|
2478 | gui = pylab_activate(ns, gui) | |||
|
2479 | self.user_ns.update(ns) | |||
|
2480 | self.user_config_ns.update(ns) | |||
|
2481 | # Now we must activate the gui pylab wants to use, and fix %run to take | |||
|
2482 | # plot updates into account | |||
|
2483 | enable_gui(gui) | |||
|
2484 | self.magic_run = self._pylab_magic_run | |||
|
2485 | ||||
|
2486 | #------------------------------------------------------------------------- | |||
2430 | # Things related to IPython exiting |
|
2487 | # Things related to IPython exiting | |
2431 | #------------------------------------------------------------------------- |
|
2488 | #------------------------------------------------------------------------- | |
2432 |
|
2489 | |||
2433 | def ask_exit(self): |
|
2490 | def ask_exit(self): | |
2434 |
""" |
|
2491 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
2435 | self.exit_now = True |
|
2492 | self.exit_now = True | |
2436 |
|
2493 | |||
2437 | def exit(self): |
|
2494 | def exit(self): | |
2438 | """Handle interactive exit. |
|
2495 | """Handle interactive exit. | |
2439 |
|
2496 | |||
2440 | This method calls the ask_exit callback.""" |
|
2497 | This method calls the ask_exit callback.""" | |
2441 | if self.confirm_exit: |
|
2498 | if self.confirm_exit: | |
2442 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2499 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
2443 | self.ask_exit() |
|
2500 | self.ask_exit() | |
2444 | else: |
|
2501 | else: | |
2445 | self.ask_exit() |
|
2502 | self.ask_exit() | |
2446 |
|
2503 | |||
2447 | def atexit_operations(self): |
|
2504 | def atexit_operations(self): | |
2448 | """This will be executed at the time of exit. |
|
2505 | """This will be executed at the time of exit. | |
2449 |
|
2506 | |||
2450 | Saving of persistent data should be performed here. |
|
2507 | Saving of persistent data should be performed here. | |
2451 | """ |
|
2508 | """ | |
2452 | self.savehist() |
|
2509 | self.savehist() | |
2453 |
|
2510 | |||
2454 | # Cleanup all tempfiles left around |
|
2511 | # Cleanup all tempfiles left around | |
2455 | for tfile in self.tempfiles: |
|
2512 | for tfile in self.tempfiles: | |
2456 | try: |
|
2513 | try: | |
2457 | os.unlink(tfile) |
|
2514 | os.unlink(tfile) | |
2458 | except OSError: |
|
2515 | except OSError: | |
2459 | pass |
|
2516 | pass | |
2460 |
|
2517 | |||
2461 | # Clear all user namespaces to release all references cleanly. |
|
2518 | # Clear all user namespaces to release all references cleanly. | |
2462 | self.reset() |
|
2519 | self.reset() | |
2463 |
|
2520 | |||
2464 | # Run user hooks |
|
2521 | # Run user hooks | |
2465 | self.hooks.shutdown_hook() |
|
2522 | self.hooks.shutdown_hook() | |
2466 |
|
2523 | |||
2467 | def cleanup(self): |
|
2524 | def cleanup(self): | |
2468 | self.restore_sys_module_state() |
|
2525 | self.restore_sys_module_state() | |
2469 |
|
2526 | |||
2470 |
|
2527 |
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 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: 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 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: 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/kernel/core/notification.py to IPython/utils/notification.py |
|
NO CONTENT: file renamed from IPython/kernel/core/notification.py to IPython/utils/notification.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: file renamed from IPython/kernel/core/tests/test_notification.py to IPython/utils/tests/test_notification.py |
|
NO CONTENT: file renamed from IPython/kernel/core/tests/test_notification.py to IPython/utils/tests/test_notification.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 |
|
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 | ||
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