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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | 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 |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | 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 |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | NO CONTENT: new file 100644, binary diff hidden |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,64 +1,67 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | IPython. |
|
5 | 5 | |
|
6 | 6 | IPython is a set of tools for interactive and exploratory computing in Python. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2008-2009 The IPython Development Team |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING, distributed as part of this software. |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Imports |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | from __future__ import absolute_import | |
|
19 | 20 | |
|
20 | 21 | import os |
|
21 | 22 | import sys |
|
22 | from IPython.core import release | |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Setup everything |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | ||
|
29 | if sys.version[0:3] < '2.4': | |
|
30 | raise ImportError('Python Version 2.4 or above is required for IPython.') | |
|
28 | if sys.version[0:3] < '2.5': | |
|
29 | raise ImportError('Python Version 2.5 or above is required for IPython.') | |
|
31 | 30 | |
|
32 | 31 | |
|
33 | 32 | # Make it easy to import extensions - they are always directly on pythonpath. |
|
34 | 33 | # Therefore, non-IPython modules can be added to extensions directory |
|
35 | 34 | sys.path.append(os.path.join(os.path.dirname(__file__), "extensions")) |
|
36 | 35 | |
|
37 | 36 | #----------------------------------------------------------------------------- |
|
38 | 37 | # Setup the top level names |
|
39 | 38 | #----------------------------------------------------------------------------- |
|
40 | 39 | |
|
41 | 40 | # In some cases, these are causing circular imports. |
|
42 | from IPython.core.iplib import InteractiveShell | |
|
43 |
from |
|
|
44 | from IPython.core.error import TryNext | |
|
41 | from .config.loader import Config | |
|
42 | from .core import release | |
|
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 | 51 | enable_wx, disable_wx, |
|
48 | 52 | enable_gtk, disable_gtk, |
|
49 | 53 | enable_qt4, disable_qt4, |
|
50 | 54 | enable_tk, disable_tk, |
|
51 | 55 | set_inputhook, clear_inputhook, |
|
52 | 56 | current_gui, spin, |
|
53 | 57 | appstart_qt4, appstart_wx, |
|
54 | 58 | appstart_gtk, appstart_tk |
|
55 | 59 | ) |
|
56 | 60 | |
|
57 | 61 | # Release data |
|
58 | 62 | __author__ = '' |
|
59 | 63 | for author, email in release.authors.values(): |
|
60 | 64 | __author__ += author + ' <' + email + '>\n' |
|
61 | 65 | __license__ = release.license |
|
62 | 66 | __version__ = release.version |
|
63 | 67 | __revision__ = release.revision |
|
64 |
@@ -1,148 +1,148 b'' | |||
|
1 | 1 | # Get the config being loaded so we can set attributes on it |
|
2 | 2 | c = get_config() |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Global options |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | |
|
8 | 8 | # c.Global.display_banner = True |
|
9 | 9 | |
|
10 | 10 | # c.Global.classic = False |
|
11 | 11 | |
|
12 | 12 | # c.Global.nosep = True |
|
13 | 13 | |
|
14 | 14 | # Set this to determine the detail of what is logged at startup. |
|
15 | 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 | 18 | # This should be a list of importable Python modules that have an |
|
19 | 19 | # load_in_ipython(ip) method. This method gets called when the extension |
|
20 | 20 | # is loaded. You can put your extensions anywhere they can be imported |
|
21 | 21 | # but we add the extensions subdir of the ipython directory to sys.path |
|
22 | 22 | # during extension loading, so you can put them there as well. |
|
23 | 23 | # c.Global.extensions = [ |
|
24 | 24 | # 'myextension' |
|
25 | 25 | # ] |
|
26 | 26 | |
|
27 | 27 | # These lines are run in IPython in the user's namespace after extensions |
|
28 | 28 | # are loaded. They can contain full IPython syntax with magics etc. |
|
29 | 29 | # c.Global.exec_lines = [ |
|
30 | 30 | # 'import numpy', |
|
31 | 31 | # 'a = 10; b = 20', |
|
32 | 32 | # '1/0' |
|
33 | 33 | # ] |
|
34 | 34 | |
|
35 | 35 | # These files are run in IPython in the user's namespace. Files with a .py |
|
36 | 36 | # extension need to be pure Python. Files with a .ipy extension can have |
|
37 | 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 | 39 | # c.Global.exec_files = [ |
|
40 | 40 | # 'mycode.py', |
|
41 | 41 | # 'fancy.ipy' |
|
42 | 42 | # ] |
|
43 | 43 | |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | # InteractiveShell options |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | |
|
48 | 48 | # c.InteractiveShell.autocall = 1 |
|
49 | 49 | |
|
50 | 50 | # c.InteractiveShell.autoedit_syntax = False |
|
51 | 51 | |
|
52 | 52 | # c.InteractiveShell.autoindent = True |
|
53 | 53 | |
|
54 | 54 | # c.InteractiveShell.automagic = False |
|
55 | 55 | |
|
56 | 56 | # c.InteractiveShell.banner1 = 'This if for overriding the default IPython banner' |
|
57 | 57 | |
|
58 | 58 | # c.InteractiveShell.banner2 = "This is for extra banner text" |
|
59 | 59 | |
|
60 | 60 | # c.InteractiveShell.cache_size = 1000 |
|
61 | 61 | |
|
62 | 62 | # c.InteractiveShell.colors = 'LightBG' |
|
63 | 63 | |
|
64 | 64 | # c.InteractiveShell.color_info = True |
|
65 | 65 | |
|
66 | 66 | # c.InteractiveShell.confirm_exit = True |
|
67 | 67 | |
|
68 | 68 | # c.InteractiveShell.deep_reload = False |
|
69 | 69 | |
|
70 | 70 | # c.InteractiveShell.editor = 'nano' |
|
71 | 71 | |
|
72 | 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 | 78 | # c.InteractiveShell.object_info_string_level = 0 |
|
79 | 79 | |
|
80 | 80 | # c.InteractiveShell.pager = 'less' |
|
81 | 81 | |
|
82 | 82 | # c.InteractiveShell.pdb = False |
|
83 | 83 | |
|
84 | 84 | # c.InteractiveShell.pprint = True |
|
85 | 85 | |
|
86 | 86 | # c.InteractiveShell.prompt_in1 = 'In [\#]: ' |
|
87 | 87 | # c.InteractiveShell.prompt_in2 = ' .\D.: ' |
|
88 | 88 | # c.InteractiveShell.prompt_out = 'Out[\#]: ' |
|
89 | 89 | # c.InteractiveShell.prompts_pad_left = True |
|
90 | 90 | |
|
91 | 91 | # c.InteractiveShell.quiet = False |
|
92 | 92 | |
|
93 | 93 | # Readline |
|
94 | 94 | # c.InteractiveShell.readline_use = True |
|
95 | 95 | |
|
96 | 96 | # c.InteractiveShell.readline_parse_and_bind = [ |
|
97 | 97 | # 'tab: complete', |
|
98 | 98 | # '"\C-l": possible-completions', |
|
99 | 99 | # 'set show-all-if-ambiguous on', |
|
100 | 100 | # '"\C-o": tab-insert', |
|
101 | 101 | # '"\M-i": " "', |
|
102 | 102 | # '"\M-o": "\d\d\d\d"', |
|
103 | 103 | # '"\M-I": "\d\d\d\d"', |
|
104 | 104 | # '"\C-r": reverse-search-history', |
|
105 | 105 | # '"\C-s": forward-search-history', |
|
106 | 106 | # '"\C-p": history-search-backward', |
|
107 | 107 | # '"\C-n": history-search-forward', |
|
108 | 108 | # '"\e[A": history-search-backward', |
|
109 | 109 | # '"\e[B": history-search-forward', |
|
110 | 110 | # '"\C-k": kill-line', |
|
111 | 111 | # '"\C-u": unix-line-discard', |
|
112 | 112 | # ] |
|
113 | 113 | # c.InteractiveShell.readline_remove_delims = '-/~' |
|
114 | 114 | # c.InteractiveShell.readline_merge_completions = True |
|
115 | 115 | # c.InteractiveShell.readline_omit_names = 0 |
|
116 | 116 | |
|
117 | 117 | # c.InteractiveShell.screen_length = 0 |
|
118 | 118 | |
|
119 | 119 | # c.InteractiveShell.separate_in = '\n' |
|
120 | 120 | # c.InteractiveShell.separate_out = '' |
|
121 | 121 | # c.InteractiveShell.separate_out2 = '' |
|
122 | 122 | |
|
123 | 123 | # c.InteractiveShell.system_header = "IPython system call: " |
|
124 | 124 | |
|
125 | 125 | # c.InteractiveShell.system_verbose = True |
|
126 | 126 | |
|
127 | 127 | # c.InteractiveShell.term_title = False |
|
128 | 128 | |
|
129 | 129 | # c.InteractiveShell.wildcards_case_sensitive = True |
|
130 | 130 | |
|
131 | 131 | # c.InteractiveShell.xmode = 'Context' |
|
132 | 132 | |
|
133 | 133 | #----------------------------------------------------------------------------- |
|
134 | 134 | # PrefilterManager options |
|
135 | 135 | #----------------------------------------------------------------------------- |
|
136 | 136 | |
|
137 | 137 | # c.PrefilterManager.multi_line_specials = True |
|
138 | 138 | |
|
139 | 139 | #----------------------------------------------------------------------------- |
|
140 | 140 | # AliasManager options |
|
141 | 141 | #----------------------------------------------------------------------------- |
|
142 | 142 | |
|
143 | 143 | # Do this to disable all defaults |
|
144 | 144 | # c.AliasManager.default_aliases = [] |
|
145 | 145 | |
|
146 | 146 | # c.AliasManager.user_aliases = [ |
|
147 | 147 | # ('foo', 'echo Hi') |
|
148 | 148 | # ] No newline at end of file |
@@ -1,329 +1,377 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | # encoding: utf-8 | |
|
1 | # coding: utf-8 | |
|
3 | 2 | """A simple configuration system. |
|
4 | 3 | |
|
5 |
Authors |
|
|
6 | ||
|
4 | Authors | |
|
5 | ------- | |
|
7 | 6 | * Brian Granger |
|
7 | * Fernando Perez | |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Imports |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | import __builtin__ |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | |
|
25 | 25 | from IPython.external import argparse |
|
26 | 26 | from IPython.utils.genutils import filefind |
|
27 | 27 | |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | # Exceptions |
|
30 | 30 | #----------------------------------------------------------------------------- |
|
31 | 31 | |
|
32 | 32 | |
|
33 | 33 | class ConfigError(Exception): |
|
34 | 34 | pass |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | class ConfigLoaderError(ConfigError): |
|
38 | 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 | 60 | # Config class for holding config information |
|
43 | 61 | #----------------------------------------------------------------------------- |
|
44 | 62 | |
|
45 | 63 | |
|
46 | 64 | class Config(dict): |
|
47 | 65 | """An attribute based dict that can do smart merges.""" |
|
48 | 66 | |
|
49 | 67 | def __init__(self, *args, **kwds): |
|
50 | 68 | dict.__init__(self, *args, **kwds) |
|
51 | 69 | # This sets self.__dict__ = self, but it has to be done this way |
|
52 | 70 | # because we are also overriding __setattr__. |
|
53 | 71 | dict.__setattr__(self, '__dict__', self) |
|
54 | 72 | |
|
55 | 73 | def _merge(self, other): |
|
56 | 74 | to_update = {} |
|
57 | 75 | for k, v in other.items(): |
|
58 | 76 | if not self.has_key(k): |
|
59 | 77 | to_update[k] = v |
|
60 | 78 | else: # I have this key |
|
61 | 79 | if isinstance(v, Config): |
|
62 | 80 | # Recursively merge common sub Configs |
|
63 | 81 | self[k]._merge(v) |
|
64 | 82 | else: |
|
65 | 83 | # Plain updates for non-Configs |
|
66 | 84 | to_update[k] = v |
|
67 | 85 | |
|
68 | 86 | self.update(to_update) |
|
69 | 87 | |
|
70 | 88 | def _is_section_key(self, key): |
|
71 | 89 | if key[0].upper()==key[0] and not key.startswith('_'): |
|
72 | 90 | return True |
|
73 | 91 | else: |
|
74 | 92 | return False |
|
75 | 93 | |
|
76 | 94 | def has_key(self, key): |
|
77 | 95 | if self._is_section_key(key): |
|
78 | 96 | return True |
|
79 | 97 | else: |
|
80 | 98 | return dict.has_key(self, key) |
|
81 | 99 | |
|
82 | 100 | def _has_section(self, key): |
|
83 | 101 | if self._is_section_key(key): |
|
84 | 102 | if dict.has_key(self, key): |
|
85 | 103 | return True |
|
86 | 104 | return False |
|
87 | 105 | |
|
88 | 106 | def copy(self): |
|
89 | 107 | return type(self)(dict.copy(self)) |
|
90 | 108 | |
|
91 | 109 | def __copy__(self): |
|
92 | 110 | return self.copy() |
|
93 | 111 | |
|
94 | 112 | def __deepcopy__(self, memo): |
|
95 | 113 | import copy |
|
96 | 114 | return type(self)(copy.deepcopy(self.items())) |
|
97 | 115 | |
|
98 | 116 | def __getitem__(self, key): |
|
99 | 117 | # Because we use this for an exec namespace, we need to delegate |
|
100 | 118 | # the lookup of names in __builtin__ to itself. This means |
|
101 | 119 | # that you can't have section or attribute names that are |
|
102 | 120 | # builtins. |
|
103 | 121 | try: |
|
104 | 122 | return getattr(__builtin__, key) |
|
105 | 123 | except AttributeError: |
|
106 | 124 | pass |
|
107 | 125 | if self._is_section_key(key): |
|
108 | 126 | try: |
|
109 | 127 | return dict.__getitem__(self, key) |
|
110 | 128 | except KeyError: |
|
111 | 129 | c = Config() |
|
112 | 130 | dict.__setitem__(self, key, c) |
|
113 | 131 | return c |
|
114 | 132 | else: |
|
115 | 133 | return dict.__getitem__(self, key) |
|
116 | 134 | |
|
117 | 135 | def __setitem__(self, key, value): |
|
118 | 136 | # Don't allow names in __builtin__ to be modified. |
|
119 | 137 | if hasattr(__builtin__, key): |
|
120 | 138 | raise ConfigError('Config variable names cannot have the same name ' |
|
121 | 139 | 'as a Python builtin: %s' % key) |
|
122 | 140 | if self._is_section_key(key): |
|
123 | 141 | if not isinstance(value, Config): |
|
124 | 142 | raise ValueError('values whose keys begin with an uppercase ' |
|
125 | 143 | 'char must be Config instances: %r, %r' % (key, value)) |
|
126 | 144 | else: |
|
127 | 145 | dict.__setitem__(self, key, value) |
|
128 | 146 | |
|
129 | 147 | def __getattr__(self, key): |
|
130 | 148 | try: |
|
131 | 149 | return self.__getitem__(key) |
|
132 | 150 | except KeyError, e: |
|
133 | 151 | raise AttributeError(e) |
|
134 | 152 | |
|
135 | 153 | def __setattr__(self, key, value): |
|
136 | 154 | try: |
|
137 | 155 | self.__setitem__(key, value) |
|
138 | 156 | except KeyError, e: |
|
139 | 157 | raise AttributeError(e) |
|
140 | 158 | |
|
141 | 159 | def __delattr__(self, key): |
|
142 | 160 | try: |
|
143 | 161 | dict.__delitem__(self, key) |
|
144 | 162 | except KeyError, e: |
|
145 | 163 | raise AttributeError(e) |
|
146 | 164 | |
|
147 | 165 | |
|
148 | 166 | #----------------------------------------------------------------------------- |
|
149 | 167 | # Config loading classes |
|
150 | 168 | #----------------------------------------------------------------------------- |
|
151 | 169 | |
|
152 | 170 | |
|
153 | 171 | class ConfigLoader(object): |
|
154 | 172 | """A object for loading configurations from just about anywhere. |
|
155 | 173 | |
|
156 | 174 | The resulting configuration is packaged as a :class:`Struct`. |
|
157 | 175 | |
|
158 | 176 | Notes |
|
159 | 177 | ----- |
|
160 | 178 | A :class:`ConfigLoader` does one thing: load a config from a source |
|
161 | 179 | (file, command line arguments) and returns the data as a :class:`Struct`. |
|
162 | 180 | There are lots of things that :class:`ConfigLoader` does not do. It does |
|
163 | 181 | not implement complex logic for finding config files. It does not handle |
|
164 | 182 | default values or merge multiple configs. These things need to be |
|
165 | 183 | handled elsewhere. |
|
166 | 184 | """ |
|
167 | 185 | |
|
168 | 186 | def __init__(self): |
|
169 | 187 | """A base class for config loaders. |
|
170 | 188 | |
|
171 | 189 | Examples |
|
172 | 190 | -------- |
|
173 | 191 | |
|
174 | 192 | >>> cl = ConfigLoader() |
|
175 | 193 | >>> config = cl.load_config() |
|
176 | 194 | >>> config |
|
177 | 195 | {} |
|
178 | 196 | """ |
|
179 | 197 | self.clear() |
|
180 | 198 | |
|
181 | 199 | def clear(self): |
|
182 | 200 | self.config = Config() |
|
183 | 201 | |
|
184 | 202 | def load_config(self): |
|
185 | 203 | """Load a config from somewhere, return a Struct. |
|
186 | 204 | |
|
187 | 205 | Usually, this will cause self.config to be set and then returned. |
|
188 | 206 | """ |
|
189 | 207 | return self.config |
|
190 | 208 | |
|
191 | 209 | |
|
192 | 210 | class FileConfigLoader(ConfigLoader): |
|
193 | 211 | """A base class for file based configurations. |
|
194 | 212 | |
|
195 | 213 | As we add more file based config loaders, the common logic should go |
|
196 | 214 | here. |
|
197 | 215 | """ |
|
198 | 216 | pass |
|
199 | 217 | |
|
200 | 218 | |
|
201 | 219 | class PyFileConfigLoader(FileConfigLoader): |
|
202 | 220 | """A config loader for pure python files. |
|
203 | 221 | |
|
204 | 222 | This calls execfile on a plain python file and looks for attributes |
|
205 | 223 | that are all caps. These attribute are added to the config Struct. |
|
206 | 224 | """ |
|
207 | 225 | |
|
208 | 226 | def __init__(self, filename, path=None): |
|
209 | 227 | """Build a config loader for a filename and path. |
|
210 | 228 | |
|
211 | 229 | Parameters |
|
212 | 230 | ---------- |
|
213 | 231 | filename : str |
|
214 | 232 | The file name of the config file. |
|
215 | 233 | path : str, list, tuple |
|
216 | 234 | The path to search for the config file on, or a sequence of |
|
217 | 235 | paths to try in order. |
|
218 | 236 | """ |
|
219 | 237 | super(PyFileConfigLoader, self).__init__() |
|
220 | 238 | self.filename = filename |
|
221 | 239 | self.path = path |
|
222 | 240 | self.full_filename = '' |
|
223 | 241 | self.data = None |
|
224 | 242 | |
|
225 | 243 | def load_config(self): |
|
226 | 244 | """Load the config from a file and return it as a Struct.""" |
|
227 | 245 | self._find_file() |
|
228 | 246 | self._read_file_as_dict() |
|
229 | 247 | self._convert_to_config() |
|
230 | 248 | return self.config |
|
231 | 249 | |
|
232 | 250 | def _find_file(self): |
|
233 | 251 | """Try to find the file by searching the paths.""" |
|
234 | 252 | self.full_filename = filefind(self.filename, self.path) |
|
235 | 253 | |
|
236 | 254 | def _read_file_as_dict(self): |
|
237 | 255 | """Load the config file into self.config, with recursive loading.""" |
|
238 | 256 | # This closure is made available in the namespace that is used |
|
239 | 257 | # to exec the config file. This allows users to call |
|
240 | 258 | # load_subconfig('myconfig.py') to load config files recursively. |
|
241 | 259 | # It needs to be a closure because it has references to self.path |
|
242 | 260 | # and self.config. The sub-config is loaded with the same path |
|
243 | 261 | # as the parent, but it uses an empty config which is then merged |
|
244 | 262 | # with the parents. |
|
245 | 263 | def load_subconfig(fname): |
|
246 | 264 | loader = PyFileConfigLoader(fname, self.path) |
|
247 | sub_config = loader.load_config() | |
|
248 | self.config._merge(sub_config) | |
|
265 | try: | |
|
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 | 274 | # Again, this needs to be a closure and should be used in config |
|
251 | 275 | # files to get the config being loaded. |
|
252 | 276 | def get_config(): |
|
253 | 277 | return self.config |
|
254 | 278 | |
|
255 | 279 | namespace = dict(load_subconfig=load_subconfig, get_config=get_config) |
|
256 | 280 | execfile(self.full_filename, namespace) |
|
257 | 281 | |
|
258 | 282 | def _convert_to_config(self): |
|
259 | 283 | if self.data is None: |
|
260 | 284 | ConfigLoaderError('self.data does not exist') |
|
261 | 285 | |
|
262 | 286 | |
|
263 | 287 | class CommandLineConfigLoader(ConfigLoader): |
|
264 | 288 | """A config loader for command line arguments. |
|
265 | 289 | |
|
266 | 290 | As we add more command line based loaders, the common logic should go |
|
267 | 291 | here. |
|
268 | 292 | """ |
|
269 | 293 | |
|
270 | 294 | |
|
271 | class NoConfigDefault(object): pass | |
|
272 | NoConfigDefault = NoConfigDefault() | |
|
295 | class __NoConfigDefault(object): pass | |
|
296 | NoConfigDefault = __NoConfigDefault() | |
|
297 | ||
|
273 | 298 | |
|
274 | 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'))] | |
|
277 | arguments = () | |
|
278 | ||
|
279 | def __init__(self, *args, **kw): | |
|
303 | def __init__(self, argv=None, arguments=(), *args, **kw): | |
|
280 | 304 | """Create a config loader for use with argparse. |
|
281 | 305 | |
|
282 | The args and kwargs arguments here are passed onto the constructor | |
|
283 | of :class:`argparse.ArgumentParser`. | |
|
306 | With the exception of ``argv`` and ``arguments``, other args and kwargs | |
|
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 | 321 | super(CommandLineConfigLoader, self).__init__() |
|
322 | if argv == None: | |
|
323 | argv = sys.argv[1:] | |
|
324 | self.argv = argv | |
|
325 | self.arguments = arguments | |
|
286 | 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 | 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 | 344 | self._create_parser() |
|
292 | 345 | self._parse_args(args) |
|
293 | 346 | self._convert_to_config() |
|
294 | 347 | return self.config |
|
295 | 348 | |
|
296 | 349 | def get_extra_args(self): |
|
297 | 350 | if hasattr(self, 'extra_args'): |
|
298 | 351 | return self.extra_args |
|
299 | 352 | else: |
|
300 | 353 | return [] |
|
301 | 354 | |
|
302 | 355 | def _create_parser(self): |
|
303 |
self.parser = |
|
|
356 | self.parser = ArgumentParser(*self.args, **self.kw) | |
|
304 | 357 | self._add_arguments() |
|
305 | 358 | self._add_other_arguments() |
|
306 | 359 | |
|
307 | def _add_other_arguments(self): | |
|
308 | pass | |
|
309 | ||
|
310 | 360 | def _add_arguments(self): |
|
311 | 361 | for argument in self.arguments: |
|
312 | if not argument[1].has_key('default'): | |
|
313 | argument[1]['default'] = NoConfigDefault | |
|
314 | 362 | self.parser.add_argument(*argument[0],**argument[1]) |
|
315 | 363 | |
|
316 |
def _ |
|
|
317 | """self.parser->self.parsed_data""" | |
|
318 |
|
|
|
319 | self.parsed_data, self.extra_args = self.parser.parse_known_args() | |
|
320 | else: | |
|
321 | self.parsed_data, self.extra_args = self.parser.parse_known_args(args) | |
|
364 | def _add_other_arguments(self): | |
|
365 | """Meant for subclasses to add their own arguments.""" | |
|
366 | pass | |
|
367 | ||
|
368 | def _parse_args(self, args): | |
|
369 | """self.parser->self.parsed_data""" | |
|
370 | self.parsed_data, self.extra_args = self.parser.parse_known_args(args) | |
|
322 | 371 | |
|
323 | 372 | def _convert_to_config(self): |
|
324 | 373 | """self.parsed_data->self.config""" |
|
325 | 374 | for k, v in vars(self.parsed_data).items(): |
|
326 | 375 | if v is not NoConfigDefault: |
|
327 | 376 | exec_str = 'self.config.' + k + '= v' |
|
328 | 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 |
@@ -1,163 +1,162 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | Tests for IPython.config.loader |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez (design help) |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | import os |
|
24 | 24 | from tempfile import mkstemp |
|
25 | 25 | from unittest import TestCase |
|
26 | 26 | |
|
27 | 27 | from IPython.config.loader import ( |
|
28 | 28 | Config, |
|
29 | 29 | PyFileConfigLoader, |
|
30 | 30 | ArgParseConfigLoader, |
|
31 | 31 | ConfigError |
|
32 | 32 | ) |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Actual tests |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | pyfile = """ |
|
40 | a = 10 | |
|
41 | b = 20 | |
|
42 | Foo.Bar.value = 10 | |
|
43 |
Foo.Ba |
|
|
44 | D.C.value = 'hi there' | |
|
40 | c = get_config() | |
|
41 | c.a = 10 | |
|
42 | c.b = 20 | |
|
43 | c.Foo.Bar.value = 10 | |
|
44 | c.Foo.Bam.value = range(10) | |
|
45 | c.D.C.value = 'hi there' | |
|
45 | 46 | """ |
|
46 | 47 | |
|
47 | 48 | class TestPyFileCL(TestCase): |
|
48 | 49 | |
|
49 | 50 | def test_basic(self): |
|
50 | fd, fname = mkstemp() | |
|
51 | fd, fname = mkstemp('.py') | |
|
51 | 52 | f = os.fdopen(fd, 'w') |
|
52 | 53 | f.write(pyfile) |
|
53 | 54 | f.close() |
|
54 | 55 | # Unlink the file |
|
55 | 56 | cl = PyFileConfigLoader(fname) |
|
56 | 57 | config = cl.load_config() |
|
57 | 58 | self.assertEquals(config.a, 10) |
|
58 | 59 | self.assertEquals(config.b, 20) |
|
59 | 60 | self.assertEquals(config.Foo.Bar.value, 10) |
|
60 | 61 | self.assertEquals(config.Foo.Bam.value, range(10)) |
|
61 | 62 | self.assertEquals(config.D.C.value, 'hi there') |
|
62 | 63 | |
|
63 | 64 | |
|
64 | 65 | class TestArgParseCL(TestCase): |
|
65 | 66 | |
|
66 | 67 | def test_basic(self): |
|
67 | 68 | |
|
68 | class MyLoader(ArgParseConfigLoader): | |
|
69 | arguments = ( | |
|
69 | arguments = ( | |
|
70 | 70 | (('-f','--foo'), dict(dest='Global.foo', type=str)), |
|
71 | 71 | (('-b',), dict(dest='MyClass.bar', type=int)), |
|
72 | 72 | (('-n',), dict(dest='n', action='store_true')), |
|
73 | 73 | (('Global.bam',), dict(type=str)) |
|
74 | 74 | ) |
|
75 | ||
|
76 | cl = MyLoader() | |
|
75 | cl = ArgParseConfigLoader(arguments=arguments) | |
|
77 | 76 | config = cl.load_config('-f hi -b 10 -n wow'.split()) |
|
78 | 77 | self.assertEquals(config.Global.foo, 'hi') |
|
79 | 78 | self.assertEquals(config.MyClass.bar, 10) |
|
80 | 79 | self.assertEquals(config.n, True) |
|
81 | 80 | self.assertEquals(config.Global.bam, 'wow') |
|
82 | 81 | |
|
83 | 82 | def test_add_arguments(self): |
|
84 | 83 | |
|
85 | 84 | class MyLoader(ArgParseConfigLoader): |
|
86 | 85 | def _add_arguments(self): |
|
87 | 86 | subparsers = self.parser.add_subparsers(dest='subparser_name') |
|
88 | 87 | subparser1 = subparsers.add_parser('1') |
|
89 | 88 | subparser1.add_argument('-x',dest='Global.x') |
|
90 | 89 | subparser2 = subparsers.add_parser('2') |
|
91 | 90 | subparser2.add_argument('y') |
|
92 | 91 | |
|
93 | 92 | cl = MyLoader() |
|
94 | 93 | config = cl.load_config('2 frobble'.split()) |
|
95 | 94 | self.assertEquals(config.subparser_name, '2') |
|
96 | 95 | self.assertEquals(config.y, 'frobble') |
|
97 | 96 | config = cl.load_config('1 -x frobble'.split()) |
|
98 | 97 | self.assertEquals(config.subparser_name, '1') |
|
99 | 98 | self.assertEquals(config.Global.x, 'frobble') |
|
100 | 99 | |
|
101 | 100 | class TestConfig(TestCase): |
|
102 | 101 | |
|
103 | 102 | def test_setget(self): |
|
104 | 103 | c = Config() |
|
105 | 104 | c.a = 10 |
|
106 | 105 | self.assertEquals(c.a, 10) |
|
107 | 106 | self.assertEquals(c.has_key('b'), False) |
|
108 | 107 | |
|
109 | 108 | def test_auto_section(self): |
|
110 | 109 | c = Config() |
|
111 | 110 | self.assertEquals(c.has_key('A'), True) |
|
112 | 111 | self.assertEquals(c._has_section('A'), False) |
|
113 | 112 | A = c.A |
|
114 | 113 | A.foo = 'hi there' |
|
115 | 114 | self.assertEquals(c._has_section('A'), True) |
|
116 | 115 | self.assertEquals(c.A.foo, 'hi there') |
|
117 | 116 | del c.A |
|
118 | 117 | self.assertEquals(len(c.A.keys()),0) |
|
119 | 118 | |
|
120 | 119 | def test_merge_doesnt_exist(self): |
|
121 | 120 | c1 = Config() |
|
122 | 121 | c2 = Config() |
|
123 | 122 | c2.bar = 10 |
|
124 | 123 | c2.Foo.bar = 10 |
|
125 | 124 | c1._merge(c2) |
|
126 | 125 | self.assertEquals(c1.Foo.bar, 10) |
|
127 | 126 | self.assertEquals(c1.bar, 10) |
|
128 | 127 | c2.Bar.bar = 10 |
|
129 | 128 | c1._merge(c2) |
|
130 | 129 | self.assertEquals(c1.Bar.bar, 10) |
|
131 | 130 | |
|
132 | 131 | def test_merge_exists(self): |
|
133 | 132 | c1 = Config() |
|
134 | 133 | c2 = Config() |
|
135 | 134 | c1.Foo.bar = 10 |
|
136 | 135 | c1.Foo.bam = 30 |
|
137 | 136 | c2.Foo.bar = 20 |
|
138 | 137 | c2.Foo.wow = 40 |
|
139 | 138 | c1._merge(c2) |
|
140 | 139 | self.assertEquals(c1.Foo.bam, 30) |
|
141 | 140 | self.assertEquals(c1.Foo.bar, 20) |
|
142 | 141 | self.assertEquals(c1.Foo.wow, 40) |
|
143 | 142 | c2.Foo.Bam.bam = 10 |
|
144 | 143 | c1._merge(c2) |
|
145 | 144 | self.assertEquals(c1.Foo.Bam.bam, 10) |
|
146 | 145 | |
|
147 | 146 | def test_deepcopy(self): |
|
148 | 147 | c1 = Config() |
|
149 | 148 | c1.Foo.bar = 10 |
|
150 | 149 | c1.Foo.bam = 30 |
|
151 | 150 | c1.a = 'asdf' |
|
152 | 151 | c1.b = range(10) |
|
153 | 152 | import copy |
|
154 | 153 | c2 = copy.deepcopy(c1) |
|
155 | 154 | self.assertEquals(c1, c2) |
|
156 | 155 | self.assert_(c1 is not c2) |
|
157 | 156 | self.assert_(c1.Foo is not c2.Foo) |
|
158 | 157 | |
|
159 | 158 | def test_builtin(self): |
|
160 | 159 | c1 = Config() |
|
161 | 160 | exec 'foo = True' in c1 |
|
162 | 161 | self.assertEquals(c1.foo, True) |
|
163 | 162 | self.assertRaises(ConfigError, setattr, c1, 'ValueError', 10) |
@@ -1,300 +1,488 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | 1 |
|
|
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 | 11 | Authors: |
|
7 | 12 | |
|
8 | 13 | * Brian Granger |
|
9 | 14 | * Fernando Perez |
|
10 | 15 | |
|
11 | 16 | Notes |
|
12 | 17 | ----- |
|
13 | 18 | """ |
|
14 | 19 | |
|
15 | 20 | #----------------------------------------------------------------------------- |
|
16 | 21 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 22 | # |
|
18 | 23 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 24 | # the file COPYING, distributed as part of this software. |
|
20 | 25 | #----------------------------------------------------------------------------- |
|
21 | 26 | |
|
22 | 27 | #----------------------------------------------------------------------------- |
|
23 | 28 | # Imports |
|
24 | 29 | #----------------------------------------------------------------------------- |
|
25 | 30 | |
|
26 | 31 | import logging |
|
27 | 32 | import os |
|
28 | 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 | 37 | from IPython.config.loader import ( |
|
34 | 38 | PyFileConfigLoader, |
|
35 | 39 | ArgParseConfigLoader, |
|
36 | 40 | Config, |
|
37 | NoConfigDefault | |
|
38 | 41 | ) |
|
39 | 42 | |
|
40 | 43 | #----------------------------------------------------------------------------- |
|
41 | 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 | 47 | class ApplicationError(Exception): |
|
67 | 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 | 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 |
|
|
|
75 | name = 'ipython' | |
|
76 | ||
|
77 | def __init__(self): | |
|
110 | name = u'ipython' | |
|
111 | description = 'IPython: an enhanced interactive Python shell.' | |
|
112 | #: usage message printed by argparse. If None, auto-generate | |
|
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 | 153 | self.init_logger() |
|
79 | self.default_config_file_name = self.config_file_name | |
|
80 | 154 | |
|
81 | 155 | def init_logger(self): |
|
82 | 156 | self.log = logging.getLogger(self.__class__.__name__) |
|
83 | 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 | 159 | self._log_handler = logging.StreamHandler() |
|
86 | 160 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
87 | 161 | self._log_handler.setFormatter(self._log_formatter) |
|
88 | 162 | self.log.addHandler(self._log_handler) |
|
89 | 163 | |
|
90 | 164 | def _set_log_level(self, level): |
|
91 | 165 | self.log.setLevel(level) |
|
92 | 166 | |
|
93 | 167 | def _get_log_level(self): |
|
94 | 168 | return self.log.level |
|
95 | 169 | |
|
96 | 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 | 232 | def start(self): |
|
99 | 233 | """Start the application.""" |
|
100 | self.attempt(self.create_default_config) | |
|
101 | self.attempt(self.pre_load_command_line_config) | |
|
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) | |
|
234 | self.initialize() | |
|
235 | self.start_app() | |
|
115 | 236 | |
|
116 | 237 | #------------------------------------------------------------------------- |
|
117 | 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 | 246 | def create_default_config(self): |
|
121 | 247 | """Create defaults that can't be set elsewhere. |
|
122 | 248 | |
|
123 | 249 | For the most part, we try to set default in the class attributes |
|
124 | 250 | of Components. But, defaults the top-level Application (which is |
|
125 | 251 | not a HasTraits or Component) are not set in this way. Instead |
|
126 | 252 | we set them here. The Global section is for variables like this that |
|
127 | 253 | don't belong to a particular component. |
|
128 | 254 | """ |
|
129 |
|
|
|
130 |
|
|
|
255 | c = Config() | |
|
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 | 261 | self.log.debug('Default config loaded:') |
|
132 | 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 | 271 | def create_command_line_config(self): |
|
135 | 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 | 279 | def pre_load_command_line_config(self): |
|
139 | 280 | """Do actions just before loading the command line config.""" |
|
140 | 281 | pass |
|
141 | 282 | |
|
142 | 283 | def load_command_line_config(self): |
|
143 | """Load the command line config. | |
|
144 | ||
|
145 | This method also sets ``self.debug``. | |
|
146 | """ | |
|
147 | ||
|
284 | """Load the command line config.""" | |
|
148 | 285 | loader = self.create_command_line_config() |
|
149 | 286 | self.command_line_config = loader.load_config() |
|
150 | 287 | self.extra_args = loader.get_extra_args() |
|
151 | 288 | |
|
289 | def set_command_line_config_log_level(self): | |
|
152 | 290 | try: |
|
153 | 291 | self.log_level = self.command_line_config.Global.log_level |
|
154 | 292 | except AttributeError: |
|
155 | pass # Use existing value which is set in Application.init_logger. | |
|
156 | self.log.debug("Command line config loaded:") | |
|
157 | self.log.debug(repr(self.command_line_config)) | |
|
293 | pass | |
|
158 | 294 | |
|
159 | 295 | def post_load_command_line_config(self): |
|
160 | 296 | """Do actions just after loading the command line config.""" |
|
161 | 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 | 304 | """Set the IPython directory. |
|
165 | 305 | |
|
166 | This sets ``self.ipythondir``, but the actual value that is passed | |
|
167 |
t |
|
|
168 |
``self.command_line_config``. This also add |
|
|
169 |
``sys.path`` so config files there can be reference |
|
|
306 | This sets ``self.ipython_dir``, but the actual value that is passed to | |
|
307 | the application is kept in either ``self.default_config`` or | |
|
308 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to | |
|
309 | ``sys.path`` so config files there can be referenced by other config | |
|
170 | 310 | files. |
|
171 | 311 | """ |
|
172 | 312 | |
|
173 | 313 | try: |
|
174 | self.ipythondir = self.command_line_config.Global.ipythondir | |
|
314 | self.ipython_dir = self.command_line_config.Global.ipython_dir | |
|
175 | 315 | except AttributeError: |
|
176 | self.ipythondir = self.default_config.Global.ipythondir | |
|
177 | sys.path.append(os.path.abspath(self.ipythondir)) | |
|
178 | if not os.path.isdir(self.ipythondir): | |
|
179 |
os.makedirs(self.ipythondir, mode |
|
|
180 | self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir) | |
|
316 | self.ipython_dir = self.default_config.Global.ipython_dir | |
|
317 | sys.path.append(os.path.abspath(self.ipython_dir)) | |
|
318 | if not os.path.isdir(self.ipython_dir): | |
|
319 | os.makedirs(self.ipython_dir, mode=0777) | |
|
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 | 331 | def find_config_file_name(self): |
|
183 | 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 | |
|
186 | it. The search paths for the config file are set in | |
|
187 |
:meth:`find_config_file_paths` and then passed |
|
|
188 | loader where they are resolved to an absolute path. | |
|
334 | This must set ``self.config_file_name`` to the filename of the | |
|
335 | config file to use (just the filename). The search paths for the | |
|
336 | config file are set in :meth:`find_config_file_paths` and then passed | |
|
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 | 342 | try: |
|
192 | 343 | self.config_file_name = self.command_line_config.Global.config_file |
|
193 | 344 | except AttributeError: |
|
194 | 345 | pass |
|
195 | 346 | |
|
196 | 347 | try: |
|
197 | 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 | 349 | except AttributeError: |
|
202 | 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 | 356 | def find_config_file_paths(self): |
|
205 |
"""Set the search paths for resolving the config file. |
|
|
206 | self.config_file_paths = (os.getcwd(), self.ipythondir) | |
|
357 | """Set the search paths for resolving the config file. | |
|
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 | 368 | def pre_load_file_config(self): |
|
209 | 369 | """Do actions before the config file is loaded.""" |
|
210 | 370 | pass |
|
211 | 371 | |
|
212 | 372 | def load_file_config(self): |
|
213 | 373 | """Load the config file. |
|
214 | 374 | |
|
215 | 375 | This tries to load the config file from disk. If successful, the |
|
216 | 376 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
217 | 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 | 381 | loader = PyFileConfigLoader(self.config_file_name, |
|
221 | 382 | path=self.config_file_paths) |
|
222 | 383 | try: |
|
223 | 384 | self.file_config = loader.load_config() |
|
224 | 385 | self.file_config.Global.config_file = loader.full_filename |
|
225 | 386 | except IOError: |
|
226 | 387 | # Only warn if the default config file was NOT being used. |
|
227 | 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 | 390 | self.config_file_name, exc_info=True) |
|
230 | 391 | self.file_config = Config() |
|
231 | 392 | except: |
|
232 |
self.log.warn("Error loading config file: |
|
|
233 |
|
|
|
393 | self.log.warn("Error loading config file: %s" % | |
|
394 | self.config_file_name, exc_info=True) | |
|
234 | 395 | self.file_config = Config() |
|
235 | else: | |
|
236 | self.log.debug("Config file loaded: <%s>" % loader.full_filename) | |
|
237 | self.log.debug(repr(self.file_config)) | |
|
396 | ||
|
397 | def set_file_config_log_level(self): | |
|
238 | 398 | # We need to keeep self.log_level updated. But we only use the value |
|
239 | 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 | 401 | if not hasattr(self.command_line_config.Global, 'log_level'): |
|
242 | 402 | try: |
|
243 | 403 | self.log_level = self.file_config.Global.log_level |
|
244 | 404 | except AttributeError: |
|
245 | 405 | pass # Use existing value |
|
246 | 406 | |
|
247 | 407 | def post_load_file_config(self): |
|
248 | 408 | """Do actions after the config file is loaded.""" |
|
249 | 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 | 417 | def merge_configs(self): |
|
252 | 418 | """Merge the default, command line and file config objects.""" |
|
253 | 419 | config = Config() |
|
254 | 420 | config._merge(self.default_config) |
|
255 | config._merge(self.file_config) | |
|
256 |
config._merge(self. |
|
|
421 | if self.override_config is None: | |
|
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 | 432 | self.master_config = config |
|
433 | self.config = config | |
|
434 | ||
|
435 | def log_master_config(self): | |
|
258 | 436 | self.log.debug("Master config created:") |
|
259 | 437 | self.log.debug(repr(self.master_config)) |
|
260 | 438 | |
|
261 | 439 | def pre_construct(self): |
|
262 | 440 | """Do actions after the config has been built, but before construct.""" |
|
263 | 441 | pass |
|
264 | 442 | |
|
265 | 443 | def construct(self): |
|
266 | 444 | """Construct the main components that make up this app.""" |
|
267 | 445 | self.log.debug("Constructing components for application") |
|
268 | 446 | |
|
269 | 447 | def post_construct(self): |
|
270 | 448 | """Do actions after construct, but before starting the app.""" |
|
271 | 449 | pass |
|
272 | 450 | |
|
273 | 451 | def start_app(self): |
|
274 | 452 | """Actually start the app.""" |
|
275 | 453 | self.log.debug("Starting application") |
|
276 | 454 | |
|
277 | 455 | #------------------------------------------------------------------------- |
|
278 | 456 | # Utility methods |
|
279 | 457 | #------------------------------------------------------------------------- |
|
280 | 458 | |
|
281 | 459 | def abort(self): |
|
282 | 460 | """Abort the starting of the application.""" |
|
283 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) | |
|
284 | sys.exit(1) | |
|
461 | if self._exiting: | |
|
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): | |
|
287 | self.log.critical("Aborting application: %s" % self.name) | |
|
288 | sys.exit(1) | |
|
468 | def exit(self, exit_status=0): | |
|
469 | if self._exiting: | |
|
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 | 476 | def attempt(self, func, action='abort'): |
|
291 | 477 | try: |
|
292 | 478 | func() |
|
293 | 479 | except SystemExit: |
|
294 |
se |
|
|
480 | raise | |
|
295 | 481 | except: |
|
296 | 482 | if action == 'abort': |
|
483 | self.log.critical("Aborting application: %s" % self.name, | |
|
484 | exc_info=True) | |
|
297 | 485 | self.abort() |
|
486 | raise | |
|
298 | 487 | elif action == 'exit': |
|
299 | self.exit() | |
|
300 | ||
|
488 | self.exit(0) |
@@ -1,117 +1,118 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | A context manager for managing things injected into :mod:`__builtin__`. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008-2009 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | import __builtin__ |
|
23 | 23 | |
|
24 | 24 | from IPython.core.component import Component |
|
25 | 25 | from IPython.core.quitter import Quitter |
|
26 | 26 | |
|
27 | 27 | from IPython.utils.autoattr import auto_attr |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Classes and functions |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | |
|
34 | class BuiltinUndefined(object): pass | |
|
35 | BuiltinUndefined = BuiltinUndefined() | |
|
34 | class __BuiltinUndefined(object): pass | |
|
35 | BuiltinUndefined = __BuiltinUndefined() | |
|
36 | 36 | |
|
37 | 37 | |
|
38 | 38 | class BuiltinTrap(Component): |
|
39 | 39 | |
|
40 | 40 | def __init__(self, parent): |
|
41 | 41 | super(BuiltinTrap, self).__init__(parent, None, None) |
|
42 | 42 | self._orig_builtins = {} |
|
43 | 43 | # We define this to track if a single BuiltinTrap is nested. |
|
44 | 44 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
45 | 45 | self._nested_level = 0 |
|
46 | 46 | |
|
47 | 47 | @auto_attr |
|
48 | 48 | def shell(self): |
|
49 | 49 | return Component.get_instances( |
|
50 | 50 | root=self.root, |
|
51 | 51 | klass='IPython.core.iplib.InteractiveShell')[0] |
|
52 | 52 | |
|
53 | 53 | def __enter__(self): |
|
54 | 54 | if self._nested_level == 0: |
|
55 | 55 | self.set() |
|
56 | 56 | self._nested_level += 1 |
|
57 | 57 | # I return self, so callers can use add_builtin in a with clause. |
|
58 | 58 | return self |
|
59 | 59 | |
|
60 | 60 | def __exit__(self, type, value, traceback): |
|
61 | 61 | if self._nested_level == 1: |
|
62 | 62 | self.unset() |
|
63 | 63 | self._nested_level -= 1 |
|
64 | 64 | # Returning False will cause exceptions to propagate |
|
65 | 65 | return False |
|
66 | 66 | |
|
67 | 67 | def add_builtin(self, key, value): |
|
68 | 68 | """Add a builtin and save the original.""" |
|
69 | 69 | orig = __builtin__.__dict__.get(key, BuiltinUndefined) |
|
70 | 70 | self._orig_builtins[key] = orig |
|
71 | 71 | __builtin__.__dict__[key] = value |
|
72 | 72 | |
|
73 | 73 | def remove_builtin(self, key): |
|
74 | 74 | """Remove an added builtin and re-set the original.""" |
|
75 | 75 | try: |
|
76 | 76 | orig = self._orig_builtins.pop(key) |
|
77 | 77 | except KeyError: |
|
78 | 78 | pass |
|
79 | 79 | else: |
|
80 | 80 | if orig is BuiltinUndefined: |
|
81 | 81 | del __builtin__.__dict__[key] |
|
82 | 82 | else: |
|
83 | 83 | __builtin__.__dict__[key] = orig |
|
84 | 84 | |
|
85 | 85 | def set(self): |
|
86 | 86 | """Store ipython references in the __builtin__ namespace.""" |
|
87 | 87 | self.add_builtin('exit', Quitter(self.shell, 'exit')) |
|
88 | 88 | self.add_builtin('quit', Quitter(self.shell, 'quit')) |
|
89 | self.add_builtin('get_ipython', self.shell.get_ipython) | |
|
89 | 90 | |
|
90 | 91 | # Recursive reload function |
|
91 | 92 | try: |
|
92 | 93 | from IPython.lib import deepreload |
|
93 | 94 | if self.shell.deep_reload: |
|
94 | 95 | self.add_builtin('reload', deepreload.reload) |
|
95 | 96 | else: |
|
96 | 97 | self.add_builtin('dreload', deepreload.reload) |
|
97 | 98 | del deepreload |
|
98 | 99 | except ImportError: |
|
99 | 100 | pass |
|
100 | 101 | |
|
101 | 102 | # Keep in the builtins a flag for when IPython is active. We set it |
|
102 | 103 | # with setdefault so that multiple nested IPythons don't clobber one |
|
103 | 104 | # another. Each will increase its value by one upon being activated, |
|
104 | 105 | # which also gives us a way to determine the nesting level. |
|
105 | 106 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
106 | 107 | |
|
107 | 108 | def unset(self): |
|
108 | 109 | """Remove any builtins which might have been added by add_builtins, or |
|
109 | 110 | restore overwritten ones to their previous values.""" |
|
110 | 111 | for key in self._orig_builtins.keys(): |
|
111 | 112 | self.remove_builtin(key) |
|
112 | 113 | self._orig_builtins.clear() |
|
113 | 114 | self._builtins_added = False |
|
114 | 115 | try: |
|
115 | 116 | del __builtin__.__dict__['__IPYTHON__active'] |
|
116 | 117 | except KeyError: |
|
117 | 118 | pass |
@@ -1,642 +1,658 b'' | |||
|
1 | 1 | """Word completion for IPython. |
|
2 | 2 | |
|
3 | 3 | This module is a fork of the rlcompleter module in the Python standard |
|
4 | 4 | library. The original enhancements made to rlcompleter have been sent |
|
5 | 5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
6 | 6 | functionality specific to IPython, so this module will continue to live as an |
|
7 | 7 | IPython-specific utility. |
|
8 | 8 | |
|
9 | 9 | Original rlcompleter documentation: |
|
10 | 10 | |
|
11 | 11 | This requires the latest extension to the readline module (the |
|
12 | 12 | completes keywords, built-ins and globals in __main__; when completing |
|
13 | 13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
14 | 14 | completes its attributes. |
|
15 | 15 | |
|
16 | 16 | It's very cool to do "import string" type "string.", hit the |
|
17 | 17 | completion key (twice), and see the list of names defined by the |
|
18 | 18 | string module! |
|
19 | 19 | |
|
20 | 20 | Tip: to use the tab key as the completion key, call |
|
21 | 21 | |
|
22 | 22 | readline.parse_and_bind("tab: complete") |
|
23 | 23 | |
|
24 | 24 | Notes: |
|
25 | 25 | |
|
26 | 26 | - Exceptions raised by the completer function are *ignored* (and |
|
27 | 27 | generally cause the completion to fail). This is a feature -- since |
|
28 | 28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
29 | 29 | traceback wouldn't work well without some complicated hoopla to save, |
|
30 | 30 | reset and restore the tty state. |
|
31 | 31 | |
|
32 | 32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
33 | 33 | application defined code to be executed if an object with a |
|
34 | 34 | __getattr__ hook is found. Since it is the responsibility of the |
|
35 | 35 | application (or the user) to enable this feature, I consider this an |
|
36 | 36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
37 | 37 | indexing operations) are *not* evaluated. |
|
38 | 38 | |
|
39 | 39 | - GNU readline is also used by the built-in functions input() and |
|
40 | 40 | raw_input(), and thus these also benefit/suffer from the completer |
|
41 | 41 | features. Clearly an interactive application can benefit by |
|
42 | 42 | specifying its own completer function and using raw_input() for all |
|
43 | 43 | its input. |
|
44 | 44 | |
|
45 | 45 | - When the original stdin is not a tty device, GNU readline is never |
|
46 | 46 | used, and this module (and the readline module) are silently inactive. |
|
47 | ||
|
48 | 47 | """ |
|
49 | 48 | |
|
50 | 49 | #***************************************************************************** |
|
51 | 50 | # |
|
52 | 51 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
53 | 52 | # module which is part of the standard Python distribution, I assume that the |
|
54 | 53 | # proper procedure is to maintain its copyright as belonging to the Python |
|
55 | 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 | 58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
|
59 | 59 | # |
|
60 | 60 | # Distributed under the terms of the BSD License. The full license is in |
|
61 | 61 | # the file COPYING, distributed as part of this software. |
|
62 | 62 | # |
|
63 | 63 | #***************************************************************************** |
|
64 | 64 | |
|
65 | #----------------------------------------------------------------------------- | |
|
66 | # Imports | |
|
67 | #----------------------------------------------------------------------------- | |
|
68 | ||
|
65 | 69 | import __builtin__ |
|
66 | 70 | import __main__ |
|
67 | 71 | import glob |
|
68 | 72 | import itertools |
|
69 | 73 | import keyword |
|
70 | 74 | import os |
|
71 | 75 | import re |
|
72 | 76 | import shlex |
|
73 | 77 | import sys |
|
74 | 78 | import types |
|
75 | 79 | |
|
80 | import IPython.utils.rlineimpl as readline | |
|
76 | 81 | from IPython.core.error import TryNext |
|
77 | 82 | from IPython.core.prefilter import ESC_MAGIC |
|
78 | ||
|
79 | import IPython.utils.rlineimpl as readline | |
|
80 | from IPython.utils.ipstruct import Struct | |
|
81 | 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 | 84 | from IPython.utils.genutils import debugx, dir2 |
|
90 | 85 | |
|
86 | #----------------------------------------------------------------------------- | |
|
87 | # Globals | |
|
88 | #----------------------------------------------------------------------------- | |
|
89 | ||
|
90 | # Public API | |
|
91 | 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 | 131 | class Completer: |
|
94 | 132 | def __init__(self,namespace=None,global_namespace=None): |
|
95 | 133 | """Create a new completer for the command line. |
|
96 | 134 | |
|
97 | 135 | Completer([namespace,global_namespace]) -> completer instance. |
|
98 | 136 | |
|
99 | 137 | If unspecified, the default namespace where completions are performed |
|
100 | 138 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
101 | 139 | given as dictionaries. |
|
102 | 140 | |
|
103 | 141 | An optional second namespace can be given. This allows the completer |
|
104 | 142 | to handle cases where both the local and global scopes need to be |
|
105 | 143 | distinguished. |
|
106 | 144 | |
|
107 | 145 | Completer instances should be used as the completion mechanism of |
|
108 | 146 | readline via the set_completer() call: |
|
109 | 147 | |
|
110 | 148 | readline.set_completer(Completer(my_namespace).complete) |
|
111 | 149 | """ |
|
112 | 150 | |
|
113 | 151 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
114 | 152 | # specific namespace or to use __main__.__dict__. This will allow us |
|
115 | 153 | # to bind to __main__.__dict__ at completion time, not now. |
|
116 | 154 | if namespace is None: |
|
117 | 155 | self.use_main_ns = 1 |
|
118 | 156 | else: |
|
119 | 157 | self.use_main_ns = 0 |
|
120 | 158 | self.namespace = namespace |
|
121 | 159 | |
|
122 | 160 | # The global namespace, if given, can be bound directly |
|
123 | 161 | if global_namespace is None: |
|
124 | 162 | self.global_namespace = {} |
|
125 | 163 | else: |
|
126 | 164 | self.global_namespace = global_namespace |
|
127 | 165 | |
|
128 | 166 | def complete(self, text, state): |
|
129 | 167 | """Return the next possible completion for 'text'. |
|
130 | 168 | |
|
131 | 169 | This is called successively with state == 0, 1, 2, ... until it |
|
132 | 170 | returns None. The completion should begin with 'text'. |
|
133 | 171 | |
|
134 | 172 | """ |
|
135 | 173 | if self.use_main_ns: |
|
136 | 174 | self.namespace = __main__.__dict__ |
|
137 | 175 | |
|
138 | 176 | if state == 0: |
|
139 | 177 | if "." in text: |
|
140 | 178 | self.matches = self.attr_matches(text) |
|
141 | 179 | else: |
|
142 | 180 | self.matches = self.global_matches(text) |
|
143 | 181 | try: |
|
144 | 182 | return self.matches[state] |
|
145 | 183 | except IndexError: |
|
146 | 184 | return None |
|
147 | 185 | |
|
148 | 186 | def global_matches(self, text): |
|
149 | 187 | """Compute matches when text is a simple name. |
|
150 | 188 | |
|
151 | 189 | Return a list of all keywords, built-in functions and names currently |
|
152 | 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 | 194 | matches = [] |
|
156 | 195 | match_append = matches.append |
|
157 | 196 | n = len(text) |
|
158 | 197 | for lst in [keyword.kwlist, |
|
159 | 198 | __builtin__.__dict__.keys(), |
|
160 | 199 | self.namespace.keys(), |
|
161 | 200 | self.global_namespace.keys()]: |
|
162 | 201 | for word in lst: |
|
163 | 202 | if word[:n] == text and word != "__builtins__": |
|
164 | 203 | match_append(word) |
|
165 | 204 | return matches |
|
166 | 205 | |
|
167 | 206 | def attr_matches(self, text): |
|
168 | 207 | """Compute matches when text contains a dot. |
|
169 | 208 | |
|
170 | 209 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
171 | 210 | evaluatable in self.namespace or self.global_namespace, it will be |
|
172 | 211 | evaluated and its attributes (as revealed by dir()) are used as |
|
173 | 212 | possible completions. (For class instances, class members are are |
|
174 | 213 | also considered.) |
|
175 | 214 | |
|
176 | 215 | WARNING: this can still invoke arbitrary C code, if an object |
|
177 | 216 | with a __getattr__ hook is evaluated. |
|
178 | 217 | |
|
179 | 218 | """ |
|
180 | 219 | import re |
|
181 | 220 | |
|
221 | #print 'Completer->attr_matches, txt=%r' % text # dbg | |
|
182 | 222 | # Another option, seems to work great. Catches things like ''.<tab> |
|
183 | 223 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
184 | 224 | |
|
185 | 225 | if not m: |
|
186 | 226 | return [] |
|
187 | 227 | |
|
188 | 228 | expr, attr = m.group(1, 3) |
|
189 | 229 | try: |
|
190 | 230 | obj = eval(expr, self.namespace) |
|
191 | 231 | except: |
|
192 | 232 | try: |
|
193 | 233 | obj = eval(expr, self.global_namespace) |
|
194 | 234 | except: |
|
195 | 235 | return [] |
|
196 | 236 | |
|
197 | 237 | words = dir2(obj) |
|
198 | 238 | |
|
199 | 239 | try: |
|
200 | 240 | words = generics.complete_object(obj, words) |
|
201 | 241 | except TryNext: |
|
202 | 242 | pass |
|
203 | 243 | # Build match list to return |
|
204 | 244 | n = len(attr) |
|
205 | 245 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
206 | 246 | return res |
|
207 | 247 | |
|
248 | ||
|
208 | 249 | class IPCompleter(Completer): |
|
209 | 250 | """Extension of the completer class with IPython-specific features""" |
|
210 | 251 | |
|
211 | 252 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
212 | 253 | omit__names=0,alias_table=None): |
|
213 | 254 | """IPCompleter() -> completer |
|
214 | 255 | |
|
215 | 256 | Return a completer object suitable for use by the readline library |
|
216 | 257 | via readline.set_completer(). |
|
217 | 258 | |
|
218 | 259 | Inputs: |
|
219 | 260 | |
|
220 | 261 | - shell: a pointer to the ipython shell itself. This is needed |
|
221 | 262 | because this completer knows about magic functions, and those can |
|
222 | 263 | only be accessed via the ipython instance. |
|
223 | 264 | |
|
224 | 265 | - namespace: an optional dict where completions are performed. |
|
225 | 266 | |
|
226 | 267 | - global_namespace: secondary optional dict for completions, to |
|
227 | 268 | handle cases (such as IPython embedded inside functions) where |
|
228 | 269 | both Python scopes are visible. |
|
229 | 270 | |
|
230 | 271 | - The optional omit__names parameter sets the completer to omit the |
|
231 | 272 | 'magic' names (__magicname__) for python objects unless the text |
|
232 | 273 | to be completed explicitly starts with one or more underscores. |
|
233 | 274 | |
|
234 | 275 | - If alias_table is supplied, it should be a dictionary of aliases |
|
235 | 276 | to complete. """ |
|
236 | 277 | |
|
237 | 278 | Completer.__init__(self,namespace,global_namespace) |
|
238 | self.magic_prefix = shell.name+'.magic_' | |
|
279 | ||
|
239 | 280 | self.magic_escape = ESC_MAGIC |
|
240 | 281 | self.readline = readline |
|
241 | 282 | delims = self.readline.get_completer_delims() |
|
242 | 283 | delims = delims.replace(self.magic_escape,'') |
|
243 | 284 | self.readline.set_completer_delims(delims) |
|
244 | 285 | self.get_line_buffer = self.readline.get_line_buffer |
|
245 | 286 | self.get_endidx = self.readline.get_endidx |
|
246 | 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 | 290 | if alias_table is None: |
|
249 | 291 | alias_table = {} |
|
250 | 292 | self.alias_table = alias_table |
|
251 | 293 | # Regexp to split filenames with spaces in them |
|
252 | 294 | self.space_name_re = re.compile(r'([^\\] )') |
|
253 | 295 | # Hold a local ref. to glob.glob for speed |
|
254 | 296 | self.glob = glob.glob |
|
255 | 297 | |
|
256 | 298 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
257 | 299 | # buffers, to avoid completion problems. |
|
258 | 300 | term = os.environ.get('TERM','xterm') |
|
259 | 301 | self.dumb_terminal = term in ['dumb','emacs'] |
|
260 | 302 | |
|
261 | 303 | # Special handling of backslashes needed in win32 platforms |
|
262 | 304 | if sys.platform == "win32": |
|
263 | 305 | self.clean_glob = self._clean_glob_win32 |
|
264 | 306 | else: |
|
265 | 307 | self.clean_glob = self._clean_glob |
|
308 | ||
|
309 | # All active matcher routines for completion | |
|
266 | 310 | self.matchers = [self.python_matches, |
|
267 | 311 | self.file_matches, |
|
312 | self.magic_matches, | |
|
268 | 313 | self.alias_matches, |
|
269 | 314 | self.python_func_kw_matches] |
|
270 | ||
|
271 | 315 | |
|
272 | 316 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
273 | 317 | def all_completions(self, text): |
|
274 | 318 | """Return all possible completions for the benefit of emacs.""" |
|
275 | 319 | |
|
276 | 320 | completions = [] |
|
277 | 321 | comp_append = completions.append |
|
278 | 322 | try: |
|
279 | 323 | for i in xrange(sys.maxint): |
|
280 | 324 | res = self.complete(text, i) |
|
281 | ||
|
282 |
|
|
|
283 | ||
|
325 | if not res: | |
|
326 | break | |
|
284 | 327 | comp_append(res) |
|
285 | 328 | #XXX workaround for ``notDefined.<tab>`` |
|
286 | 329 | except NameError: |
|
287 | 330 | pass |
|
288 | 331 | return completions |
|
289 | 332 | # /end Alex Schmolck code. |
|
290 | 333 | |
|
291 | 334 | def _clean_glob(self,text): |
|
292 | 335 | return self.glob("%s*" % text) |
|
293 | 336 | |
|
294 | 337 | def _clean_glob_win32(self,text): |
|
295 | 338 | return [f.replace("\\","/") |
|
296 | 339 | for f in self.glob("%s*" % text)] |
|
297 | 340 | |
|
298 | 341 | def file_matches(self, text): |
|
299 | 342 | """Match filenames, expanding ~USER type strings. |
|
300 | 343 | |
|
301 | 344 | Most of the seemingly convoluted logic in this completer is an |
|
302 | 345 | attempt to handle filenames with spaces in them. And yet it's not |
|
303 | 346 | quite perfect, because Python's readline doesn't expose all of the |
|
304 | 347 | GNU readline details needed for this to be done correctly. |
|
305 | 348 | |
|
306 | 349 | For a filename with a space in it, the printed completions will be |
|
307 | 350 | only the parts after what's already been typed (instead of the |
|
308 | 351 | full completions, as is normally done). I don't think with the |
|
309 | 352 | current (as of Python 2.3) Python readline it's possible to do |
|
310 | 353 | better.""" |
|
311 | 354 | |
|
312 | 355 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
313 | 356 | |
|
314 | 357 | # chars that require escaping with backslash - i.e. chars |
|
315 | 358 | # that readline treats incorrectly as delimiters, but we |
|
316 | 359 | # don't want to treat as delimiters in filename matching |
|
317 | 360 | # when escaped with backslash |
|
318 | 361 | |
|
319 | if sys.platform == 'win32': | |
|
320 | protectables = ' ' | |
|
321 | else: | |
|
322 | protectables = ' ()' | |
|
323 | ||
|
324 | 362 | if text.startswith('!'): |
|
325 | 363 | text = text[1:] |
|
326 | 364 | text_prefix = '!' |
|
327 | 365 | else: |
|
328 | 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 | 368 | lbuf = self.lbuf |
|
355 | 369 | open_quotes = 0 # track strings with open quotes |
|
356 | 370 | try: |
|
357 | 371 | lsplit = shlex.split(lbuf)[-1] |
|
358 | 372 | except ValueError: |
|
359 | 373 | # typically an unmatched ", or backslash without escaped char. |
|
360 | 374 | if lbuf.count('"')==1: |
|
361 | 375 | open_quotes = 1 |
|
362 | 376 | lsplit = lbuf.split('"')[-1] |
|
363 | 377 | elif lbuf.count("'")==1: |
|
364 | 378 | open_quotes = 1 |
|
365 | 379 | lsplit = lbuf.split("'")[-1] |
|
366 | 380 | else: |
|
367 | 381 | return [] |
|
368 | 382 | except IndexError: |
|
369 | 383 | # tab pressed on empty line |
|
370 | 384 | lsplit = "" |
|
371 | 385 | |
|
372 | 386 | if lsplit != protect_filename(lsplit): |
|
373 | 387 | # if protectables are found, do matching on the whole escaped |
|
374 | 388 | # name |
|
375 | 389 | has_protectables = 1 |
|
376 | 390 | text0,text = text,lsplit |
|
377 | 391 | else: |
|
378 | 392 | has_protectables = 0 |
|
379 | 393 | text = os.path.expanduser(text) |
|
380 | 394 | |
|
381 | 395 | if text == "": |
|
382 | 396 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
383 | 397 | |
|
384 | 398 | m0 = self.clean_glob(text.replace('\\','')) |
|
385 | 399 | if has_protectables: |
|
386 | 400 | # If we had protectables, we need to revert our changes to the |
|
387 | 401 | # beginning of filename so that we don't double-write the part |
|
388 | 402 | # of the filename we have so far |
|
389 | 403 | len_lsplit = len(lsplit) |
|
390 | 404 | matches = [text_prefix + text0 + |
|
391 | 405 | protect_filename(f[len_lsplit:]) for f in m0] |
|
392 | 406 | else: |
|
393 | 407 | if open_quotes: |
|
394 | 408 | # if we have a string with an open quote, we don't need to |
|
395 | 409 | # protect the names at all (and we _shouldn't_, as it |
|
396 | 410 | # would cause bugs when the filesystem call is made). |
|
397 | 411 | matches = m0 |
|
398 | 412 | else: |
|
399 | 413 | matches = [text_prefix + |
|
400 | 414 | protect_filename(f) for f in m0] |
|
401 | 415 | |
|
402 | 416 | #print 'mm',matches # dbg |
|
403 | 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 | 429 | def alias_matches(self, text): |
|
406 | 430 | """Match internal system aliases""" |
|
407 | 431 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
408 | 432 | |
|
409 | 433 | # if we are not in the first 'item', alias matching |
|
410 | 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 | 437 | return [] |
|
413 | 438 | text = os.path.expanduser(text) |
|
414 | 439 | aliases = self.alias_table.keys() |
|
415 | 440 | if text == "": |
|
416 | 441 | return aliases |
|
417 | 442 | else: |
|
418 | 443 | return [alias for alias in aliases if alias.startswith(text)] |
|
419 | 444 | |
|
420 | 445 | def python_matches(self,text): |
|
421 | 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 | 449 | if "." in text: |
|
425 | 450 | try: |
|
426 | 451 | matches = self.attr_matches(text) |
|
427 | 452 | if text.endswith('.') and self.omit__names: |
|
428 | 453 | if self.omit__names == 1: |
|
429 | 454 | # true if txt is _not_ a __ name, false otherwise: |
|
430 | 455 | no__name = (lambda txt: |
|
431 | 456 | re.match(r'.*\.__.*?__',txt) is None) |
|
432 | 457 | else: |
|
433 | 458 | # true if txt is _not_ a _ name, false otherwise: |
|
434 | 459 | no__name = (lambda txt: |
|
435 | 460 | re.match(r'.*\._.*?',txt) is None) |
|
436 | 461 | matches = filter(no__name, matches) |
|
437 | 462 | except NameError: |
|
438 | 463 | # catches <undefined attributes>.<tab> |
|
439 | 464 | matches = [] |
|
440 | 465 | else: |
|
441 | 466 | matches = self.global_matches(text) |
|
442 | # this is so completion finds magics when automagic is on: | |
|
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) | |
|
467 | ||
|
447 | 468 | return matches |
|
448 | 469 | |
|
449 | 470 | def _default_arguments(self, obj): |
|
450 | 471 | """Return the list of default arguments of obj if it is callable, |
|
451 | 472 | or empty list otherwise.""" |
|
452 | 473 | |
|
453 | 474 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
454 | 475 | # for classes, check for __init__,__new__ |
|
455 | 476 | if inspect.isclass(obj): |
|
456 | 477 | obj = (getattr(obj,'__init__',None) or |
|
457 | 478 | getattr(obj,'__new__',None)) |
|
458 | 479 | # for all others, check if they are __call__able |
|
459 | 480 | elif hasattr(obj, '__call__'): |
|
460 | 481 | obj = obj.__call__ |
|
461 | 482 | # XXX: is there a way to handle the builtins ? |
|
462 | 483 | try: |
|
463 | 484 | args,_,_1,defaults = inspect.getargspec(obj) |
|
464 | 485 | if defaults: |
|
465 | 486 | return args[-len(defaults):] |
|
466 | 487 | except TypeError: pass |
|
467 | 488 | return [] |
|
468 | 489 | |
|
469 | 490 | def python_func_kw_matches(self,text): |
|
470 | 491 | """Match named parameters (kwargs) of the last open function""" |
|
471 | 492 | |
|
472 | 493 | if "." in text: # a parameter cannot be dotted |
|
473 | 494 | return [] |
|
474 | 495 | try: regexp = self.__funcParamsRegex |
|
475 | 496 | except AttributeError: |
|
476 | 497 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
477 | 498 | '.*?' | # single quoted strings or |
|
478 | 499 | ".*?" | # double quoted strings or |
|
479 | 500 | \w+ | # identifier |
|
480 | 501 | \S # other characters |
|
481 | 502 | ''', re.VERBOSE | re.DOTALL) |
|
482 | 503 | # 1. find the nearest identifier that comes before an unclosed |
|
483 | 504 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
484 | 505 | tokens = regexp.findall(self.get_line_buffer()) |
|
485 | 506 | tokens.reverse() |
|
486 | 507 | iterTokens = iter(tokens); openPar = 0 |
|
487 | 508 | for token in iterTokens: |
|
488 | 509 | if token == ')': |
|
489 | 510 | openPar -= 1 |
|
490 | 511 | elif token == '(': |
|
491 | 512 | openPar += 1 |
|
492 | 513 | if openPar > 0: |
|
493 | 514 | # found the last unclosed parenthesis |
|
494 | 515 | break |
|
495 | 516 | else: |
|
496 | 517 | return [] |
|
497 | 518 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
498 | 519 | ids = [] |
|
499 | 520 | isId = re.compile(r'\w+$').match |
|
500 | 521 | while True: |
|
501 | 522 | try: |
|
502 | 523 | ids.append(iterTokens.next()) |
|
503 | 524 | if not isId(ids[-1]): |
|
504 | 525 | ids.pop(); break |
|
505 | 526 | if not iterTokens.next() == '.': |
|
506 | 527 | break |
|
507 | 528 | except StopIteration: |
|
508 | 529 | break |
|
509 | 530 | # lookup the candidate callable matches either using global_matches |
|
510 | 531 | # or attr_matches for dotted names |
|
511 | 532 | if len(ids) == 1: |
|
512 | 533 | callableMatches = self.global_matches(ids[0]) |
|
513 | 534 | else: |
|
514 | 535 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
515 | 536 | argMatches = [] |
|
516 | 537 | for callableMatch in callableMatches: |
|
517 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
|
538 | try: | |
|
539 | namedArgs = self._default_arguments(eval(callableMatch, | |
|
518 | 540 | self.namespace)) |
|
519 |
except: |
|
|
541 | except: | |
|
542 | continue | |
|
520 | 543 | for namedArg in namedArgs: |
|
521 | 544 | if namedArg.startswith(text): |
|
522 | 545 | argMatches.append("%s=" %namedArg) |
|
523 | 546 | return argMatches |
|
524 | 547 | |
|
525 | 548 | def dispatch_custom_completer(self,text): |
|
526 | 549 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
527 | 550 | line = self.full_lbuf |
|
528 | 551 | if not line.strip(): |
|
529 | 552 | return None |
|
530 | 553 | |
|
531 |
event = |
|
|
554 | event = Bunch() | |
|
532 | 555 | event.line = line |
|
533 | 556 | event.symbol = text |
|
534 | 557 | cmd = line.split(None,1)[0] |
|
535 | 558 | event.command = cmd |
|
536 | 559 | #print "\ncustom:{%s]\n" % event # dbg |
|
537 | 560 | |
|
538 | 561 | # for foo etc, try also to find completer for %foo |
|
539 | 562 | if not cmd.startswith(self.magic_escape): |
|
540 | 563 | try_magic = self.custom_completers.s_matches( |
|
541 | 564 | self.magic_escape + cmd) |
|
542 | 565 | else: |
|
543 | try_magic = [] | |
|
544 | ||
|
566 | try_magic = [] | |
|
545 | 567 | |
|
546 | for c in itertools.chain( | |
|
547 | self.custom_completers.s_matches(cmd), | |
|
568 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
|
548 | 569 | try_magic, |
|
549 | 570 | self.custom_completers.flat_matches(self.lbuf)): |
|
550 | 571 | #print "try",c # dbg |
|
551 | 572 | try: |
|
552 | 573 | res = c(event) |
|
553 | 574 | # first, try case sensitive match |
|
554 | 575 | withcase = [r for r in res if r.startswith(text)] |
|
555 | 576 | if withcase: |
|
556 | 577 | return withcase |
|
557 | 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 | 581 | except TryNext: |
|
560 | 582 | pass |
|
561 | 583 | |
|
562 | 584 | return None |
|
563 | 585 | |
|
564 | 586 | def complete(self, text, state,line_buffer=None): |
|
565 | 587 | """Return the next possible completion for 'text'. |
|
566 | 588 | |
|
567 | 589 | This is called successively with state == 0, 1, 2, ... until it |
|
568 | 590 | returns None. The completion should begin with 'text'. |
|
569 | 591 | |
|
570 | 592 | :Keywords: |
|
571 | 593 | - line_buffer: string |
|
572 | 594 | If not given, the completer attempts to obtain the current line buffer |
|
573 | 595 | via readline. This keyword allows clients which are requesting for |
|
574 | 596 | text completions in non-readline contexts to inform the completer of |
|
575 | 597 | the entire text. |
|
576 | 598 | """ |
|
577 | 599 | |
|
578 | 600 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
579 | 601 | |
|
580 | 602 | # if there is only a tab on a line with only whitespace, instead |
|
581 | 603 | # of the mostly useless 'do you want to see all million |
|
582 | 604 | # completions' message, just do the right thing and give the user |
|
583 | 605 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
584 | 606 | # an editor (as long as autoindent is off). |
|
585 | 607 | |
|
586 | 608 | # It should be noted that at least pyreadline still shows |
|
587 | 609 | # file completions - is there a way around it? |
|
588 | 610 | |
|
589 | 611 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
590 | 612 | # don't interfere with their own tab-completion mechanism. |
|
591 | 613 | if line_buffer is None: |
|
592 | 614 | self.full_lbuf = self.get_line_buffer() |
|
593 | 615 | else: |
|
594 | 616 | self.full_lbuf = line_buffer |
|
595 | 617 | |
|
596 | 618 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
597 | 619 | self.readline.insert_text('\t') |
|
598 | 620 | return None |
|
599 | 621 | |
|
600 | 622 | magic_escape = self.magic_escape |
|
601 | magic_prefix = self.magic_prefix | |
|
602 | 623 | |
|
603 | 624 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
604 | 625 | |
|
605 | 626 | try: |
|
606 |
if text.startswith( |
|
|
607 | text = text.replace(magic_escape,magic_prefix) | |
|
608 | elif text.startswith('~'): | |
|
627 | if text.startswith('~'): | |
|
609 | 628 | text = os.path.expanduser(text) |
|
610 | 629 | if state == 0: |
|
611 | 630 | custom_res = self.dispatch_custom_completer(text) |
|
612 | 631 | if custom_res is not None: |
|
613 | 632 | # did custom completers produce something? |
|
614 | 633 | self.matches = custom_res |
|
615 | 634 | else: |
|
616 | 635 | # Extend the list of completions with the results of each |
|
617 | 636 | # matcher, so we return results to the user from all |
|
618 | 637 | # namespaces. |
|
619 | 638 | if self.merge_completions: |
|
620 | 639 | self.matches = [] |
|
621 | 640 | for matcher in self.matchers: |
|
622 | 641 | self.matches.extend(matcher(text)) |
|
623 | 642 | else: |
|
624 | 643 | for matcher in self.matchers: |
|
625 | 644 | self.matches = matcher(text) |
|
626 | 645 | if self.matches: |
|
627 | 646 | break |
|
628 | def uniq(alist): | |
|
629 | set = {} | |
|
630 | return [set.setdefault(e,e) for e in alist if e not in set] | |
|
631 | self.matches = uniq(self.matches) | |
|
647 | self.matches = list(set(self.matches)) | |
|
632 | 648 | try: |
|
633 | ret = self.matches[state].replace(magic_prefix,magic_escape) | |
|
634 |
return |
|
|
649 | #print "MATCH: %r" % self.matches[state] # dbg | |
|
650 | return self.matches[state] | |
|
635 | 651 | except IndexError: |
|
636 | 652 | return None |
|
637 | 653 | except: |
|
638 | 654 | #from IPython.core.ultratb import AutoFormattedTB; # dbg |
|
639 | 655 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
640 | 656 | |
|
641 | 657 | # If completion fails, don't annoy the user. |
|
642 | 658 | return None |
@@ -1,325 +1,346 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | A lightweight component system for IPython. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | from copy import deepcopy |
|
24 | 24 | import datetime |
|
25 | 25 | from weakref import WeakValueDictionary |
|
26 | 26 | |
|
27 | 27 | from IPython.utils.importstring import import_item |
|
28 | 28 | from IPython.config.loader import Config |
|
29 | 29 | from IPython.utils.traitlets import ( |
|
30 | 30 | HasTraits, TraitError, MetaHasTraits, Instance, This |
|
31 | 31 | ) |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Helper classes for Components |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | class ComponentError(Exception): |
|
40 | 40 | pass |
|
41 | 41 | |
|
42 | 42 | class MetaComponentTracker(type): |
|
43 | 43 | """A metaclass that tracks instances of Components and its subclasses.""" |
|
44 | 44 | |
|
45 | 45 | def __init__(cls, name, bases, d): |
|
46 | 46 | super(MetaComponentTracker, cls).__init__(name, bases, d) |
|
47 | 47 | cls.__instance_refs = WeakValueDictionary() |
|
48 | 48 | cls.__numcreated = 0 |
|
49 | 49 | |
|
50 | 50 | def __call__(cls, *args, **kw): |
|
51 | 51 | """Called when a class is called (instantiated)!!! |
|
52 | 52 | |
|
53 | 53 | When a Component or subclass is instantiated, this is called and |
|
54 | 54 | the instance is saved in a WeakValueDictionary for tracking. |
|
55 | 55 | """ |
|
56 | 56 | instance = cls.__new__(cls, *args, **kw) |
|
57 | 57 | |
|
58 | 58 | # Register the instance before __init__ is called so get_instances |
|
59 | 59 | # works inside __init__ methods! |
|
60 | 60 | indices = cls.register_instance(instance) |
|
61 | 61 | |
|
62 | 62 | # This is in a try/except because of the __init__ method fails, the |
|
63 | 63 | # instance is discarded and shouldn't be tracked. |
|
64 | 64 | try: |
|
65 | 65 | if isinstance(instance, cls): |
|
66 | 66 | cls.__init__(instance, *args, **kw) |
|
67 | 67 | except: |
|
68 | 68 | # Unregister the instance because __init__ failed! |
|
69 | 69 | cls.unregister_instances(indices) |
|
70 | 70 | raise |
|
71 | 71 | else: |
|
72 | 72 | return instance |
|
73 | 73 | |
|
74 | 74 | def register_instance(cls, instance): |
|
75 | 75 | """Register instance with cls and its subclasses.""" |
|
76 | 76 | # indices is a list of the keys used to register the instance |
|
77 | 77 | # with. This list is needed if the instance needs to be unregistered. |
|
78 | 78 | indices = [] |
|
79 | 79 | for c in cls.__mro__: |
|
80 | 80 | if issubclass(cls, c) and issubclass(c, Component): |
|
81 | 81 | c.__numcreated += 1 |
|
82 | 82 | indices.append(c.__numcreated) |
|
83 | 83 | c.__instance_refs[c.__numcreated] = instance |
|
84 | 84 | else: |
|
85 | 85 | break |
|
86 | 86 | return indices |
|
87 | 87 | |
|
88 | 88 | def unregister_instances(cls, indices): |
|
89 | 89 | """Unregister instance with cls and its subclasses.""" |
|
90 | 90 | for c, index in zip(cls.__mro__, indices): |
|
91 | 91 | try: |
|
92 | 92 | del c.__instance_refs[index] |
|
93 | 93 | except KeyError: |
|
94 | 94 | pass |
|
95 | 95 | |
|
96 | 96 | def clear_instances(cls): |
|
97 | 97 | """Clear all instances tracked by cls.""" |
|
98 | 98 | cls.__instance_refs.clear() |
|
99 | 99 | cls.__numcreated = 0 |
|
100 | 100 | |
|
101 | 101 | def get_instances(cls, name=None, root=None, klass=None): |
|
102 | 102 | """Get all instances of cls and its subclasses. |
|
103 | 103 | |
|
104 | 104 | Parameters |
|
105 | 105 | ---------- |
|
106 | 106 | name : str |
|
107 | 107 | Limit to components with this name. |
|
108 | 108 | root : Component or subclass |
|
109 | 109 | Limit to components having this root. |
|
110 | 110 | klass : class or str |
|
111 | 111 | Limits to instances of the class or its subclasses. If a str |
|
112 | 112 | is given ut must be in the form 'foo.bar.MyClass'. The str |
|
113 | 113 | form of this argument is useful for forward declarations. |
|
114 | 114 | """ |
|
115 | 115 | if klass is not None: |
|
116 | 116 | if isinstance(klass, basestring): |
|
117 | 117 | klass = import_item(klass) |
|
118 | 118 | # Limit search to instances of klass for performance |
|
119 | 119 | if issubclass(klass, Component): |
|
120 | 120 | return klass.get_instances(name=name, root=root) |
|
121 | 121 | instances = cls.__instance_refs.values() |
|
122 | 122 | if name is not None: |
|
123 | 123 | instances = [i for i in instances if i.name == name] |
|
124 | 124 | if klass is not None: |
|
125 | 125 | instances = [i for i in instances if isinstance(i, klass)] |
|
126 | 126 | if root is not None: |
|
127 | 127 | instances = [i for i in instances if i.root == root] |
|
128 | 128 | return instances |
|
129 | 129 | |
|
130 | 130 | def get_instances_by_condition(cls, call, name=None, root=None, |
|
131 | 131 | klass=None): |
|
132 | 132 | """Get all instances of cls, i such that call(i)==True. |
|
133 | 133 | |
|
134 | 134 | This also takes the ``name`` and ``root`` and ``classname`` |
|
135 | 135 | arguments of :meth:`get_instance` |
|
136 | 136 | """ |
|
137 | 137 | return [i for i in cls.get_instances(name, root, klass) if call(i)] |
|
138 | 138 | |
|
139 | 139 | |
|
140 | 140 | def masquerade_as(instance, cls): |
|
141 | 141 | """Let instance masquerade as an instance of cls. |
|
142 | 142 | |
|
143 | 143 | Sometimes, such as in testing code, it is useful to let a class |
|
144 | 144 | masquerade as another. Python, being duck typed, allows this by |
|
145 | 145 | default. But, instances of components are tracked by their class type. |
|
146 | 146 | |
|
147 | 147 | After calling this, ``cls.get_instances()`` will return ``instance``. This |
|
148 | 148 | does not, however, cause ``isinstance(instance, cls)`` to return ``True``. |
|
149 | 149 | |
|
150 | 150 | Parameters |
|
151 | 151 | ---------- |
|
152 | 152 | instance : an instance of a Component or Component subclass |
|
153 | 153 | The instance that will pretend to be a cls. |
|
154 | 154 | cls : subclass of Component |
|
155 | 155 | The Component subclass that instance will pretend to be. |
|
156 | 156 | """ |
|
157 | 157 | cls.register_instance(instance) |
|
158 | 158 | |
|
159 | 159 | |
|
160 | class ComponentNameGenerator(object): | |
|
160 | class __ComponentNameGenerator(object): | |
|
161 | 161 | """A Singleton to generate unique component names.""" |
|
162 | 162 | |
|
163 | 163 | def __init__(self, prefix): |
|
164 | 164 | self.prefix = prefix |
|
165 | 165 | self.i = 0 |
|
166 | 166 | |
|
167 | 167 | def __call__(self): |
|
168 | 168 | count = self.i |
|
169 | 169 | self.i += 1 |
|
170 | 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 | 176 | class MetaComponent(MetaHasTraits, MetaComponentTracker): |
|
177 | 177 | pass |
|
178 | 178 | |
|
179 | 179 | |
|
180 | 180 | #----------------------------------------------------------------------------- |
|
181 | 181 | # Component implementation |
|
182 | 182 | #----------------------------------------------------------------------------- |
|
183 | 183 | |
|
184 | 184 | |
|
185 | 185 | class Component(HasTraits): |
|
186 | 186 | |
|
187 | 187 | __metaclass__ = MetaComponent |
|
188 | 188 | |
|
189 | 189 | # Traits are fun! |
|
190 | 190 | config = Instance(Config,(),{}) |
|
191 | 191 | parent = This() |
|
192 | 192 | root = This() |
|
193 | 193 | created = None |
|
194 | 194 | |
|
195 | 195 | def __init__(self, parent, name=None, config=None): |
|
196 | 196 | """Create a component given a parent and possibly and name and config. |
|
197 | 197 | |
|
198 | 198 | Parameters |
|
199 | 199 | ---------- |
|
200 | 200 | parent : Component subclass |
|
201 | 201 | The parent in the component graph. The parent is used |
|
202 | 202 | to get the root of the component graph. |
|
203 | 203 | name : str |
|
204 | 204 | The unique name of the component. If empty, then a unique |
|
205 | 205 | one will be autogenerated. |
|
206 | 206 | config : Config |
|
207 | 207 | If this is empty, self.config = parent.config, otherwise |
|
208 | 208 | self.config = config and root.config is ignored. This argument |
|
209 | 209 | should only be used to *override* the automatic inheritance of |
|
210 | 210 | parent.config. If a caller wants to modify parent.config |
|
211 | 211 | (not override), the caller should make a copy and change |
|
212 | 212 | attributes and then pass the copy to this argument. |
|
213 | 213 | |
|
214 | 214 | Notes |
|
215 | 215 | ----- |
|
216 | 216 | Subclasses of Component must call the :meth:`__init__` method of |
|
217 | 217 | :class:`Component` *before* doing anything else and using |
|
218 | 218 | :func:`super`:: |
|
219 | 219 | |
|
220 | 220 | class MyComponent(Component): |
|
221 | 221 | def __init__(self, parent, name=None, config=None): |
|
222 | 222 | super(MyComponent, self).__init__(parent, name, config) |
|
223 | 223 | # Then any other code you need to finish initialization. |
|
224 | 224 | |
|
225 | 225 | This ensures that the :attr:`parent`, :attr:`name` and :attr:`config` |
|
226 | 226 | attributes are handled properly. |
|
227 | 227 | """ |
|
228 | 228 | super(Component, self).__init__() |
|
229 | 229 | self._children = [] |
|
230 | 230 | if name is None: |
|
231 | 231 | self.name = ComponentNameGenerator() |
|
232 | 232 | else: |
|
233 | 233 | self.name = name |
|
234 | 234 | self.root = self # This is the default, it is set when parent is set |
|
235 | 235 | self.parent = parent |
|
236 | 236 | if config is not None: |
|
237 | 237 | self.config = config |
|
238 | 238 | # We used to deepcopy, but for now we are trying to just save |
|
239 | 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 | 244 | # self.config = deepcopy(config) |
|
242 | 245 | else: |
|
243 | 246 | if self.parent is not None: |
|
244 | 247 | self.config = self.parent.config |
|
245 | 248 | # We used to deepcopy, but for now we are trying to just save |
|
246 | 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 | 254 | # self.config = deepcopy(self.parent.config) |
|
249 | 255 | |
|
250 | 256 | self.created = datetime.datetime.now() |
|
251 | 257 | |
|
252 | 258 | #------------------------------------------------------------------------- |
|
253 | 259 | # Static trait notifiations |
|
254 | 260 | #------------------------------------------------------------------------- |
|
255 | 261 | |
|
256 | 262 | def _parent_changed(self, name, old, new): |
|
257 | 263 | if old is not None: |
|
258 | 264 | old._remove_child(self) |
|
259 | 265 | if new is not None: |
|
260 | 266 | new._add_child(self) |
|
261 | 267 | |
|
262 | 268 | if new is None: |
|
263 | 269 | self.root = self |
|
264 | 270 | else: |
|
265 | 271 | self.root = new.root |
|
266 | 272 | |
|
267 | 273 | def _root_changed(self, name, old, new): |
|
268 | 274 | if self.parent is None: |
|
269 | 275 | if not (new is self): |
|
270 | 276 | raise ComponentError("Root not self, but parent is None.") |
|
271 | 277 | else: |
|
272 | 278 | if not self.parent.root is new: |
|
273 | 279 | raise ComponentError("Error in setting the root attribute: " |
|
274 | 280 | "root != parent.root") |
|
275 | 281 | |
|
276 | 282 | def _config_changed(self, name, old, new): |
|
277 | 283 | """Update all the class traits having ``config=True`` as metadata. |
|
278 | 284 | |
|
279 | 285 | For any class trait with a ``config`` metadata attribute that is |
|
280 | 286 | ``True``, we update the trait with the value of the corresponding |
|
281 | 287 | config entry. |
|
282 | 288 | """ |
|
283 | 289 | # Get all traits with a config metadata entry that is True |
|
284 | 290 | traits = self.traits(config=True) |
|
285 | 291 | |
|
286 | 292 | # We auto-load config section for this class as well as any parent |
|
287 | 293 | # classes that are Component subclasses. This starts with Component |
|
288 | 294 | # and works down the mro loading the config for each section. |
|
289 | 295 | section_names = [cls.__name__ for cls in \ |
|
290 | 296 | reversed(self.__class__.__mro__) if |
|
291 | 297 | issubclass(cls, Component) and issubclass(self.__class__, cls)] |
|
292 | 298 | |
|
293 | 299 | for sname in section_names: |
|
294 | 300 | # Don't do a blind getattr as that would cause the config to |
|
295 | 301 | # dynamically create the section with name self.__class__.__name__. |
|
296 | 302 | if new._has_section(sname): |
|
297 | 303 | my_config = new[sname] |
|
298 | 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 | 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 | 318 | config_value = my_config[k] |
|
301 | 319 | except KeyError: |
|
302 | 320 | pass |
|
303 | 321 | else: |
|
304 | 322 | # print "Setting %s.%s from %s.%s=%r" % \ |
|
305 | 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 | 329 | @property |
|
309 | 330 | def children(self): |
|
310 | 331 | """A list of all my child components.""" |
|
311 | 332 | return self._children |
|
312 | 333 | |
|
313 | 334 | def _remove_child(self, child): |
|
314 | 335 | """A private method for removing children components.""" |
|
315 | 336 | if child in self._children: |
|
316 | 337 | index = self._children.index(child) |
|
317 | 338 | del self._children[index] |
|
318 | 339 | |
|
319 | 340 | def _add_child(self, child): |
|
320 | 341 | """A private method for adding children components.""" |
|
321 | 342 | if child not in self._children: |
|
322 | 343 | self._children.append(child) |
|
323 | 344 | |
|
324 | 345 | def __repr__(self): |
|
325 | 346 | return "<%s('%s')>" % (self.__class__.__name__, self.name) |
@@ -1,229 +1,228 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """sys.excepthook for IPython itself, leaves a detailed report on disk. |
|
3 | 3 | |
|
4 | 4 | |
|
5 | 5 | Authors |
|
6 | 6 | ------- |
|
7 | 7 | - Fernando Perez <Fernando.Perez@berkeley.edu> |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | 12 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #***************************************************************************** |
|
17 | 17 | |
|
18 | 18 | #**************************************************************************** |
|
19 | 19 | # Required modules |
|
20 | 20 | |
|
21 | 21 | # From the standard library |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | from pprint import pformat |
|
25 | 25 | |
|
26 | 26 | # Our own |
|
27 | 27 | from IPython.core import release |
|
28 | 28 | from IPython.core import ultratb |
|
29 | 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 | 33 | """Customizable crash handlers for IPython-based systems. |
|
36 | 34 | |
|
37 | 35 | Instances of this class provide a __call__ method which can be used as a |
|
38 | 36 | sys.excepthook, i.e., the __call__ signature is: |
|
39 | 37 | |
|
40 | 38 | def __call__(self,etype, evalue, etb) |
|
41 | 39 | |
|
42 | 40 | """ |
|
43 | 41 | |
|
44 |
def __init__(self, |
|
|
45 | bug_tracker,crash_report_fname, | |
|
46 | show_crash_traceback=True): | |
|
42 | def __init__(self,app, app_name, contact_name=None, contact_email=None, | |
|
43 | bug_tracker=None, crash_report_fname='CrashReport.txt', | |
|
44 | show_crash_traceback=True, call_pdb=False): | |
|
47 | 45 | """New crash handler. |
|
48 | 46 | |
|
49 | 47 | Inputs: |
|
50 | 48 | |
|
51 |
- |
|
|
52 | for internal information. | |
|
49 | - app: a running application instance, which will be queried at crash | |
|
50 | time for internal information. | |
|
53 | 51 | |
|
54 | 52 | - app_name: a string containing the name of your application. |
|
55 | 53 | |
|
56 | 54 | - contact_name: a string with the name of the person to contact. |
|
57 | 55 | |
|
58 | 56 | - contact_email: a string with the email address of the contact. |
|
59 | 57 | |
|
60 | 58 | - bug_tracker: a string with the URL for your project's bug tracker. |
|
61 | 59 | |
|
62 | 60 | - crash_report_fname: a string with the filename for the crash report |
|
63 | 61 | to be saved in. These reports are left in the ipython user directory |
|
64 | 62 | as determined by the running IPython instance. |
|
65 | 63 | |
|
66 | 64 | Optional inputs: |
|
67 | 65 | |
|
68 | 66 | - show_crash_traceback(True): if false, don't print the crash |
|
69 | 67 | traceback on stderr, only generate the on-disk report |
|
70 | 68 | |
|
71 | 69 | |
|
72 | 70 | Non-argument instance attributes: |
|
73 | 71 | |
|
74 | 72 | These instances contain some non-argument attributes which allow for |
|
75 | 73 | further customization of the crash handler's behavior. Please see the |
|
76 | 74 | source for further details. |
|
77 | 75 | """ |
|
78 | 76 | |
|
79 | 77 | # apply args into instance |
|
80 | self.IP = IP # IPython instance | |
|
78 | self.app = app | |
|
81 | 79 | self.app_name = app_name |
|
82 | 80 | self.contact_name = contact_name |
|
83 | 81 | self.contact_email = contact_email |
|
84 | 82 | self.bug_tracker = bug_tracker |
|
85 | 83 | self.crash_report_fname = crash_report_fname |
|
86 | 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 | 89 | # Hardcoded defaults, which can be overridden either by subclasses or |
|
89 | 90 | # at runtime for the instance. |
|
90 | 91 | |
|
91 | 92 | # Template for the user message. Subclasses which completely override |
|
92 | 93 | # this, or user apps, can modify it to suit their tastes. It gets |
|
93 | 94 | # expanded using itpl, so calls of the kind $self.foo are valid. |
|
94 | 95 | self.user_message_template = """ |
|
95 | 96 | Oops, $self.app_name crashed. We do our best to make it stable, but... |
|
96 | 97 | |
|
97 | 98 | A crash report was automatically generated with the following information: |
|
98 | 99 | - A verbatim copy of the crash traceback. |
|
99 | 100 | - A copy of your input history during this session. |
|
100 | 101 | - Data on your current $self.app_name configuration. |
|
101 | 102 | |
|
102 | 103 | It was left in the file named: |
|
103 | 104 | \t'$self.crash_report_fname' |
|
104 | 105 | If you can email this file to the developers, the information in it will help |
|
105 | 106 | them in understanding and correcting the problem. |
|
106 | 107 | |
|
107 | 108 | You can mail it to: $self.contact_name at $self.contact_email |
|
108 | 109 | with the subject '$self.app_name Crash Report'. |
|
109 | 110 | |
|
110 | 111 | If you want to do it now, the following command will work (under Unix): |
|
111 | 112 | mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname |
|
112 | 113 | |
|
113 | 114 | To ensure accurate tracking of this issue, please file a report about it at: |
|
114 | 115 | $self.bug_tracker |
|
115 | 116 | """ |
|
116 | 117 | |
|
117 | 118 | def __call__(self,etype, evalue, etb): |
|
118 | 119 | """Handle an exception, call for compatible with sys.excepthook""" |
|
119 | 120 | |
|
120 | 121 | # Report tracebacks shouldn't use color in general (safer for users) |
|
121 | 122 | color_scheme = 'NoColor' |
|
122 | 123 | |
|
123 | 124 | # Use this ONLY for developer debugging (keep commented out for release) |
|
124 | 125 | #color_scheme = 'Linux' # dbg |
|
125 | 126 | |
|
126 | 127 | try: |
|
127 |
rptdir = self. |
|
|
128 | rptdir = self.app.ipython_dir | |
|
128 | 129 | except: |
|
129 | 130 | rptdir = os.getcwd() |
|
130 | 131 | if not os.path.isdir(rptdir): |
|
131 | 132 | rptdir = os.getcwd() |
|
132 | 133 | report_name = os.path.join(rptdir,self.crash_report_fname) |
|
133 | 134 | # write the report filename into the instance dict so it can get |
|
134 | 135 | # properly expanded out in the user message template |
|
135 | 136 | self.crash_report_fname = report_name |
|
136 | 137 | TBhandler = ultratb.VerboseTB(color_scheme=color_scheme, |
|
137 |
|
|
|
138 | traceback = TBhandler.text(etype,evalue,etb,context=31) | |
|
138 | long_header=1, | |
|
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 | 147 | # print traceback to screen |
|
141 | 148 | if self.show_crash_traceback: |
|
142 | 149 | print >> sys.stderr, traceback |
|
143 | 150 | |
|
144 | 151 | # and generate a complete report on disk |
|
145 | 152 | try: |
|
146 | 153 | report = open(report_name,'w') |
|
147 | 154 | except: |
|
148 | 155 | print >> sys.stderr, 'Could not create crash report on disk.' |
|
149 | 156 | return |
|
150 | 157 | |
|
151 | 158 | # Inform user on stderr of what happened |
|
152 | 159 | msg = itpl('\n'+'*'*70+'\n'+self.user_message_template) |
|
153 | 160 | print >> sys.stderr, msg |
|
154 | 161 | |
|
155 | 162 | # Construct report on disk |
|
156 | 163 | report.write(self.make_report(traceback)) |
|
157 | 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 | 167 | def make_report(self,traceback): |
|
161 | 168 | """Return a string containing a crash report.""" |
|
162 | ||
|
163 | sec_sep = '\n\n'+'*'*75+'\n\n' | |
|
164 | ||
|
169 | import platform | |
|
170 | ||
|
171 | sec_sep = self.section_sep | |
|
172 | ||
|
165 | 173 | report = [] |
|
166 | 174 | rpt_add = report.append |
|
167 | 175 | |
|
168 | 176 | rpt_add('*'*75+'\n\n'+'IPython post-mortem report\n\n') |
|
169 |
rpt_add('IPython version: %s |
|
|
170 |
rpt_add('BZR revision : %s |
|
|
171 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s' % | |
|
177 | rpt_add('IPython version: %s \n' % release.version) | |
|
178 | rpt_add('BZR revision : %s \n' % release.revision) | |
|
179 | rpt_add('Platform info : os.name -> %s, sys.platform -> %s\n' % | |
|
172 | 180 | (os.name,sys.platform) ) |
|
173 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
|
174 | rpt_add(pformat(self.IP.dict())) | |
|
175 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) | |
|
181 | rpt_add(' : %s\n' % platform.platform()) | |
|
182 | rpt_add('Python info : %s\n' % sys.version) | |
|
183 | ||
|
176 | 184 | try: |
|
177 | rpt_add(sec_sep+"History of session input:") | |
|
178 | for line in self.IP.user_ns['_ih']: | |
|
179 |
|
|
|
180 | rpt_add('\n*** Last line of input (may not be in above history):\n') | |
|
181 | rpt_add(self.IP._last_input_line+'\n') | |
|
185 | config = pformat(self.app.config) | |
|
186 | rpt_add(sec_sep+'Current user configuration structure:\n\n') | |
|
187 | rpt_add(config) | |
|
182 | 188 | except: |
|
183 | 189 | pass |
|
190 | rpt_add(sec_sep+'Crash traceback:\n\n' + traceback) | |
|
184 | 191 | |
|
185 | 192 | return ''.join(report) |
|
186 | 193 | |
|
194 | ||
|
187 | 195 | class IPythonCrashHandler(CrashHandler): |
|
188 | 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 | 200 | # Set here which of the IPython authors should be listed as contact |
|
193 | 201 | AUTHOR_CONTACT = 'Fernando' |
|
194 | 202 | |
|
195 | 203 | # Set argument defaults |
|
196 | app_name = 'IPython' | |
|
197 | 204 | bug_tracker = 'https://bugs.launchpad.net/ipython/+filebug' |
|
198 | 205 | contact_name,contact_email = release.authors[AUTHOR_CONTACT][:2] |
|
199 | 206 | crash_report_fname = 'IPython_crash_report.txt' |
|
200 | 207 | # Call parent constructor |
|
201 |
CrashHandler.__init__(self, |
|
|
208 | CrashHandler.__init__(self,app,app_name,contact_name,contact_email, | |
|
202 | 209 | bug_tracker,crash_report_fname) |
|
203 | 210 | |
|
204 | 211 | def make_report(self,traceback): |
|
205 | 212 | """Return a string containing a crash report.""" |
|
206 | 213 | |
|
207 | sec_sep = '\n\n'+'*'*75+'\n\n' | |
|
208 | ||
|
209 | report = [] | |
|
214 | sec_sep = self.section_sep | |
|
215 | # Start with parent report | |
|
216 | report = [super(IPythonCrashHandler, self).make_report(traceback)] | |
|
217 | # Add interactive-specific info we may have | |
|
210 | 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 | 219 | try: |
|
221 | 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 | 222 | rpt_add(line) |
|
224 | 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 | 225 | except: |
|
227 | 226 | pass |
|
228 | 227 | |
|
229 | 228 | return ''.join(report) |
@@ -1,524 +1,512 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Pdb debugger class. |
|
4 | 4 | |
|
5 | 5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
6 | 6 | the command line completion of other programs which include this isn't |
|
7 | 7 | damaged. |
|
8 | 8 | |
|
9 | 9 | In the future, this class will be expanded with improvements over the standard |
|
10 | 10 | pdb. |
|
11 | 11 | |
|
12 | 12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
13 | 13 | changes. Licensing should therefore be under the standard Python terms. For |
|
14 | 14 | details on the PSF (Python Software Foundation) standard license, see: |
|
15 | 15 | |
|
16 | 16 | http://www.python.org/2.2.3/license.html""" |
|
17 | 17 | |
|
18 | 18 | #***************************************************************************** |
|
19 | 19 | # |
|
20 | 20 | # This file is licensed under the PSF license. |
|
21 | 21 | # |
|
22 | 22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
23 | 23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
24 | 24 | # |
|
25 | 25 | # |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | |
|
28 | 28 | import bdb |
|
29 | 29 | import cmd |
|
30 | 30 | import linecache |
|
31 | 31 | import os |
|
32 | 32 | import sys |
|
33 | 33 | |
|
34 | 34 | from IPython.utils import PyColorize |
|
35 | 35 | from IPython.core import ipapi |
|
36 | 36 | from IPython.utils import coloransi |
|
37 | 37 | from IPython.utils.genutils import Term |
|
38 | 38 | from IPython.core.excolors import exception_colors |
|
39 | 39 | |
|
40 | 40 | # See if we can use pydb. |
|
41 | 41 | has_pydb = False |
|
42 | 42 | prompt = 'ipdb> ' |
|
43 | 43 | #We have to check this directly from sys.argv, config struct not yet available |
|
44 | 44 | if '-pydb' in sys.argv: |
|
45 | 45 | try: |
|
46 | 46 | import pydb |
|
47 | 47 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
48 | 48 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
49 | 49 | # better protect against it. |
|
50 | 50 | has_pydb = True |
|
51 | 51 | except ImportError: |
|
52 | 52 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" |
|
53 | 53 | |
|
54 | 54 | if has_pydb: |
|
55 | 55 | from pydb import Pdb as OldPdb |
|
56 | 56 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
57 | 57 | prompt = 'ipydb> ' |
|
58 | 58 | else: |
|
59 | 59 | from pdb import Pdb as OldPdb |
|
60 | 60 | |
|
61 | 61 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
62 | 62 | # it does so with some limitations. The rest of this support is implemented in |
|
63 | 63 | # the Tracer constructor. |
|
64 | 64 | def BdbQuit_excepthook(et,ev,tb): |
|
65 | 65 | if et==bdb.BdbQuit: |
|
66 | 66 | print 'Exiting Debugger.' |
|
67 | 67 | else: |
|
68 | 68 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
69 | 69 | |
|
70 | 70 | def BdbQuit_IPython_excepthook(self,et,ev,tb): |
|
71 | 71 | print 'Exiting Debugger.' |
|
72 | 72 | |
|
73 | ||
|
73 | 74 | class Tracer(object): |
|
74 | 75 | """Class for local debugging, similar to pdb.set_trace. |
|
75 | 76 | |
|
76 | 77 | Instances of this class, when called, behave like pdb.set_trace, but |
|
77 | 78 | providing IPython's enhanced capabilities. |
|
78 | 79 | |
|
79 | 80 | This is implemented as a class which must be initialized in your own code |
|
80 | 81 | and not as a standalone function because we need to detect at runtime |
|
81 | 82 | whether IPython is already active or not. That detection is done in the |
|
82 | 83 | constructor, ensuring that this code plays nicely with a running IPython, |
|
83 | 84 | while functioning acceptably (though with limitations) if outside of it. |
|
84 | 85 | """ |
|
85 | 86 | |
|
86 | 87 | def __init__(self,colors=None): |
|
87 | 88 | """Create a local debugger instance. |
|
88 | 89 | |
|
89 | 90 | :Parameters: |
|
90 | 91 | |
|
91 | 92 | - `colors` (None): a string containing the name of the color scheme to |
|
92 | 93 | use, it must be one of IPython's valid color schemes. If not given, the |
|
93 | 94 | function will default to the current IPython scheme when running inside |
|
94 | 95 | IPython, and to 'NoColor' otherwise. |
|
95 | 96 | |
|
96 | 97 | Usage example: |
|
97 | 98 | |
|
98 | 99 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
99 | 100 | |
|
100 | 101 | ... later in your code |
|
101 | 102 | debug_here() # -> will open up the debugger at that point. |
|
102 | 103 | |
|
103 | 104 | Once the debugger activates, you can use all of its regular commands to |
|
104 | 105 | step through code, set breakpoints, etc. See the pdb documentation |
|
105 | 106 | from the Python standard library for usage details. |
|
106 | 107 | """ |
|
107 | 108 | |
|
108 | global __IPYTHON__ | |
|
109 | 109 | try: |
|
110 | __IPYTHON__ | |
|
111 |
except |
|
|
110 | ip = ipapi.get() | |
|
111 | except: | |
|
112 | 112 | # Outside of ipython, we set our own exception hook manually |
|
113 | __IPYTHON__ = ipapi.get() | |
|
114 | 113 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
115 | 114 | sys.excepthook = BdbQuit_excepthook |
|
116 | 115 | def_colors = 'NoColor' |
|
117 | 116 | try: |
|
118 | 117 | # Limited tab completion support |
|
119 | 118 | import readline |
|
120 | 119 | readline.parse_and_bind('tab: complete') |
|
121 | 120 | except ImportError: |
|
122 | 121 | pass |
|
123 | 122 | else: |
|
124 | 123 | # In ipython, we use its custom exception handler mechanism |
|
125 | ip = ipapi.get() | |
|
126 | 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 | 127 | if colors is None: |
|
130 | 128 | colors = def_colors |
|
131 | 129 | self.debugger = Pdb(colors) |
|
132 | 130 | |
|
133 | 131 | def __call__(self): |
|
134 | 132 | """Starts an interactive debugger at the point where called. |
|
135 | 133 | |
|
136 | 134 | This is similar to the pdb.set_trace() function from the std lib, but |
|
137 | 135 | using IPython's enhanced debugger.""" |
|
138 | 136 | |
|
139 | 137 | self.debugger.set_trace(sys._getframe().f_back) |
|
140 | 138 | |
|
139 | ||
|
141 | 140 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
142 | 141 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
143 | 142 | for the do_... commands that hook into the help system. |
|
144 | 143 | Adapted from from a comp.lang.python posting |
|
145 | 144 | by Duncan Booth.""" |
|
146 | 145 | def wrapper(*args, **kw): |
|
147 | 146 | return new_fn(*args, **kw) |
|
148 | 147 | if old_fn.__doc__: |
|
149 | 148 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
150 | 149 | return wrapper |
|
151 | 150 | |
|
151 | ||
|
152 | 152 | def _file_lines(fname): |
|
153 | 153 | """Return the contents of a named file as a list of lines. |
|
154 | 154 | |
|
155 | 155 | This function never raises an IOError exception: if the file can't be |
|
156 | 156 | read, it simply returns an empty list.""" |
|
157 | 157 | |
|
158 | 158 | try: |
|
159 | 159 | outfile = open(fname) |
|
160 | 160 | except IOError: |
|
161 | 161 | return [] |
|
162 | 162 | else: |
|
163 | 163 | out = outfile.readlines() |
|
164 | 164 | outfile.close() |
|
165 | 165 | return out |
|
166 | 166 | |
|
167 | ||
|
167 | 168 | class Pdb(OldPdb): |
|
168 | 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, | |
|
172 | stdin=None, stdout=None): | |
|
171 | def __init__(self,color_scheme='NoColor',completekey=None, | |
|
172 | stdin=None, stdout=None): | |
|
173 | 173 | |
|
174 |
|
|
|
175 |
|
|
|
176 |
|
|
|
177 |
|
|
|
178 |
|
|
|
179 | ||
|
180 | self.prompt = prompt # The default prompt is '(Pdb)' | |
|
174 | # Parent constructor: | |
|
175 | if has_pydb and completekey is None: | |
|
176 | OldPdb.__init__(self,stdin=stdin,stdout=Term.cout) | |
|
177 | else: | |
|
178 | OldPdb.__init__(self,completekey,stdin,stdout) | |
|
181 | 179 | |
|
182 | # IPython changes... | |
|
183 | self.is_pydb = has_pydb | |
|
184 | ||
|
185 |
|
|
|
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() | |
|
180 | self.prompt = prompt # The default prompt is '(Pdb)' | |
|
181 | ||
|
182 | # IPython changes... | |
|
183 | self.is_pydb = has_pydb | |
|
210 | 184 | |
|
211 | # shorthands | |
|
212 | C = coloransi.TermColors | |
|
213 | cst = self.color_scheme_table | |
|
185 | self.shell = ipapi.get() | |
|
214 | 186 | |
|
215 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
|
216 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
|
187 | if self.is_pydb: | |
|
217 | 188 | |
|
218 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
|
219 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
|
189 | # iplib.py's ipalias seems to want pdb's checkline | |
|
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 | |
|
222 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
|
195 | self.curframe = None | |
|
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 | |
|
227 | # debugging. | |
|
228 | self.parser = PyColorize.Parser() | |
|
201 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, | |
|
202 | OldPdb.do_list) | |
|
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: | |
|
232 | # Ugly hack: for Python 2.3-2.4, we can't call the parent constructor, | |
|
233 | # because it binds readline and breaks tab-completion. This means we | |
|
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")) | |
|
209 | # Create color table: we copy the default one from the traceback | |
|
210 | # module and add a few attributes needed for debugging | |
|
211 | self.color_scheme_table = exception_colors() | |
|
253 | 212 | |
|
254 | # Create color table: we copy the default one from the traceback | |
|
255 | # module and add a few attributes needed for debugging | |
|
256 |
|
|
|
213 | # shorthands | |
|
214 | C = coloransi.TermColors | |
|
215 | cst = self.color_scheme_table | |
|
257 | 216 | |
|
258 | # shorthands | |
|
259 | C = coloransi.TermColors | |
|
260 | cst = self.color_scheme_table | |
|
217 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
|
218 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
|
261 | 219 | |
|
262 |
|
|
|
263 |
|
|
|
220 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
|
221 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
|
264 | 222 | |
|
265 |
|
|
|
266 |
|
|
|
223 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
|
224 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
|
267 | 225 | |
|
268 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
|
269 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
|
226 | self.set_colors(color_scheme) | |
|
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 | 232 | def set_colors(self, scheme): |
|
278 | 233 | """Shorthand access to the color table scheme selector method.""" |
|
279 | 234 | self.color_scheme_table.set_active_scheme(scheme) |
|
280 | 235 | |
|
281 | 236 | def interaction(self, frame, traceback): |
|
282 |
|
|
|
237 | self.shell.set_completer_frame(frame) | |
|
283 | 238 | OldPdb.interaction(self, frame, traceback) |
|
284 | 239 | |
|
285 | 240 | def new_do_up(self, arg): |
|
286 | 241 | OldPdb.do_up(self, arg) |
|
287 |
|
|
|
242 | self.shell.set_completer_frame(self.curframe) | |
|
288 | 243 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
289 | 244 | |
|
290 | 245 | def new_do_down(self, arg): |
|
291 | 246 | OldPdb.do_down(self, arg) |
|
292 |
|
|
|
247 | self.shell.set_completer_frame(self.curframe) | |
|
293 | 248 | |
|
294 | 249 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
295 | 250 | |
|
296 | 251 | def new_do_frame(self, arg): |
|
297 | 252 | OldPdb.do_frame(self, arg) |
|
298 |
|
|
|
253 | self.shell.set_completer_frame(self.curframe) | |
|
299 | 254 | |
|
300 | 255 | def new_do_quit(self, arg): |
|
301 | 256 | |
|
302 | 257 | if hasattr(self, 'old_all_completions'): |
|
303 |
|
|
|
258 | self.shell.Completer.all_completions=self.old_all_completions | |
|
304 | 259 | |
|
305 | 260 | |
|
306 | 261 | return OldPdb.do_quit(self, arg) |
|
307 | 262 | |
|
308 | 263 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
309 | 264 | |
|
310 | 265 | def new_do_restart(self, arg): |
|
311 | 266 | """Restart command. In the context of ipython this is exactly the same |
|
312 | 267 | thing as 'quit'.""" |
|
313 | 268 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
314 | 269 | return self.do_quit(arg) |
|
315 | 270 | |
|
316 | 271 | def postloop(self): |
|
317 |
|
|
|
272 | self.shell.set_completer_frame(None) | |
|
318 | 273 | |
|
319 | 274 | def print_stack_trace(self): |
|
320 | 275 | try: |
|
321 | 276 | for frame_lineno in self.stack: |
|
322 | 277 | self.print_stack_entry(frame_lineno, context = 5) |
|
323 | 278 | except KeyboardInterrupt: |
|
324 | 279 | pass |
|
325 | 280 | |
|
326 | 281 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
327 | 282 | context = 3): |
|
328 | 283 | #frame, lineno = frame_lineno |
|
329 | 284 | print >>Term.cout, self.format_stack_entry(frame_lineno, '', context) |
|
330 | 285 | |
|
331 | 286 | # vds: >> |
|
332 | 287 | frame, lineno = frame_lineno |
|
333 | 288 | filename = frame.f_code.co_filename |
|
334 |
|
|
|
289 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
|
335 | 290 | # vds: << |
|
336 | 291 | |
|
337 | 292 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
338 | 293 | import linecache, repr |
|
339 | 294 | |
|
340 | 295 | ret = [] |
|
341 | 296 | |
|
342 | 297 | Colors = self.color_scheme_table.active_colors |
|
343 | 298 | ColorsNormal = Colors.Normal |
|
344 | 299 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
345 | 300 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
346 | 301 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
347 | 302 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
348 | 303 | ColorsNormal) |
|
349 | 304 | |
|
350 | 305 | frame, lineno = frame_lineno |
|
351 | 306 | |
|
352 | 307 | return_value = '' |
|
353 | 308 | if '__return__' in frame.f_locals: |
|
354 | 309 | rv = frame.f_locals['__return__'] |
|
355 | 310 | #return_value += '->' |
|
356 | 311 | return_value += repr.repr(rv) + '\n' |
|
357 | 312 | ret.append(return_value) |
|
358 | 313 | |
|
359 | 314 | #s = filename + '(' + `lineno` + ')' |
|
360 | 315 | filename = self.canonic(frame.f_code.co_filename) |
|
361 | 316 | link = tpl_link % filename |
|
362 | 317 | |
|
363 | 318 | if frame.f_code.co_name: |
|
364 | 319 | func = frame.f_code.co_name |
|
365 | 320 | else: |
|
366 | 321 | func = "<lambda>" |
|
367 | 322 | |
|
368 | 323 | call = '' |
|
369 | 324 | if func != '?': |
|
370 | 325 | if '__args__' in frame.f_locals: |
|
371 | 326 | args = repr.repr(frame.f_locals['__args__']) |
|
372 | 327 | else: |
|
373 | 328 | args = '()' |
|
374 | 329 | call = tpl_call % (func, args) |
|
375 | 330 | |
|
376 | 331 | # The level info should be generated in the same format pdb uses, to |
|
377 | 332 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
378 | 333 | if frame is self.curframe: |
|
379 | 334 | ret.append('> ') |
|
380 | 335 | else: |
|
381 | 336 | ret.append(' ') |
|
382 | 337 | ret.append('%s(%s)%s\n' % (link,lineno,call)) |
|
383 | 338 | |
|
384 | 339 | start = lineno - 1 - context//2 |
|
385 | 340 | lines = linecache.getlines(filename) |
|
386 | 341 | start = max(start, 0) |
|
387 | 342 | start = min(start, len(lines) - context) |
|
388 | 343 | lines = lines[start : start + context] |
|
389 | 344 | |
|
390 | 345 | for i,line in enumerate(lines): |
|
391 | 346 | show_arrow = (start + 1 + i == lineno) |
|
392 | 347 | linetpl = (frame is self.curframe or show_arrow) \ |
|
393 | 348 | and tpl_line_em \ |
|
394 | 349 | or tpl_line |
|
395 | 350 | ret.append(self.__format_line(linetpl, filename, |
|
396 | 351 | start + 1 + i, line, |
|
397 | 352 | arrow = show_arrow) ) |
|
398 | 353 | |
|
399 | 354 | return ''.join(ret) |
|
400 | 355 | |
|
401 | 356 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
402 | 357 | bp_mark = "" |
|
403 | 358 | bp_mark_color = "" |
|
404 | 359 | |
|
405 | 360 | scheme = self.color_scheme_table.active_scheme_name |
|
406 | 361 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
407 | 362 | if not err: line = new_line |
|
408 | 363 | |
|
409 | 364 | bp = None |
|
410 | 365 | if lineno in self.get_file_breaks(filename): |
|
411 | 366 | bps = self.get_breaks(filename, lineno) |
|
412 | 367 | bp = bps[-1] |
|
413 | 368 | |
|
414 | 369 | if bp: |
|
415 | 370 | Colors = self.color_scheme_table.active_colors |
|
416 | 371 | bp_mark = str(bp.number) |
|
417 | 372 | bp_mark_color = Colors.breakpoint_enabled |
|
418 | 373 | if not bp.enabled: |
|
419 | 374 | bp_mark_color = Colors.breakpoint_disabled |
|
420 | 375 | |
|
421 | 376 | numbers_width = 7 |
|
422 | 377 | if arrow: |
|
423 | 378 | # This is the line with the error |
|
424 | 379 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
425 | 380 | if pad >= 3: |
|
426 | 381 | marker = '-'*(pad-3) + '-> ' |
|
427 | 382 | elif pad == 2: |
|
428 | 383 | marker = '> ' |
|
429 | 384 | elif pad == 1: |
|
430 | 385 | marker = '>' |
|
431 | 386 | else: |
|
432 | 387 | marker = '' |
|
433 | 388 | num = '%s%s' % (marker, str(lineno)) |
|
434 | 389 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
435 | 390 | else: |
|
436 | 391 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
437 | 392 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
438 | 393 | |
|
439 | 394 | return line |
|
440 | 395 | |
|
441 | 396 | def list_command_pydb(self, arg): |
|
442 | 397 | """List command to use if we have a newer pydb installed""" |
|
443 | 398 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
444 | 399 | if filename is not None: |
|
445 | 400 | self.print_list_lines(filename, first, last) |
|
446 | 401 | |
|
447 | 402 | def print_list_lines(self, filename, first, last): |
|
448 | 403 | """The printing (as opposed to the parsing part of a 'list' |
|
449 | 404 | command.""" |
|
450 | 405 | try: |
|
451 | 406 | Colors = self.color_scheme_table.active_colors |
|
452 | 407 | ColorsNormal = Colors.Normal |
|
453 | 408 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
454 | 409 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
455 | 410 | src = [] |
|
456 | 411 | for lineno in range(first, last+1): |
|
457 | 412 | line = linecache.getline(filename, lineno) |
|
458 | 413 | if not line: |
|
459 | 414 | break |
|
460 | 415 | |
|
461 | 416 | if lineno == self.curframe.f_lineno: |
|
462 | 417 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
463 | 418 | else: |
|
464 | 419 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
465 | 420 | |
|
466 | 421 | src.append(line) |
|
467 | 422 | self.lineno = lineno |
|
468 | 423 | |
|
469 | 424 | print >>Term.cout, ''.join(src) |
|
470 | 425 | |
|
471 | 426 | except KeyboardInterrupt: |
|
472 | 427 | pass |
|
473 | 428 | |
|
474 | 429 | def do_list(self, arg): |
|
475 | 430 | self.lastcmd = 'list' |
|
476 | 431 | last = None |
|
477 | 432 | if arg: |
|
478 | 433 | try: |
|
479 | 434 | x = eval(arg, {}, {}) |
|
480 | 435 | if type(x) == type(()): |
|
481 | 436 | first, last = x |
|
482 | 437 | first = int(first) |
|
483 | 438 | last = int(last) |
|
484 | 439 | if last < first: |
|
485 | 440 | # Assume it's a count |
|
486 | 441 | last = first + last |
|
487 | 442 | else: |
|
488 | 443 | first = max(1, int(x) - 5) |
|
489 | 444 | except: |
|
490 | 445 | print '*** Error in argument:', `arg` |
|
491 | 446 | return |
|
492 | 447 | elif self.lineno is None: |
|
493 | 448 | first = max(1, self.curframe.f_lineno - 5) |
|
494 | 449 | else: |
|
495 | 450 | first = self.lineno + 1 |
|
496 | 451 | if last is None: |
|
497 | 452 | last = first + 10 |
|
498 | 453 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
499 | 454 | |
|
500 | 455 | # vds: >> |
|
501 | 456 | lineno = first |
|
502 | 457 | filename = self.curframe.f_code.co_filename |
|
503 |
|
|
|
458 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
|
504 | 459 | # vds: << |
|
505 | 460 | |
|
506 | 461 | do_l = do_list |
|
507 | 462 | |
|
508 | 463 | def do_pdef(self, arg): |
|
509 | 464 | """The debugger interface to magic_pdef""" |
|
510 | 465 | namespaces = [('Locals', self.curframe.f_locals), |
|
511 | 466 | ('Globals', self.curframe.f_globals)] |
|
512 |
|
|
|
467 | self.shell.magic_pdef(arg, namespaces=namespaces) | |
|
513 | 468 | |
|
514 | 469 | def do_pdoc(self, arg): |
|
515 | 470 | """The debugger interface to magic_pdoc""" |
|
516 | 471 | namespaces = [('Locals', self.curframe.f_locals), |
|
517 | 472 | ('Globals', self.curframe.f_globals)] |
|
518 |
|
|
|
473 | self.shell.magic_pdoc(arg, namespaces=namespaces) | |
|
519 | 474 | |
|
520 | 475 | def do_pinfo(self, arg): |
|
521 | 476 | """The debugger equivalant of ?obj""" |
|
522 | 477 | namespaces = [('Locals', self.curframe.f_locals), |
|
523 | 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 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | A context manager for handling sys.displayhook. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Robert Kern |
|
9 | 9 | * Brian Granger |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (C) 2008-2009 The IPython Development Team |
|
14 | 14 | # |
|
15 | 15 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | 16 | # the file COPYING, distributed as part of this software. |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Imports |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | import sys |
|
24 | 24 | |
|
25 | 25 | from IPython.core.component import Component |
|
26 | 26 | |
|
27 | 27 | from IPython.utils.autoattr import auto_attr |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Classes and functions |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | class DisplayTrap(Component): |
|
35 | 35 | """Object to manage sys.displayhook. |
|
36 | 36 | |
|
37 | 37 | This came from IPython.core.kernel.display_hook, but is simplified |
|
38 | 38 | (no callbacks or formatters) until more of the core is refactored. |
|
39 | 39 | """ |
|
40 | 40 | |
|
41 | 41 | def __init__(self, parent, hook): |
|
42 | 42 | super(DisplayTrap, self).__init__(parent, None, None) |
|
43 | 43 | self.hook = hook |
|
44 | 44 | self.old_hook = None |
|
45 | 45 | # We define this to track if a single BuiltinTrap is nested. |
|
46 | 46 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
47 | 47 | self._nested_level = 0 |
|
48 | 48 | |
|
49 | @auto_attr | |
|
50 | def shell(self): | |
|
51 | return Component.get_instances( | |
|
52 | root=self.root, | |
|
53 | klass='IPython.core.iplib.InteractiveShell')[0] | |
|
49 | # @auto_attr | |
|
50 | # def shell(self): | |
|
51 | # return Component.get_instances( | |
|
52 | # root=self.root, | |
|
53 | # klass='IPython.core.iplib.InteractiveShell')[0] | |
|
54 | 54 | |
|
55 | 55 | def __enter__(self): |
|
56 | 56 | if self._nested_level == 0: |
|
57 | 57 | self.set() |
|
58 | 58 | self._nested_level += 1 |
|
59 | 59 | return self |
|
60 | 60 | |
|
61 | 61 | def __exit__(self, type, value, traceback): |
|
62 | 62 | if self._nested_level == 1: |
|
63 | 63 | self.unset() |
|
64 | 64 | self._nested_level -= 1 |
|
65 | 65 | # Returning False will cause exceptions to propagate |
|
66 | 66 | return False |
|
67 | 67 | |
|
68 | 68 | def set(self): |
|
69 | 69 | """Set the hook.""" |
|
70 | 70 | if sys.displayhook is not self.hook: |
|
71 | 71 | self.old_hook = sys.displayhook |
|
72 | 72 | sys.displayhook = self.hook |
|
73 | 73 | |
|
74 | 74 | def unset(self): |
|
75 | 75 | """Unset the hook.""" |
|
76 | 76 | sys.displayhook = self.old_hook |
|
77 | 77 |
@@ -1,280 +1,272 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | An embedded IPython shell. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez |
|
10 | 10 | |
|
11 | 11 | Notes |
|
12 | 12 | ----- |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | from __future__ import with_statement |
|
27 | 27 | |
|
28 | 28 | import sys |
|
29 | 29 | from contextlib import nested |
|
30 | 30 | |
|
31 | 31 | from IPython.core import ultratb |
|
32 | 32 | from IPython.core.iplib import InteractiveShell |
|
33 | 33 | from IPython.core.ipapp import load_default_config |
|
34 | 34 | |
|
35 | 35 | from IPython.utils.traitlets import Bool, Str, CBool |
|
36 | 36 | from IPython.utils.genutils import ask_yes_no |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | #----------------------------------------------------------------------------- |
|
40 | 40 | # Classes and functions |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | |
|
43 | 43 | # This is an additional magic that is exposed in embedded shells. |
|
44 | 44 | def kill_embedded(self,parameter_s=''): |
|
45 | 45 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
46 | 46 | |
|
47 | 47 | This function (after asking for confirmation) sets an internal flag so that |
|
48 | 48 | an embedded IPython will never activate again. This is useful to |
|
49 | 49 | permanently disable a shell that is being called inside a loop: once you've |
|
50 | 50 | figured out what you needed from it, you may then kill it and the program |
|
51 | 51 | will then continue to run without the interactive shell interfering again. |
|
52 | 52 | """ |
|
53 | 53 | |
|
54 | 54 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
55 | 55 | "(y/n)? [y/N] ",'n') |
|
56 | 56 | if kill: |
|
57 | 57 | self.embedded_active = False |
|
58 | 58 | print "This embedded IPython will not reactivate anymore once you exit." |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | class InteractiveShellEmbed(InteractiveShell): |
|
62 | 62 | |
|
63 | 63 | dummy_mode = Bool(False) |
|
64 | 64 | exit_msg = Str('') |
|
65 | 65 | embedded = CBool(True) |
|
66 | 66 | embedded_active = CBool(True) |
|
67 | 67 | # Like the base class display_banner is not configurable, but here it |
|
68 | 68 | # is True by default. |
|
69 | 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 | 72 | user_ns=None, user_global_ns=None, |
|
73 | 73 | banner1=None, banner2=None, display_banner=None, |
|
74 | 74 | custom_exceptions=((),None), exit_msg=''): |
|
75 | 75 | |
|
76 | 76 | self.save_sys_ipcompleter() |
|
77 | 77 | |
|
78 | 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 | 80 | user_ns=user_ns, user_global_ns=user_global_ns, |
|
81 | 81 | banner1=banner1, banner2=banner2, display_banner=display_banner, |
|
82 | 82 | custom_exceptions=custom_exceptions) |
|
83 | 83 | |
|
84 | 84 | self.exit_msg = exit_msg |
|
85 | 85 | self.define_magic("kill_embedded", kill_embedded) |
|
86 | 86 | |
|
87 | 87 | # don't use the ipython crash handler so that user exceptions aren't |
|
88 | 88 | # trapped |
|
89 | 89 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
90 | 90 | mode=self.xmode, |
|
91 | 91 | call_pdb=self.pdb) |
|
92 | 92 | |
|
93 | 93 | self.restore_sys_ipcompleter() |
|
94 | 94 | |
|
95 | 95 | def init_sys_modules(self): |
|
96 | 96 | pass |
|
97 | 97 | |
|
98 | 98 | def save_sys_ipcompleter(self): |
|
99 | 99 | """Save readline completer status.""" |
|
100 | 100 | try: |
|
101 | 101 | #print 'Save completer',sys.ipcompleter # dbg |
|
102 | 102 | self.sys_ipcompleter_orig = sys.ipcompleter |
|
103 | 103 | except: |
|
104 | 104 | pass # not nested with IPython |
|
105 | 105 | |
|
106 | 106 | def restore_sys_ipcompleter(self): |
|
107 | 107 | """Restores the readline completer which was in place. |
|
108 | 108 | |
|
109 | 109 | This allows embedded IPython within IPython not to disrupt the |
|
110 | 110 | parent's completion. |
|
111 | 111 | """ |
|
112 | 112 | try: |
|
113 | 113 | self.readline.set_completer(self.sys_ipcompleter_orig) |
|
114 | 114 | sys.ipcompleter = self.sys_ipcompleter_orig |
|
115 | 115 | except: |
|
116 | 116 | pass |
|
117 | 117 | |
|
118 | 118 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, |
|
119 | 119 | stack_depth=1): |
|
120 | 120 | """Activate the interactive interpreter. |
|
121 | 121 | |
|
122 | 122 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
123 | 123 | the interpreter shell with the given local and global namespaces, and |
|
124 | 124 | optionally print a header string at startup. |
|
125 | 125 | |
|
126 | 126 | The shell can be globally activated/deactivated using the |
|
127 | 127 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
128 | 128 | for debugging globally. |
|
129 | 129 | |
|
130 | 130 | However, *each* time you call the shell you can override the current |
|
131 | 131 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
132 | 132 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
133 | 133 | can still have a specific call work by making it as IPShell(dummy=0). |
|
134 | 134 | |
|
135 | 135 | The optional keyword parameter dummy controls whether the call |
|
136 | 136 | actually does anything. |
|
137 | 137 | """ |
|
138 | 138 | |
|
139 | 139 | # If the user has turned it off, go away |
|
140 | 140 | if not self.embedded_active: |
|
141 | 141 | return |
|
142 | 142 | |
|
143 | 143 | # Normal exits from interactive mode set this flag, so the shell can't |
|
144 | 144 | # re-enter (it checks this variable at the start of interactive mode). |
|
145 | 145 | self.exit_now = False |
|
146 | 146 | |
|
147 | 147 | # Allow the dummy parameter to override the global __dummy_mode |
|
148 | 148 | if dummy or (dummy != 0 and self.dummy_mode): |
|
149 | 149 | return |
|
150 | 150 | |
|
151 | 151 | if self.has_readline: |
|
152 | 152 | self.set_completer() |
|
153 | 153 | |
|
154 | 154 | # self.banner is auto computed |
|
155 | 155 | if header: |
|
156 | 156 | self.old_banner2 = self.banner2 |
|
157 | 157 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
158 | 158 | |
|
159 | 159 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
160 | 160 | # our call and get the original caller's namespaces. |
|
161 | 161 | self.mainloop(local_ns, global_ns, stack_depth=stack_depth) |
|
162 | 162 | |
|
163 | 163 | self.banner2 = self.old_banner2 |
|
164 | 164 | |
|
165 | 165 | if self.exit_msg is not None: |
|
166 | 166 | print self.exit_msg |
|
167 | 167 | |
|
168 | 168 | self.restore_sys_ipcompleter() |
|
169 | 169 | |
|
170 | 170 | def mainloop(self, local_ns=None, global_ns=None, stack_depth=0, |
|
171 | 171 | display_banner=None): |
|
172 | 172 | """Embeds IPython into a running python program. |
|
173 | 173 | |
|
174 | 174 | Input: |
|
175 | 175 | |
|
176 | 176 | - header: An optional header message can be specified. |
|
177 | 177 | |
|
178 | 178 | - local_ns, global_ns: working namespaces. If given as None, the |
|
179 | 179 | IPython-initialized one is updated with __main__.__dict__, so that |
|
180 | 180 | program variables become visible but user-specific configuration |
|
181 | 181 | remains possible. |
|
182 | 182 | |
|
183 | 183 | - stack_depth: specifies how many levels in the stack to go to |
|
184 | 184 | looking for namespaces (when local_ns and global_ns are None). This |
|
185 | 185 | allows an intermediate caller to make sure that this function gets |
|
186 | 186 | the namespace from the intended level in the stack. By default (0) |
|
187 | 187 | it will get its locals and globals from the immediate caller. |
|
188 | 188 | |
|
189 | 189 | Warning: it's possible to use this in a program which is being run by |
|
190 | 190 | IPython itself (via %run), but some funny things will happen (a few |
|
191 | 191 | globals get overwritten). In the future this will be cleaned up, as |
|
192 | 192 | there is no fundamental reason why it can't work perfectly.""" |
|
193 | 193 | |
|
194 | 194 | # Get locals and globals from caller |
|
195 | 195 | if local_ns is None or global_ns is None: |
|
196 | 196 | call_frame = sys._getframe(stack_depth).f_back |
|
197 | 197 | |
|
198 | 198 | if local_ns is None: |
|
199 | 199 | local_ns = call_frame.f_locals |
|
200 | 200 | if global_ns is None: |
|
201 | 201 | global_ns = call_frame.f_globals |
|
202 | 202 | |
|
203 | 203 | # Update namespaces and fire up interpreter |
|
204 | 204 | |
|
205 | 205 | # The global one is easy, we can just throw it in |
|
206 | 206 | self.user_global_ns = global_ns |
|
207 | 207 | |
|
208 | 208 | # but the user/local one is tricky: ipython needs it to store internal |
|
209 | 209 | # data, but we also need the locals. We'll copy locals in the user |
|
210 | 210 | # one, but will track what got copied so we can delete them at exit. |
|
211 | 211 | # This is so that a later embedded call doesn't see locals from a |
|
212 | 212 | # previous call (which most likely existed in a separate scope). |
|
213 | 213 | local_varnames = local_ns.keys() |
|
214 | 214 | self.user_ns.update(local_ns) |
|
215 | 215 | #self.user_ns['local_ns'] = local_ns # dbg |
|
216 | 216 | |
|
217 | 217 | # Patch for global embedding to make sure that things don't overwrite |
|
218 | 218 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
219 | 219 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
220 | 220 | if local_ns is None and global_ns is None: |
|
221 | 221 | self.user_global_ns.update(__main__.__dict__) |
|
222 | 222 | |
|
223 | 223 | # make sure the tab-completer has the correct frame information, so it |
|
224 | 224 | # actually completes using the frame's locals/globals |
|
225 | 225 | self.set_completer_frame() |
|
226 | 226 | |
|
227 | 227 | with nested(self.builtin_trap, self.display_trap): |
|
228 | 228 | self.interact(display_banner=display_banner) |
|
229 | 229 | |
|
230 | 230 | # now, purge out the user namespace from anything we might have added |
|
231 | 231 | # from the caller's local namespace |
|
232 | 232 | delvar = self.user_ns.pop |
|
233 | 233 | for var in local_varnames: |
|
234 | 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 | 237 | _embedded_shell = None |
|
246 | 238 | |
|
247 | 239 | |
|
248 | 240 | def embed(header='', config=None, usage=None, banner1=None, banner2=None, |
|
249 | 241 | display_banner=True, exit_msg=''): |
|
250 | 242 | """Call this to embed IPython at the current point in your program. |
|
251 | 243 | |
|
252 | 244 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
253 | 245 | instance and then call it. Consecutive calls just call the already |
|
254 | 246 | created instance. |
|
255 | 247 | |
|
256 | 248 | Here is a simple example:: |
|
257 | 249 | |
|
258 | 250 | from IPython import embed |
|
259 | 251 | a = 10 |
|
260 | 252 | b = 20 |
|
261 | 253 | embed('First time') |
|
262 | 254 | c = 30 |
|
263 | 255 | d = 40 |
|
264 | 256 | embed |
|
265 | 257 | |
|
266 | 258 | Full customization can be done by passing a :class:`Struct` in as the |
|
267 | 259 | config argument. |
|
268 | 260 | """ |
|
269 | 261 | if config is None: |
|
270 | 262 | config = load_default_config() |
|
271 | 263 | config.InteractiveShellEmbed = config.InteractiveShell |
|
272 | 264 | global _embedded_shell |
|
273 | 265 | if _embedded_shell is None: |
|
274 | 266 | _embedded_shell = InteractiveShellEmbed( |
|
275 | 267 | config=config, usage=usage, |
|
276 | 268 | banner1=banner1, banner2=banner2, |
|
277 | 269 | display_banner=display_banner, exit_msg=exit_msg |
|
278 | 270 | ) |
|
279 | 271 | _embedded_shell(header=header, stack_depth=2) |
|
280 | 272 |
@@ -1,254 +1,274 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ History related magics and functionality """ |
|
3 | 3 | |
|
4 | 4 | # Stdlib imports |
|
5 | 5 | import fnmatch |
|
6 | 6 | import os |
|
7 | 7 | |
|
8 | 8 | from IPython.utils.genutils import Term, ask_yes_no, warn |
|
9 | 9 | from IPython.core import ipapi |
|
10 | 10 | |
|
11 | 11 | def magic_history(self, parameter_s = ''): |
|
12 | 12 | """Print input history (_i<n> variables), with most recent last. |
|
13 | 13 | |
|
14 | 14 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
15 | 15 | %history n -> print at most n inputs\\ |
|
16 | 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 | |
|
26 | printout of many lines which can be directly pasted into a text | |
|
27 | editor. | |
|
21 | With -n, each input's number <n> is shown, and is accessible as the | |
|
22 | automatically generated variable _i<n> as well as In[<n>]. Multi-line | |
|
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 | 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 | 36 | -t: (default) print the 'translated' history, as IPython understands it. |
|
32 | 37 | IPython filters your input and converts it all into valid Python source |
|
33 | 38 | before executing it (things like magics or aliases are turned into |
|
34 | 39 | function calls, for example). With this option, you'll see the native |
|
35 | 40 | history instead of the user-entered version: '%cd /' will be seen as |
|
36 | 41 | '_ip.magic("%cd /")' instead of '%cd /'. |
|
37 | 42 | |
|
38 | 43 | -r: print the 'raw' history, i.e. the actual commands you typed. |
|
39 | 44 | |
|
40 | 45 | -g: treat the arg as a pattern to grep for in (full) history. |
|
41 | 46 | This includes the "shadow history" (almost all commands ever written). |
|
42 | 47 | Use '%hist -g' to show full shadow history (may be very long). |
|
43 | 48 | In shadow history, every index nuwber starts with 0. |
|
44 | 49 | |
|
45 | 50 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
46 | 51 | the given file. The file is always overwritten, though IPython asks for |
|
47 | 52 | confirmation first if it already exists. |
|
48 | 53 | """ |
|
49 | 54 | |
|
50 | 55 | if not self.outputcache.do_full_cache: |
|
51 | 56 | print 'This feature is only available if numbered prompts are in use.' |
|
52 | 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 | 60 | # Check if output to specific file was requested. |
|
56 | 61 | try: |
|
57 | 62 | outfname = opts['f'] |
|
58 | 63 | except KeyError: |
|
59 | 64 | outfile = Term.cout # default |
|
60 | 65 | # We don't want to close stdout at the end! |
|
61 | 66 | close_at_end = False |
|
62 | 67 | else: |
|
63 | 68 | if os.path.exists(outfname): |
|
64 | 69 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): |
|
65 | 70 | print 'Aborting.' |
|
66 | 71 | return |
|
67 | 72 | |
|
68 | 73 | outfile = open(outfname,'w') |
|
69 | 74 | close_at_end = True |
|
70 | 75 | |
|
71 | 76 | if 't' in opts: |
|
72 | 77 | input_hist = self.input_hist |
|
73 | 78 | elif 'r' in opts: |
|
74 | 79 | input_hist = self.input_hist_raw |
|
75 | 80 | else: |
|
76 | 81 | input_hist = self.input_hist |
|
77 | 82 | |
|
78 | 83 | default_length = 40 |
|
79 | 84 | pattern = None |
|
80 | 85 | if 'g' in opts: |
|
81 | 86 | init = 1 |
|
82 | 87 | final = len(input_hist) |
|
83 | 88 | parts = parameter_s.split(None,1) |
|
84 | 89 | if len(parts) == 1: |
|
85 | 90 | parts += '*' |
|
86 | 91 | head, pattern = parts |
|
87 | 92 | pattern = "*" + pattern + "*" |
|
88 | 93 | elif len(args) == 0: |
|
89 | 94 | final = len(input_hist) |
|
90 | 95 | init = max(1,final-default_length) |
|
91 | 96 | elif len(args) == 1: |
|
92 | 97 | final = len(input_hist) |
|
93 | 98 | init = max(1,final-int(args[0])) |
|
94 | 99 | elif len(args) == 2: |
|
95 | 100 | init,final = map(int,args) |
|
96 | 101 | else: |
|
97 | 102 | warn('%hist takes 0, 1 or 2 arguments separated by spaces.') |
|
98 | 103 | print self.magic_hist.__doc__ |
|
99 | 104 | return |
|
105 | ||
|
100 | 106 | width = len(str(final)) |
|
101 | 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 | 112 | found = False |
|
105 | 113 | if pattern is not None: |
|
106 | 114 | sh = self.shadowhist.all() |
|
107 | 115 | for idx, s in sh: |
|
108 | 116 | if fnmatch.fnmatch(s, pattern): |
|
109 | 117 | print "0%d: %s" %(idx, s) |
|
110 | 118 | found = True |
|
111 | 119 | |
|
112 | 120 | if found: |
|
113 | 121 | print "===" |
|
114 | 122 | print "shadow history ends, fetch by %rep <number> (must start with 0)" |
|
115 | 123 | print "=== start of normal history ===" |
|
116 | 124 | |
|
117 | 125 | for in_num in range(init,final): |
|
118 | 126 | inline = input_hist[in_num] |
|
119 | 127 | if pattern is not None and not fnmatch.fnmatch(inline, pattern): |
|
120 | 128 | continue |
|
121 | 129 | |
|
122 | 130 | multiline = int(inline.count('\n') > 1) |
|
123 | 131 | if print_nums: |
|
124 | 132 | print >> outfile, \ |
|
125 | 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 | 148 | if close_at_end: |
|
129 | 149 | outfile.close() |
|
130 | 150 | |
|
131 | 151 | |
|
132 | 152 | def magic_hist(self, parameter_s=''): |
|
133 | 153 | """Alternate name for %history.""" |
|
134 | 154 | return self.magic_history(parameter_s) |
|
135 | 155 | |
|
136 | 156 | |
|
137 | 157 | def rep_f(self, arg): |
|
138 | 158 | r""" Repeat a command, or get command to input line for editing |
|
139 | 159 | |
|
140 | 160 | - %rep (no arguments): |
|
141 | 161 | |
|
142 | 162 | Place a string version of last computation result (stored in the special '_' |
|
143 | 163 | variable) to the next input prompt. Allows you to create elaborate command |
|
144 | 164 | lines without using copy-paste:: |
|
145 | 165 | |
|
146 | 166 | $ l = ["hei", "vaan"] |
|
147 | 167 | $ "".join(l) |
|
148 | 168 | ==> heivaan |
|
149 | 169 | $ %rep |
|
150 | 170 | $ heivaan_ <== cursor blinking |
|
151 | 171 | |
|
152 | 172 | %rep 45 |
|
153 | 173 | |
|
154 | 174 | Place history line 45 to next input prompt. Use %hist to find out the |
|
155 | 175 | number. |
|
156 | 176 | |
|
157 | 177 | %rep 1-4 6-7 3 |
|
158 | 178 | |
|
159 | 179 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
160 | 180 | in %macro and %save. |
|
161 | 181 | |
|
162 | 182 | %rep foo |
|
163 | 183 | |
|
164 | 184 | Place the most recent line that has the substring "foo" to next input. |
|
165 | 185 | (e.g. 'svn ci -m foobar'). |
|
166 | 186 | """ |
|
167 | 187 | |
|
168 | 188 | opts,args = self.parse_options(arg,'',mode='list') |
|
169 | 189 | if not args: |
|
170 | 190 | self.set_next_input(str(self.user_ns["_"])) |
|
171 | 191 | return |
|
172 | 192 | |
|
173 | 193 | if len(args) == 1 and not '-' in args[0]: |
|
174 | 194 | arg = args[0] |
|
175 | 195 | if len(arg) > 1 and arg.startswith('0'): |
|
176 | 196 | # get from shadow hist |
|
177 | 197 | num = int(arg[1:]) |
|
178 | 198 | line = self.shadowhist.get(num) |
|
179 | 199 | self.set_next_input(str(line)) |
|
180 | 200 | return |
|
181 | 201 | try: |
|
182 | 202 | num = int(args[0]) |
|
183 | 203 | self.set_next_input(str(self.input_hist_raw[num]).rstrip()) |
|
184 | 204 | return |
|
185 | 205 | except ValueError: |
|
186 | 206 | pass |
|
187 | 207 | |
|
188 | 208 | for h in reversed(self.input_hist_raw): |
|
189 | 209 | if 'rep' in h: |
|
190 | 210 | continue |
|
191 | 211 | if fnmatch.fnmatch(h,'*' + arg + '*'): |
|
192 | 212 | self.set_next_input(str(h).rstrip()) |
|
193 | 213 | return |
|
194 | 214 | |
|
195 | 215 | try: |
|
196 | 216 | lines = self.extract_input_slices(args, True) |
|
197 | 217 | print "lines",lines |
|
198 | 218 | self.runlines(lines) |
|
199 | 219 | except ValueError: |
|
200 | 220 | print "Not found in recent history:", args |
|
201 | 221 | |
|
202 | 222 | |
|
203 | 223 | _sentinel = object() |
|
204 | 224 | |
|
205 | 225 | class ShadowHist(object): |
|
206 | 226 | def __init__(self,db): |
|
207 | 227 | # cmd => idx mapping |
|
208 | 228 | self.curidx = 0 |
|
209 | 229 | self.db = db |
|
210 | 230 | self.disabled = False |
|
211 | 231 | |
|
212 | 232 | def inc_idx(self): |
|
213 | 233 | idx = self.db.get('shadowhist_idx', 1) |
|
214 | 234 | self.db['shadowhist_idx'] = idx + 1 |
|
215 | 235 | return idx |
|
216 | 236 | |
|
217 | 237 | def add(self, ent): |
|
218 | 238 | if self.disabled: |
|
219 | 239 | return |
|
220 | 240 | try: |
|
221 | 241 | old = self.db.hget('shadowhist', ent, _sentinel) |
|
222 | 242 | if old is not _sentinel: |
|
223 | 243 | return |
|
224 | 244 | newidx = self.inc_idx() |
|
225 | 245 | #print "new",newidx # dbg |
|
226 | 246 | self.db.hset('shadowhist',ent, newidx) |
|
227 | 247 | except: |
|
228 | 248 | ipapi.get().showtraceback() |
|
229 | 249 | print "WARNING: disabling shadow history" |
|
230 | 250 | self.disabled = True |
|
231 | 251 | |
|
232 | 252 | def all(self): |
|
233 | 253 | d = self.db.hdict('shadowhist') |
|
234 | 254 | items = [(i,s) for (s,i) in d.items()] |
|
235 | 255 | items.sort() |
|
236 | 256 | return items |
|
237 | 257 | |
|
238 | 258 | def get(self, idx): |
|
239 | 259 | all = self.all() |
|
240 | 260 | |
|
241 | 261 | for k, v in all: |
|
242 | 262 | #print k,v |
|
243 | 263 | if k == idx: |
|
244 | 264 | return v |
|
245 | 265 | |
|
246 | 266 | |
|
247 | 267 | def init_ipython(ip): |
|
248 | import ipy_completers | |
|
249 | ||
|
250 | 268 | ip.define_magic("rep",rep_f) |
|
251 | 269 | ip.define_magic("hist",magic_hist) |
|
252 | 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 | 1 | """hooks for IPython. |
|
2 | 2 | |
|
3 | 3 | In Python, it is possible to overwrite any method of any object if you really |
|
4 | 4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
5 | 5 | be overwritten by users for customization purposes. This module defines the |
|
6 | 6 | default versions of all such hooks, which get used by IPython if not |
|
7 | 7 | overridden by the user. |
|
8 | 8 | |
|
9 | 9 | hooks are simple functions, but they should be declared with 'self' as their |
|
10 | 10 | first argument, because when activated they are registered into IPython as |
|
11 | 11 | instance methods. The self argument will be the IPython running instance |
|
12 | 12 | itself, so hooks have full access to the entire IPython object. |
|
13 | 13 | |
|
14 | 14 | If you wish to define a new hook and activate it, you need to put the |
|
15 | 15 | necessary code into a python file which can be either imported or execfile()'d |
|
16 | 16 | from within your ipythonrc configuration. |
|
17 | 17 | |
|
18 | 18 | For example, suppose that you have a module called 'myiphooks' in your |
|
19 | 19 | PYTHONPATH, which contains the following definition: |
|
20 | 20 | |
|
21 | 21 | import os |
|
22 | 22 | from IPython.core import ipapi |
|
23 | 23 | ip = ipapi.get() |
|
24 | 24 | |
|
25 | 25 | def calljed(self,filename, linenum): |
|
26 | 26 | "My editor hook calls the jed editor directly." |
|
27 | 27 | print "Calling my own editor, jed ..." |
|
28 | 28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
29 | 29 | raise TryNext() |
|
30 | 30 | |
|
31 | 31 | ip.set_hook('editor', calljed) |
|
32 | 32 | |
|
33 | 33 | You can then enable the functionality by doing 'import myiphooks' |
|
34 | 34 | somewhere in your configuration files or ipython command line. |
|
35 | 35 | """ |
|
36 | 36 | |
|
37 | 37 | #***************************************************************************** |
|
38 | 38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
39 | 39 | # |
|
40 | 40 | # Distributed under the terms of the BSD License. The full license is in |
|
41 | 41 | # the file COPYING, distributed as part of this software. |
|
42 | 42 | #***************************************************************************** |
|
43 | 43 | |
|
44 | 44 | import os, bisect |
|
45 | 45 | import sys |
|
46 | 46 | from IPython.utils.genutils import Term, shell |
|
47 | 47 | from pprint import PrettyPrinter |
|
48 | 48 | |
|
49 | 49 | from IPython.core.error import TryNext |
|
50 | 50 | |
|
51 | 51 | # List here all the default hooks. For now it's just the editor functions |
|
52 | 52 | # but over time we'll move here all the public API for user-accessible things. |
|
53 | 53 | |
|
54 | 54 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', 'result_display', |
|
55 | 55 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
56 | 56 | 'generate_prompt', 'generate_output_prompt','shell_hook', |
|
57 | 57 | 'show_in_pager','pre_prompt_hook', 'pre_runcode_hook', |
|
58 | 58 | 'clipboard_get'] |
|
59 | 59 | |
|
60 | 60 | pformat = PrettyPrinter().pformat |
|
61 | 61 | |
|
62 | 62 | def editor(self,filename, linenum=None): |
|
63 | 63 | """Open the default editor at the given filename and linenumber. |
|
64 | 64 | |
|
65 | 65 | This is IPython's default editor hook, you can use it as an example to |
|
66 | 66 | write your own modified one. To set your own editor function as the |
|
67 | 67 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
68 | 68 | |
|
69 | 69 | # IPython configures a default editor at startup by reading $EDITOR from |
|
70 | 70 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
71 | 71 | editor = self.editor |
|
72 | 72 | |
|
73 | 73 | # marker for at which line to open the file (for existing objects) |
|
74 | 74 | if linenum is None or editor=='notepad': |
|
75 | 75 | linemark = '' |
|
76 | 76 | else: |
|
77 | 77 | linemark = '+%d' % int(linenum) |
|
78 | 78 | |
|
79 | 79 | # Enclose in quotes if necessary and legal |
|
80 | 80 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
81 | 81 | editor = '"%s"' % editor |
|
82 | 82 | |
|
83 | 83 | # Call the actual editor |
|
84 | 84 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
85 | 85 | raise TryNext() |
|
86 | 86 | |
|
87 | 87 | import tempfile |
|
88 | 88 | def fix_error_editor(self,filename,linenum,column,msg): |
|
89 | 89 | """Open the editor at the given filename, linenumber, column and |
|
90 | 90 | show an error message. This is used for correcting syntax errors. |
|
91 | 91 | The current implementation only has special support for the VIM editor, |
|
92 | 92 | and falls back on the 'editor' hook if VIM is not used. |
|
93 | 93 | |
|
94 | 94 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
95 | 95 | """ |
|
96 | 96 | def vim_quickfix_file(): |
|
97 | 97 | t = tempfile.NamedTemporaryFile() |
|
98 | 98 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
99 | 99 | t.flush() |
|
100 | 100 | return t |
|
101 | 101 | if os.path.basename(self.editor) != 'vim': |
|
102 | 102 | self.hooks.editor(filename,linenum) |
|
103 | 103 | return |
|
104 | 104 | t = vim_quickfix_file() |
|
105 | 105 | try: |
|
106 | 106 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
107 | 107 | raise TryNext() |
|
108 | 108 | finally: |
|
109 | 109 | t.close() |
|
110 | 110 | |
|
111 | 111 | |
|
112 | 112 | def synchronize_with_editor(self, filename, linenum, column): |
|
113 | 113 | pass |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | class CommandChainDispatcher: |
|
117 | 117 | """ Dispatch calls to a chain of commands until some func can handle it |
|
118 | 118 | |
|
119 | 119 | Usage: instantiate, execute "add" to add commands (with optional |
|
120 | 120 | priority), execute normally via f() calling mechanism. |
|
121 | 121 | |
|
122 | 122 | """ |
|
123 | 123 | def __init__(self,commands=None): |
|
124 | 124 | if commands is None: |
|
125 | 125 | self.chain = [] |
|
126 | 126 | else: |
|
127 | 127 | self.chain = commands |
|
128 | 128 | |
|
129 | 129 | |
|
130 | 130 | def __call__(self,*args, **kw): |
|
131 | 131 | """ Command chain is called just like normal func. |
|
132 | 132 | |
|
133 | 133 | This will call all funcs in chain with the same args as were given to this |
|
134 | 134 | function, and return the result of first func that didn't raise |
|
135 | 135 | TryNext """ |
|
136 | 136 | |
|
137 | 137 | for prio,cmd in self.chain: |
|
138 | 138 | #print "prio",prio,"cmd",cmd #dbg |
|
139 | 139 | try: |
|
140 |
ret |
|
|
141 | return ret | |
|
140 | return cmd(*args, **kw) | |
|
142 | 141 | except TryNext, exc: |
|
143 | 142 | if exc.args or exc.kwargs: |
|
144 | 143 | args = exc.args |
|
145 | 144 | kw = exc.kwargs |
|
146 | 145 | # if no function will accept it, raise TryNext up to the caller |
|
147 | 146 | raise TryNext |
|
148 | 147 | |
|
149 | 148 | def __str__(self): |
|
150 | 149 | return str(self.chain) |
|
151 | 150 | |
|
152 | 151 | def add(self, func, priority=0): |
|
153 | 152 | """ Add a func to the cmd chain with given priority """ |
|
154 | 153 | bisect.insort(self.chain,(priority,func)) |
|
155 | 154 | |
|
156 | 155 | def __iter__(self): |
|
157 | 156 | """ Return all objects in chain. |
|
158 | 157 | |
|
159 | 158 | Handy if the objects are not callable. |
|
160 | 159 | """ |
|
161 | 160 | return iter(self.chain) |
|
162 | 161 | |
|
163 | 162 | |
|
164 | 163 | def result_display(self,arg): |
|
165 | 164 | """ Default display hook. |
|
166 | 165 | |
|
167 | 166 | Called for displaying the result to the user. |
|
168 | 167 | """ |
|
169 | 168 | |
|
170 | 169 | if self.pprint: |
|
171 | 170 | out = pformat(arg) |
|
172 | 171 | if '\n' in out: |
|
173 | 172 | # So that multi-line strings line up with the left column of |
|
174 | 173 | # the screen, instead of having the output prompt mess up |
|
175 | 174 | # their first line. |
|
176 | 175 | Term.cout.write('\n') |
|
177 | 176 | print >>Term.cout, out |
|
178 | 177 | else: |
|
179 | 178 | # By default, the interactive prompt uses repr() to display results, |
|
180 | 179 | # so we should honor this. Users who'd rather use a different |
|
181 | 180 | # mechanism can easily override this hook. |
|
182 | 181 | print >>Term.cout, repr(arg) |
|
183 | 182 | # the default display hook doesn't manipulate the value to put in history |
|
184 | 183 | return None |
|
185 | 184 | |
|
186 | 185 | |
|
187 | 186 | def input_prefilter(self,line): |
|
188 | 187 | """ Default input prefilter |
|
189 | 188 | |
|
190 | 189 | This returns the line as unchanged, so that the interpreter |
|
191 | 190 | knows that nothing was done and proceeds with "classic" prefiltering |
|
192 | 191 | (%magics, !shell commands etc.). |
|
193 | 192 | |
|
194 | 193 | Note that leading whitespace is not passed to this hook. Prefilter |
|
195 | 194 | can't alter indentation. |
|
196 | 195 | |
|
197 | 196 | """ |
|
198 | 197 | #print "attempt to rewrite",line #dbg |
|
199 | 198 | return line |
|
200 | 199 | |
|
201 | 200 | |
|
202 | 201 | def shutdown_hook(self): |
|
203 | 202 | """ default shutdown hook |
|
204 | 203 | |
|
205 | 204 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
206 | 205 | """ |
|
207 | 206 | |
|
208 | 207 | #print "default shutdown hook ok" # dbg |
|
209 | 208 | return |
|
210 | 209 | |
|
211 | 210 | |
|
212 | 211 | def late_startup_hook(self): |
|
213 | 212 | """ Executed after ipython has been constructed and configured |
|
214 | 213 | |
|
215 | 214 | """ |
|
216 | 215 | #print "default startup hook ok" # dbg |
|
217 | 216 | |
|
218 | 217 | |
|
219 | 218 | def generate_prompt(self, is_continuation): |
|
220 | 219 | """ calculate and return a string with the prompt to display """ |
|
221 | 220 | if is_continuation: |
|
222 | 221 | return str(self.outputcache.prompt2) |
|
223 | 222 | return str(self.outputcache.prompt1) |
|
224 | 223 | |
|
225 | 224 | |
|
226 | 225 | def generate_output_prompt(self): |
|
227 | 226 | return str(self.outputcache.prompt_out) |
|
228 | 227 | |
|
229 | 228 | |
|
230 | 229 | def shell_hook(self,cmd): |
|
231 | 230 | """ Run system/shell command a'la os.system() """ |
|
232 | 231 | |
|
233 | 232 | shell(cmd, header=self.system_header, verbose=self.system_verbose) |
|
234 | 233 | |
|
235 | 234 | |
|
236 | 235 | def show_in_pager(self,s): |
|
237 | 236 | """ Run a string through pager """ |
|
238 | 237 | # raising TryNext here will use the default paging functionality |
|
239 | 238 | raise TryNext |
|
240 | 239 | |
|
241 | 240 | |
|
242 | 241 | def pre_prompt_hook(self): |
|
243 | 242 | """ Run before displaying the next prompt |
|
244 | 243 | |
|
245 | 244 | Use this e.g. to display output from asynchronous operations (in order |
|
246 | 245 | to not mess up text entry) |
|
247 | 246 | """ |
|
248 | 247 | |
|
249 | 248 | return None |
|
250 | 249 | |
|
251 | 250 | |
|
252 | 251 | def pre_runcode_hook(self): |
|
253 | 252 | """ Executed before running the (prefiltered) code in IPython """ |
|
254 | 253 | return None |
|
255 | 254 | |
|
256 | 255 | |
|
257 | 256 | def clipboard_get(self): |
|
258 | 257 | """ Get text from the clipboard. |
|
259 | 258 | """ |
|
260 | 259 | from IPython.lib.clipboard import ( |
|
261 | 260 | osx_clipboard_get, tkinter_clipboard_get, |
|
262 | 261 | win32_clipboard_get |
|
263 | 262 | ) |
|
264 | 263 | if sys.platform == 'win32': |
|
265 | 264 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
266 | 265 | elif sys.platform == 'darwin': |
|
267 | 266 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
268 | 267 | else: |
|
269 | 268 | chain = [tkinter_clipboard_get] |
|
270 | 269 | dispatcher = CommandChainDispatcher() |
|
271 | 270 | for func in chain: |
|
272 | 271 | dispatcher.add(func) |
|
273 | 272 | text = dispatcher() |
|
274 | 273 | return text |
@@ -1,35 +1,38 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | This module is *completely* deprecated and should no longer be used for |
|
5 | 5 | any purpose. Currently, we have a few parts of the core that have |
|
6 | 6 | not been componentized and thus, still rely on this module. When everything |
|
7 | 7 | has been made into a component, this module will be sent to deathrow. |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Copyright (C) 2008-2009 The IPython Development Team |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 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 | 24 | # Classes and functions |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | ||
|
27 | 28 | def get(): |
|
28 | 29 | """Get the most recently created InteractiveShell instance.""" |
|
29 | 30 | from IPython.core.iplib import InteractiveShell |
|
30 | 31 | insts = InteractiveShell.get_instances() |
|
32 | if len(insts)==0: | |
|
33 | return None | |
|
31 | 34 | most_recent = insts[0] |
|
32 | 35 | for inst in insts[1:]: |
|
33 | 36 | if inst.created > most_recent.created: |
|
34 | 37 | most_recent = inst |
|
35 | 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 | 1 | #!/usr/bin/env python |
|
2 | 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 | 10 | * Brian Granger |
|
9 | 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 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 18 | # the file COPYING, distributed as part of this software. |
|
20 | 19 | #----------------------------------------------------------------------------- |
|
21 | 20 | |
|
22 | 21 | #----------------------------------------------------------------------------- |
|
23 | 22 | # Imports |
|
24 | 23 | #----------------------------------------------------------------------------- |
|
24 | from __future__ import absolute_import | |
|
25 | 25 | |
|
26 | 26 | import logging |
|
27 | 27 | import os |
|
28 | 28 | import sys |
|
29 | import warnings | |
|
30 | 29 | |
|
31 | from IPython.core.application import Application, IPythonArgParseConfigLoader | |
|
32 |
from IPython.core import |
|
|
30 | from IPython.core import crashhandler | |
|
31 | from IPython.core.application import Application | |
|
33 | 32 | from IPython.core.iplib import InteractiveShell |
|
34 | 33 | from IPython.config.loader import ( |
|
35 | NoConfigDefault, | |
|
36 | 34 | Config, |
|
37 |
Config |
|
|
38 | PyFileConfigLoader | |
|
35 | PyFileConfigLoader, | |
|
36 | # NoConfigDefault, | |
|
39 | 37 | ) |
|
40 | ||
|
41 | 38 | from IPython.lib import inputhook |
|
42 | ||
|
43 | from IPython.utils.ipstruct import Struct | |
|
44 | 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 | ||
|
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 | #----------------------------------------------------------------------------- | |
|
46 | default_config_file_name = u'ipython_config.py' | |
|
81 | 47 | |
|
82 | 48 | cl_args = ( |
|
83 | (('-autocall',), dict( | |
|
84 |
type=int, dest='InteractiveShell.autocall', |
|
|
85 | help='Set the autocall value (0,1,2).', | |
|
49 | (('--autocall',), dict( | |
|
50 | type=int, dest='InteractiveShell.autocall', | |
|
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 | 59 | metavar='InteractiveShell.autocall') |
|
87 | 60 | ), |
|
88 | (('-autoindent',), dict( | |
|
89 |
action='store_true', dest='InteractiveShell.autoindent', |
|
|
61 | (('--autoindent',), dict( | |
|
62 | action='store_true', dest='InteractiveShell.autoindent', | |
|
90 | 63 | help='Turn on autoindenting.') |
|
91 | 64 | ), |
|
92 | (('-noautoindent',), dict( | |
|
93 |
action='store_false', dest='InteractiveShell.autoindent', |
|
|
65 | (('--no-autoindent',), dict( | |
|
66 | action='store_false', dest='InteractiveShell.autoindent', | |
|
94 | 67 | help='Turn off autoindenting.') |
|
95 | 68 | ), |
|
96 | (('-automagic',), dict( | |
|
97 |
action='store_true', dest='InteractiveShell.automagic', |
|
|
98 |
help='Turn on the auto calling of magic commands.' |
|
|
99 | ), | |
|
100 | (('-noautomagic',), dict( | |
|
101 | action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault, | |
|
69 | (('--automagic',), dict( | |
|
70 | action='store_true', dest='InteractiveShell.automagic', | |
|
71 | help='Turn on the auto calling of magic commands.' | |
|
72 | 'Type %%magic at the IPython prompt for more information.') | |
|
73 | ), | |
|
74 | (('--no-automagic',), dict( | |
|
75 | action='store_false', dest='InteractiveShell.automagic', | |
|
102 | 76 | help='Turn off the auto calling of magic commands.') |
|
103 | 77 | ), |
|
104 |
(('-autoedit |
|
|
105 |
action='store_true', dest='InteractiveShell.autoedit_syntax', |
|
|
78 | (('--autoedit-syntax',), dict( | |
|
79 | action='store_true', dest='InteractiveShell.autoedit_syntax', | |
|
106 | 80 | help='Turn on auto editing of files with syntax errors.') |
|
107 | 81 | ), |
|
108 |
(('-noautoedit |
|
|
109 |
action='store_false', dest='InteractiveShell.autoedit_syntax', |
|
|
82 | (('--no-autoedit-syntax',), dict( | |
|
83 | action='store_false', dest='InteractiveShell.autoedit_syntax', | |
|
110 | 84 | help='Turn off auto editing of files with syntax errors.') |
|
111 | 85 | ), |
|
112 | (('-banner',), dict( | |
|
113 |
action='store_true', dest='Global.display_banner', |
|
|
86 | (('--banner',), dict( | |
|
87 | action='store_true', dest='Global.display_banner', | |
|
114 | 88 | help='Display a banner upon starting IPython.') |
|
115 | 89 | ), |
|
116 | (('-nobanner',), dict( | |
|
117 |
action='store_false', dest='Global.display_banner', |
|
|
90 | (('--no-banner',), dict( | |
|
91 | action='store_false', dest='Global.display_banner', | |
|
118 | 92 | help="Don't display a banner upon starting IPython.") |
|
119 | 93 | ), |
|
120 |
(('-cache |
|
|
121 |
type=int, dest='InteractiveShell.cache_size', |
|
|
122 | help="Set the size of the output cache.", | |
|
94 | (('--cache-size',), dict( | |
|
95 | type=int, dest='InteractiveShell.cache_size', | |
|
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 | 104 | metavar='InteractiveShell.cache_size') |
|
124 | 105 | ), |
|
125 | (('-classic',), dict( | |
|
126 |
action='store_true', dest='Global.classic', |
|
|
106 | (('--classic',), dict( | |
|
107 | action='store_true', dest='Global.classic', | |
|
127 | 108 | help="Gives IPython a similar feel to the classic Python prompt.") |
|
128 | 109 | ), |
|
129 | (('-colors',), dict( | |
|
130 |
type=str, dest='InteractiveShell.colors', |
|
|
110 | (('--colors',), dict( | |
|
111 | type=str, dest='InteractiveShell.colors', | |
|
131 | 112 | help="Set the color scheme (NoColor, Linux, and LightBG).", |
|
132 | 113 | metavar='InteractiveShell.colors') |
|
133 | 114 | ), |
|
134 |
(('-color |
|
|
135 |
action='store_true', dest='InteractiveShell.color_info', |
|
|
136 | help="Enable using colors for info related things.") | |
|
115 | (('--color-info',), dict( | |
|
116 | action='store_true', dest='InteractiveShell.color_info', | |
|
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 |
(('- |
|
|
139 |
action='store_false', dest='InteractiveShell.color_info', |
|
|
129 | (('--no-color-info',), dict( | |
|
130 | action='store_false', dest='InteractiveShell.color_info', | |
|
140 | 131 | help="Disable using colors for info related things.") |
|
141 | 132 | ), |
|
142 |
(('-confirm |
|
|
143 |
action='store_true', dest='InteractiveShell.confirm_exit', |
|
|
144 | help="Prompt the user when existing.") | |
|
145 | ), | |
|
146 | (('-noconfirm_exit',), dict( | |
|
147 | action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault, | |
|
148 | help="Don't prompt the user when existing.") | |
|
149 |
) |
|
|
150 | (('-deep_reload',), dict( | |
|
151 | action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault, | |
|
152 | help="Enable deep (recursive) reloading by default.") | |
|
133 | (('--confirm-exit',), dict( | |
|
134 | action='store_true', dest='InteractiveShell.confirm_exit', | |
|
135 | help= | |
|
136 | """Set to confirm when you try to exit IPython with an EOF (Control-D | |
|
137 | in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or | |
|
138 | '%%Exit', you can force a direct exit without any confirmation. | |
|
139 | """ | |
|
140 | ) | |
|
153 | 141 | ), |
|
154 |
(('- |
|
|
155 |
action='store_false', dest='InteractiveShell. |
|
|
142 | (('--no-confirm-exit',), dict( | |
|
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 | 161 | help="Disable deep (recursive) reloading by default.") |
|
157 | 162 | ), |
|
158 | (('-editor',), dict( | |
|
159 |
type=str, dest='InteractiveShell.editor', |
|
|
163 | (('--editor',), dict( | |
|
164 | type=str, dest='InteractiveShell.editor', | |
|
160 | 165 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad).", |
|
161 | 166 | metavar='InteractiveShell.editor') |
|
162 | 167 | ), |
|
163 | (('-log','-l'), dict( | |
|
164 |
action='store_true', dest='InteractiveShell.logstart', |
|
|
165 | help="Start logging to the default file (./ipython_log.py).") | |
|
168 | (('--log','-l'), dict( | |
|
169 | action='store_true', dest='InteractiveShell.logstart', | |
|
170 | help="Start logging to the default log file (./ipython_log.py).") | |
|
166 | 171 | ), |
|
167 | (('-logfile','-lf'), dict( | |
|
168 |
type= |
|
|
169 | help="Start logging to logfile.", | |
|
172 | (('--logfile','-lf'), dict( | |
|
173 | type=unicode, dest='InteractiveShell.logfile', | |
|
174 | help="Start logging to logfile with this name.", | |
|
170 | 175 | metavar='InteractiveShell.logfile') |
|
171 | 176 | ), |
|
172 | (('-logappend','-la'), dict( | |
|
173 |
type= |
|
|
174 |
help="Start logging to |
|
|
177 | (('--log-append','-la'), dict( | |
|
178 | type=unicode, dest='InteractiveShell.logappend', | |
|
179 | help="Start logging to the given file in append mode.", | |
|
175 | 180 | metavar='InteractiveShell.logfile') |
|
176 | 181 | ), |
|
177 | (('-pdb',), dict( | |
|
178 |
action='store_true', dest='InteractiveShell.pdb', |
|
|
182 | (('--pdb',), dict( | |
|
183 | action='store_true', dest='InteractiveShell.pdb', | |
|
179 | 184 | help="Enable auto calling the pdb debugger after every exception.") |
|
180 | 185 | ), |
|
181 | (('-nopdb',), dict( | |
|
182 |
action='store_false', dest='InteractiveShell.pdb', |
|
|
186 | (('--no-pdb',), dict( | |
|
187 | action='store_false', dest='InteractiveShell.pdb', | |
|
183 | 188 | help="Disable auto calling the pdb debugger after every exception.") |
|
184 | 189 | ), |
|
185 | (('-pprint',), dict( | |
|
186 |
action='store_true', dest='InteractiveShell.pprint', |
|
|
190 | (('--pprint',), dict( | |
|
191 | action='store_true', dest='InteractiveShell.pprint', | |
|
187 | 192 | help="Enable auto pretty printing of results.") |
|
188 | 193 | ), |
|
189 | (('-nopprint',), dict( | |
|
190 |
action='store_false', dest='InteractiveShell.pprint', |
|
|
194 | (('--no-pprint',), dict( | |
|
195 | action='store_false', dest='InteractiveShell.pprint', | |
|
191 | 196 | help="Disable auto auto pretty printing of results.") |
|
192 | 197 | ), |
|
193 |
(('-prompt |
|
|
194 |
type=str, dest='InteractiveShell.prompt_in1', |
|
|
195 | help="Set the main input prompt ('In [\#]: ')", | |
|
198 | (('--prompt-in1','-pi1'), dict( | |
|
199 | type=str, dest='InteractiveShell.prompt_in1', | |
|
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 | 208 | metavar='InteractiveShell.prompt_in1') |
|
197 | 209 | ), |
|
198 |
(('-prompt |
|
|
199 |
type=str, dest='InteractiveShell.prompt_in2', |
|
|
200 | help="Set the secondary input prompt (' .\D.: ')", | |
|
210 | (('--prompt-in2','-pi2'), dict( | |
|
211 | type=str, dest='InteractiveShell.prompt_in2', | |
|
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 | 219 | metavar='InteractiveShell.prompt_in2') |
|
202 | 220 | ), |
|
203 |
(('-prompt |
|
|
204 |
type=str, dest='InteractiveShell.prompt_out', |
|
|
221 | (('--prompt-out','-po'), dict( | |
|
222 | type=str, dest='InteractiveShell.prompt_out', | |
|
205 | 223 | help="Set the output prompt ('Out[\#]:')", |
|
206 | 224 | metavar='InteractiveShell.prompt_out') |
|
207 | 225 | ), |
|
208 | (('-quick',), dict( | |
|
209 |
action='store_true', dest='Global.quick', |
|
|
226 | (('--quick',), dict( | |
|
227 | action='store_true', dest='Global.quick', | |
|
210 | 228 | help="Enable quick startup with no config files.") |
|
211 | 229 | ), |
|
212 | (('-readline',), dict( | |
|
213 |
action='store_true', dest='InteractiveShell.readline_use', |
|
|
230 | (('--readline',), dict( | |
|
231 | action='store_true', dest='InteractiveShell.readline_use', | |
|
214 | 232 | help="Enable readline for command line usage.") |
|
215 | 233 | ), |
|
216 | (('-noreadline',), dict( | |
|
217 |
action='store_false', dest='InteractiveShell.readline_use', |
|
|
234 | (('--no-readline',), dict( | |
|
235 | action='store_false', dest='InteractiveShell.readline_use', | |
|
218 | 236 | help="Disable readline for command line usage.") |
|
219 | 237 | ), |
|
220 |
(('-screen |
|
|
221 |
type=int, dest='InteractiveShell.screen_length', |
|
|
222 | help='Number of lines on screen, used to control printing of long strings.', | |
|
238 | (('--screen-length','-sl'), dict( | |
|
239 | type=int, dest='InteractiveShell.screen_length', | |
|
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 | 250 | metavar='InteractiveShell.screen_length') |
|
224 | 251 | ), |
|
225 |
(('-separate |
|
|
226 |
type=str, dest='InteractiveShell.separate_in', |
|
|
227 | help="Separator before input prompts. Default '\n'.", | |
|
252 | (('--separate-in','-si'), dict( | |
|
253 | type=str, dest='InteractiveShell.separate_in', | |
|
254 | help="Separator before input prompts. Default '\\n'.", | |
|
228 | 255 | metavar='InteractiveShell.separate_in') |
|
229 | 256 | ), |
|
230 |
(('-separate |
|
|
231 |
type=str, dest='InteractiveShell.separate_out', |
|
|
257 | (('--separate-out','-so'), dict( | |
|
258 | type=str, dest='InteractiveShell.separate_out', | |
|
232 | 259 | help="Separator before output prompts. Default 0 (nothing).", |
|
233 | 260 | metavar='InteractiveShell.separate_out') |
|
234 | 261 | ), |
|
235 |
(('-separate |
|
|
236 |
type=str, dest='InteractiveShell.separate_out2', |
|
|
262 | (('--separate-out2','-so2'), dict( | |
|
263 | type=str, dest='InteractiveShell.separate_out2', | |
|
237 | 264 | help="Separator after output prompts. Default 0 (nonight).", |
|
238 | 265 | metavar='InteractiveShell.separate_out2') |
|
239 | 266 | ), |
|
240 | (('-nosep',), dict( | |
|
241 |
action='store_true', dest='Global.nosep', |
|
|
267 | (('-no-sep',), dict( | |
|
268 | action='store_true', dest='Global.nosep', | |
|
242 | 269 | help="Eliminate all spacing between prompts.") |
|
243 | 270 | ), |
|
244 |
(('- |
|
|
245 |
action='store_true', dest='InteractiveShell.term_title', |
|
|
271 | (('--term-title',), dict( | |
|
272 | action='store_true', dest='InteractiveShell.term_title', | |
|
246 | 273 | help="Enable auto setting the terminal title.") |
|
247 | 274 | ), |
|
248 |
(('- |
|
|
249 |
action='store_false', dest='InteractiveShell.term_title', |
|
|
275 | (('--no-term-title',), dict( | |
|
276 | action='store_false', dest='InteractiveShell.term_title', | |
|
250 | 277 | help="Disable auto setting the terminal title.") |
|
251 | 278 | ), |
|
252 | (('-xmode',), dict( | |
|
253 |
type=str, dest='InteractiveShell.xmode', |
|
|
254 | help="Exception mode ('Plain','Context','Verbose')", | |
|
279 | (('--xmode',), dict( | |
|
280 | type=str, dest='InteractiveShell.xmode', | |
|
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 | 293 | metavar='InteractiveShell.xmode') |
|
256 | 294 | ), |
|
257 | (('-ext',), dict( | |
|
258 |
type=str, dest='Global.extra_extension', |
|
|
295 | (('--ext',), dict( | |
|
296 | type=str, dest='Global.extra_extension', | |
|
259 | 297 | help="The dotted module name of an IPython extension to load.", |
|
260 | 298 | metavar='Global.extra_extension') |
|
261 | 299 | ), |
|
262 | 300 | (('-c',), dict( |
|
263 |
type=str, dest='Global.code_to_run', |
|
|
301 | type=str, dest='Global.code_to_run', | |
|
264 | 302 | help="Execute the given command string.", |
|
265 | 303 | metavar='Global.code_to_run') |
|
266 | 304 | ), |
|
267 | 305 | (('-i',), dict( |
|
268 |
action='store_true', dest='Global.force_interact', |
|
|
269 | help="If running code from the command line, become interactive afterwards.") | |
|
270 | ), | |
|
271 | (('-wthread',), dict( | |
|
272 | action='store_true', dest='Global.wthread', default=NoConfigDefault, | |
|
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): | |
|
306 | action='store_true', dest='Global.force_interact', | |
|
307 | help= | |
|
308 | "If running code from the command line, become interactive afterwards." | |
|
309 | ) | |
|
310 | ), | |
|
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 | 350 | class IPythonApp(Application): |
|
299 | name = 'ipython' | |
|
300 | config_file_name = _default_config_file_name | |
|
351 | name = u'ipython' | |
|
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 | 393 | def create_default_config(self): |
|
303 | 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 | 401 | # If the -c flag is given or a file is given to run at the cmd line |
|
307 | 402 | # like "ipython foo.py", normally we exit without starting the main |
|
308 | 403 | # loop. The force_interact config variable allows a user to override |
|
309 | 404 | # this and interact. It is also set by the -i cmd line flag, just |
|
310 | 405 | # like Python. |
|
311 |
|
|
|
406 | Global.force_interact = False | |
|
312 | 407 | |
|
313 | 408 | # By default always interact by starting the IPython mainloop. |
|
314 |
|
|
|
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 | |
|
409 | Global.interact = True | |
|
320 | 410 | |
|
321 | 411 | # No GUI integration by default |
|
322 |
|
|
|
323 | self.default_config.Global.q4thread = False | |
|
324 |
|
|
|
325 | ||
|
326 | def create_command_line_config(self): | |
|
327 | """Create and return a command line config loader.""" | |
|
328 | return IPythonAppCLConfigLoader( | |
|
329 | description=ipython_desc, | |
|
330 | version=release.version) | |
|
331 | ||
|
332 | def post_load_command_line_config(self): | |
|
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'] | |
|
412 | Global.gui = False | |
|
413 | # Pylab off by default | |
|
414 | Global.pylab = False | |
|
415 | ||
|
416 | # Deprecated versions of gui support that used threading, we support | |
|
417 | # them just for bacwards compatibility as an alternate spelling for | |
|
418 | # '--gui X' | |
|
419 | Global.qthread = False | |
|
420 | Global.q4thread = False | |
|
421 | Global.wthread = False | |
|
422 | Global.gthread = False | |
|
340 | 423 | |
|
341 | 424 | def load_file_config(self): |
|
342 | 425 | if hasattr(self.command_line_config.Global, 'quick'): |
|
343 | 426 | if self.command_line_config.Global.quick: |
|
344 | 427 | self.file_config = Config() |
|
345 | 428 | return |
|
346 | 429 | super(IPythonApp, self).load_file_config() |
|
347 | 430 | |
|
348 | 431 | def post_load_file_config(self): |
|
349 | 432 | if hasattr(self.command_line_config.Global, 'extra_extension'): |
|
350 | 433 | if not hasattr(self.file_config.Global, 'extensions'): |
|
351 | 434 | self.file_config.Global.extensions = [] |
|
352 | 435 | self.file_config.Global.extensions.append( |
|
353 | 436 | self.command_line_config.Global.extra_extension) |
|
354 | 437 | del self.command_line_config.Global.extra_extension |
|
355 | 438 | |
|
356 | 439 | def pre_construct(self): |
|
357 | 440 | config = self.master_config |
|
358 | 441 | |
|
359 | 442 | if hasattr(config.Global, 'classic'): |
|
360 | 443 | if config.Global.classic: |
|
361 | 444 | config.InteractiveShell.cache_size = 0 |
|
362 | 445 | config.InteractiveShell.pprint = 0 |
|
363 | 446 | config.InteractiveShell.prompt_in1 = '>>> ' |
|
364 | 447 | config.InteractiveShell.prompt_in2 = '... ' |
|
365 | 448 | config.InteractiveShell.prompt_out = '' |
|
366 | 449 | config.InteractiveShell.separate_in = \ |
|
367 | 450 | config.InteractiveShell.separate_out = \ |
|
368 | 451 | config.InteractiveShell.separate_out2 = '' |
|
369 | 452 | config.InteractiveShell.colors = 'NoColor' |
|
370 | 453 | config.InteractiveShell.xmode = 'Plain' |
|
371 | 454 | |
|
372 | 455 | if hasattr(config.Global, 'nosep'): |
|
373 | 456 | if config.Global.nosep: |
|
374 | 457 | config.InteractiveShell.separate_in = \ |
|
375 | 458 | config.InteractiveShell.separate_out = \ |
|
376 | 459 | config.InteractiveShell.separate_out2 = '' |
|
377 | 460 | |
|
378 | 461 | # if there is code of files to run from the cmd line, don't interact |
|
379 | 462 | # unless the -i flag (Global.force_interact) is true. |
|
380 | 463 | code_to_run = config.Global.get('code_to_run','') |
|
381 | 464 | file_to_run = False |
|
382 |
if |
|
|
383 | if self.extra_args[0]: | |
|
465 | if self.extra_args and self.extra_args[0]: | |
|
384 | 466 | file_to_run = True |
|
385 | 467 | if file_to_run or code_to_run: |
|
386 | 468 | if not config.Global.force_interact: |
|
387 | 469 | config.Global.interact = False |
|
388 | 470 | |
|
389 | 471 | def construct(self): |
|
390 | 472 | # I am a little hesitant to put these into InteractiveShell itself. |
|
391 | 473 | # But that might be the place for them |
|
392 | 474 | sys.path.insert(0, '') |
|
393 | 475 | |
|
394 | 476 | # Create an InteractiveShell instance |
|
395 | self.shell = InteractiveShell( | |
|
396 | parent=None, | |
|
397 | config=self.master_config | |
|
398 | ) | |
|
477 | self.shell = InteractiveShell(None, self.master_config, | |
|
478 | **self.shell_params ) | |
|
399 | 479 | |
|
400 | 480 | def post_construct(self): |
|
401 | 481 | """Do actions after construct, but before starting the app.""" |
|
402 | 482 | config = self.master_config |
|
403 | 483 | |
|
404 | 484 | # shell.display_banner should always be False for the terminal |
|
405 | 485 | # based app, because we call shell.show_banner() by hand below |
|
406 | 486 | # so the banner shows *before* all extension loading stuff. |
|
407 | 487 | self.shell.display_banner = False |
|
408 | 488 | |
|
409 | 489 | if config.Global.display_banner and \ |
|
410 | 490 | config.Global.interact: |
|
411 | 491 | self.shell.show_banner() |
|
412 | 492 | |
|
413 | 493 | # Make sure there is a space below the banner. |
|
414 | 494 | if self.log_level <= logging.INFO: print |
|
415 | 495 | |
|
416 | 496 | # Now a variety of things that happen after the banner is printed. |
|
417 | self._enable_gui() | |
|
497 | self._enable_gui_pylab() | |
|
418 | 498 | self._load_extensions() |
|
419 | 499 | self._run_exec_lines() |
|
420 | 500 | self._run_exec_files() |
|
421 | 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): | |
|
424 | """Enable GUI event loop integration.""" | |
|
425 | config = self.master_config | |
|
426 | try: | |
|
427 | # Enable GUI integration | |
|
428 | if config.Global.wthread: | |
|
429 |
self.log. |
|
|
430 | inputhook.enable_wx(app=True) | |
|
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() | |
|
535 | if gui or Global.pylab: | |
|
536 | try: | |
|
537 | self.log.info("Enabling GUI event loop integration, " | |
|
538 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) | |
|
539 | activate(gui) | |
|
540 | except: | |
|
541 | self.log.warn("Error in enabling GUI event loop integration:") | |
|
542 | self.shell.showtraceback() | |
|
440 | 543 | |
|
441 | 544 | def _load_extensions(self): |
|
442 | 545 | """Load all IPython extensions in Global.extensions. |
|
443 | 546 | |
|
444 | 547 | This uses the :meth:`InteractiveShell.load_extensions` to load all |
|
445 | 548 | the extensions listed in ``self.master_config.Global.extensions``. |
|
446 | 549 | """ |
|
447 | 550 | try: |
|
448 | 551 | if hasattr(self.master_config.Global, 'extensions'): |
|
449 | 552 | self.log.debug("Loading IPython extensions...") |
|
450 | 553 | extensions = self.master_config.Global.extensions |
|
451 | 554 | for ext in extensions: |
|
452 | 555 | try: |
|
453 | 556 | self.log.info("Loading IPython extension: %s" % ext) |
|
454 | 557 | self.shell.load_extension(ext) |
|
455 | 558 | except: |
|
456 | 559 | self.log.warn("Error in loading extension: %s" % ext) |
|
457 | 560 | self.shell.showtraceback() |
|
458 | 561 | except: |
|
459 | 562 | self.log.warn("Unknown error in loading extensions:") |
|
460 | 563 | self.shell.showtraceback() |
|
461 | 564 | |
|
462 | 565 | def _run_exec_lines(self): |
|
463 | 566 | """Run lines of code in Global.exec_lines in the user's namespace.""" |
|
464 | 567 | try: |
|
465 | 568 | if hasattr(self.master_config.Global, 'exec_lines'): |
|
466 | 569 | self.log.debug("Running code from Global.exec_lines...") |
|
467 | 570 | exec_lines = self.master_config.Global.exec_lines |
|
468 | 571 | for line in exec_lines: |
|
469 | 572 | try: |
|
470 | 573 | self.log.info("Running code in user namespace: %s" % line) |
|
471 | 574 | self.shell.runlines(line) |
|
472 | 575 | except: |
|
473 | 576 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
474 | 577 | self.shell.showtraceback() |
|
475 | 578 | except: |
|
476 | 579 | self.log.warn("Unknown error in handling Global.exec_lines:") |
|
477 | 580 | self.shell.showtraceback() |
|
478 | 581 | |
|
479 | 582 | def _exec_file(self, fname): |
|
480 | full_filename = filefind(fname, ['.', self.ipythondir]) | |
|
583 | full_filename = filefind(fname, [u'.', self.ipython_dir]) | |
|
481 | 584 | if os.path.isfile(full_filename): |
|
482 | if full_filename.endswith('.py'): | |
|
585 | if full_filename.endswith(u'.py'): | |
|
483 | 586 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
484 | 587 | self.shell.safe_execfile(full_filename, self.shell.user_ns) |
|
485 | 588 | elif full_filename.endswith('.ipy'): |
|
486 | 589 | self.log.info("Running file in user namespace: %s" % full_filename) |
|
487 | 590 | self.shell.safe_execfile_ipy(full_filename) |
|
488 | 591 | else: |
|
489 | 592 | self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename) |
|
490 | 593 | |
|
491 | 594 | def _run_exec_files(self): |
|
492 | 595 | try: |
|
493 | 596 | if hasattr(self.master_config.Global, 'exec_files'): |
|
494 | 597 | self.log.debug("Running files in Global.exec_files...") |
|
495 | 598 | exec_files = self.master_config.Global.exec_files |
|
496 | 599 | for fname in exec_files: |
|
497 | 600 | self._exec_file(fname) |
|
498 | 601 | except: |
|
499 | 602 | self.log.warn("Unknown error in handling Global.exec_files:") |
|
500 | 603 | self.shell.showtraceback() |
|
501 | 604 | |
|
502 | 605 | def _run_cmd_line_code(self): |
|
503 | 606 | if hasattr(self.master_config.Global, 'code_to_run'): |
|
504 | 607 | line = self.master_config.Global.code_to_run |
|
505 | 608 | try: |
|
506 | 609 | self.log.info("Running code given at command line (-c): %s" % line) |
|
507 | 610 | self.shell.runlines(line) |
|
508 | 611 | except: |
|
509 | 612 | self.log.warn("Error in executing line in user namespace: %s" % line) |
|
510 | 613 | self.shell.showtraceback() |
|
511 | 614 | return |
|
512 | 615 | # Like Python itself, ignore the second if the first of these is present |
|
513 | 616 | try: |
|
514 | 617 | fname = self.extra_args[0] |
|
515 | 618 | except: |
|
516 | 619 | pass |
|
517 | 620 | else: |
|
518 | 621 | try: |
|
519 | 622 | self._exec_file(fname) |
|
520 | 623 | except: |
|
521 | 624 | self.log.warn("Error in executing file in user namespace: %s" % fname) |
|
522 | 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 | 632 | def start_app(self): |
|
525 | 633 | if self.master_config.Global.interact: |
|
526 | 634 | self.log.debug("Starting IPython's mainloop...") |
|
527 | 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): | |
|
531 | """Load the default config file from the default ipythondir. | |
|
640 | def load_default_config(ipython_dir=None): | |
|
641 | """Load the default config file from the default ipython_dir. | |
|
532 | 642 | |
|
533 | 643 | This is useful for embedded shells. |
|
534 | 644 | """ |
|
535 | if ipythondir is None: | |
|
536 | ipythondir = get_ipython_dir() | |
|
537 |
cl = PyFileConfigLoader( |
|
|
645 | if ipython_dir is None: | |
|
646 | ipython_dir = get_ipython_dir() | |
|
647 | cl = PyFileConfigLoader(default_config_file_name, ipython_dir) | |
|
538 | 648 | config = cl.load_config() |
|
539 | 649 | return config |
|
540 | 650 | |
|
541 | 651 | |
|
542 | 652 | def launch_new_instance(): |
|
543 | """Create a run a full blown IPython instance""" | |
|
653 | """Create and run a full blown IPython instance""" | |
|
544 | 654 | app = IPythonApp() |
|
545 | 655 | app.start() |
|
546 |
@@ -1,2470 +1,2527 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Main IPython Component |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
8 | 8 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
9 | 9 | # Copyright (C) 2008-2009 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Imports |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | |
|
19 | 19 | from __future__ import with_statement |
|
20 | from __future__ import absolute_import | |
|
20 | 21 | |
|
21 | 22 | import __builtin__ |
|
22 | 23 | import StringIO |
|
23 | 24 | import bdb |
|
24 | 25 | import codeop |
|
25 | 26 | import exceptions |
|
26 | 27 | import new |
|
27 | 28 | import os |
|
28 | 29 | import re |
|
29 | 30 | import string |
|
30 | 31 | import sys |
|
31 | 32 | import tempfile |
|
32 | 33 | from contextlib import nested |
|
33 | 34 | |
|
34 | from IPython.core import ultratb | |
|
35 | 35 | from IPython.core import debugger, oinspect |
|
36 | from IPython.core import shadowns | |
|
37 | 36 | from IPython.core import history as ipcorehist |
|
38 | 37 | from IPython.core import prefilter |
|
38 | from IPython.core import shadowns | |
|
39 | from IPython.core import ultratb | |
|
39 | 40 | from IPython.core.alias import AliasManager |
|
40 | 41 | from IPython.core.builtin_trap import BuiltinTrap |
|
42 | from IPython.core.component import Component | |
|
41 | 43 | from IPython.core.display_trap import DisplayTrap |
|
44 | from IPython.core.error import TryNext, UsageError | |
|
42 | 45 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
43 | 46 | from IPython.core.logger import Logger |
|
44 | 47 | from IPython.core.magic import Magic |
|
45 | from IPython.core.prompts import CachedOutput | |
|
46 | 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 | 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 | 52 | from IPython.external.Itpl import ItplNS |
|
53 | from IPython.lib.inputhook import enable_gui | |
|
53 | 54 | from IPython.lib.backgroundjobs import BackgroundJobManager |
|
54 | from IPython.utils.ipstruct import Struct | |
|
55 | 55 | from IPython.utils import PyColorize |
|
56 |
from IPython.utils |
|
|
56 | from IPython.utils import pickleshare | |
|
57 | 57 | from IPython.utils.genutils import get_ipython_dir |
|
58 | from IPython.utils.ipstruct import Struct | |
|
58 | 59 | from IPython.utils.platutils import toggle_set_term_title, set_term_title |
|
59 | 60 | from IPython.utils.strdispatch import StrDispatch |
|
60 | 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 | 66 | # from IPython.utils import growl |
|
63 | 67 | # growl.start("IPython") |
|
64 | 68 | |
|
65 | 69 | from IPython.utils.traitlets import ( |
|
66 | 70 | Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode |
|
67 | 71 | ) |
|
68 | 72 | |
|
69 | 73 | #----------------------------------------------------------------------------- |
|
70 | 74 | # Globals |
|
71 | 75 | #----------------------------------------------------------------------------- |
|
72 | 76 | |
|
73 | ||
|
74 | 77 | # store the builtin raw_input globally, and use this always, in case user code |
|
75 | 78 | # overwrites it (like wx.py.PyShell does) |
|
76 | 79 | raw_input_original = raw_input |
|
77 | 80 | |
|
78 | 81 | # compiled regexps for autoindent management |
|
79 | 82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
80 | 83 | |
|
81 | ||
|
82 | 84 | #----------------------------------------------------------------------------- |
|
83 | 85 | # Utilities |
|
84 | 86 | #----------------------------------------------------------------------------- |
|
85 | 87 | |
|
86 | ||
|
87 | 88 | ini_spaces_re = re.compile(r'^(\s+)') |
|
88 | 89 | |
|
89 | 90 | |
|
90 | 91 | def num_ini_spaces(strng): |
|
91 | 92 | """Return the number of initial spaces in a string""" |
|
92 | 93 | |
|
93 | 94 | ini_spaces = ini_spaces_re.match(strng) |
|
94 | 95 | if ini_spaces: |
|
95 | 96 | return ini_spaces.end() |
|
96 | 97 | else: |
|
97 | 98 | return 0 |
|
98 | 99 | |
|
99 | 100 | |
|
100 | 101 | def softspace(file, newvalue): |
|
101 | 102 | """Copied from code.py, to remove the dependency""" |
|
102 | 103 | |
|
103 | 104 | oldvalue = 0 |
|
104 | 105 | try: |
|
105 | 106 | oldvalue = file.softspace |
|
106 | 107 | except AttributeError: |
|
107 | 108 | pass |
|
108 | 109 | try: |
|
109 | 110 | file.softspace = newvalue |
|
110 | 111 | except (AttributeError, TypeError): |
|
111 | 112 | # "attribute-less object" or "read-only attributes" |
|
112 | 113 | pass |
|
113 | 114 | return oldvalue |
|
114 | 115 | |
|
115 | 116 | |
|
117 | def no_op(*a, **kw): pass | |
|
118 | ||
|
116 | 119 | class SpaceInInput(exceptions.Exception): pass |
|
117 | 120 | |
|
118 | 121 | class Bunch: pass |
|
119 | 122 | |
|
120 | 123 | class InputList(list): |
|
121 | 124 | """Class to store user input. |
|
122 | 125 | |
|
123 | 126 | It's basically a list, but slices return a string instead of a list, thus |
|
124 | 127 | allowing things like (assuming 'In' is an instance): |
|
125 | 128 | |
|
126 | 129 | exec In[4:7] |
|
127 | 130 | |
|
128 | 131 | or |
|
129 | 132 | |
|
130 | 133 | exec In[5:9] + In[14] + In[21:25]""" |
|
131 | 134 | |
|
132 | 135 | def __getslice__(self,i,j): |
|
133 | 136 | return ''.join(list.__getslice__(self,i,j)) |
|
134 | 137 | |
|
135 | 138 | |
|
136 | 139 | class SyntaxTB(ultratb.ListTB): |
|
137 | 140 | """Extension which holds some state: the last exception value""" |
|
138 | 141 | |
|
139 | 142 | def __init__(self,color_scheme = 'NoColor'): |
|
140 | 143 | ultratb.ListTB.__init__(self,color_scheme) |
|
141 | 144 | self.last_syntax_error = None |
|
142 | 145 | |
|
143 | 146 | def __call__(self, etype, value, elist): |
|
144 | 147 | self.last_syntax_error = value |
|
145 | 148 | ultratb.ListTB.__call__(self,etype,value,elist) |
|
146 | 149 | |
|
147 | 150 | def clear_err_state(self): |
|
148 | 151 | """Return the current error state and clear it""" |
|
149 | 152 | e = self.last_syntax_error |
|
150 | 153 | self.last_syntax_error = None |
|
151 | 154 | return e |
|
152 | 155 | |
|
153 | 156 | |
|
154 | 157 | def get_default_editor(): |
|
155 | 158 | try: |
|
156 | 159 | ed = os.environ['EDITOR'] |
|
157 | 160 | except KeyError: |
|
158 | 161 | if os.name == 'posix': |
|
159 | 162 | ed = 'vi' # the only one guaranteed to be there! |
|
160 | 163 | else: |
|
161 | 164 | ed = 'notepad' # same in Windows! |
|
162 | 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 | 177 | class SeparateStr(Str): |
|
166 | 178 | """A Str subclass to validate separate_in, separate_out, etc. |
|
167 | 179 | |
|
168 | 180 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
169 | 181 | """ |
|
170 | 182 | |
|
171 | 183 | def validate(self, obj, value): |
|
172 | 184 | if value == '0': value = '' |
|
173 | 185 | value = value.replace('\\n','\n') |
|
174 | 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 | 241 | # Main IPython class |
|
179 | 242 | #----------------------------------------------------------------------------- |
|
180 | 243 | |
|
181 | 244 | |
|
182 | 245 | class InteractiveShell(Component, Magic): |
|
183 | 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 | 249 | autoedit_syntax = CBool(False, config=True) |
|
187 | 250 | autoindent = CBool(True, config=True) |
|
188 | 251 | automagic = CBool(True, config=True) |
|
189 | 252 | banner = Str('') |
|
190 | 253 | banner1 = Str(default_banner, config=True) |
|
191 | 254 | banner2 = Str('', config=True) |
|
192 | 255 | cache_size = Int(1000, config=True) |
|
193 | 256 | color_info = CBool(True, config=True) |
|
194 | 257 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
195 |
default_value= |
|
|
258 | default_value=get_default_colors(), config=True) | |
|
196 | 259 | confirm_exit = CBool(True, config=True) |
|
197 | 260 | debug = CBool(False, config=True) |
|
198 | 261 | deep_reload = CBool(False, config=True) |
|
199 | 262 | # This display_banner only controls whether or not self.show_banner() |
|
200 | 263 | # is called when mainloop/interact are called. The default is False |
|
201 | 264 | # because for the terminal based application, the banner behavior |
|
202 | 265 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
203 | 266 | # to determine if *it* should call show_banner() by hand or not. |
|
204 | 267 | display_banner = CBool(False) # This isn't configurable! |
|
205 | 268 | embedded = CBool(False) |
|
206 | 269 | embedded_active = CBool(False) |
|
207 | 270 | editor = Str(get_default_editor(), config=True) |
|
208 | 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 | 273 | logstart = CBool(False, config=True) |
|
211 | 274 | logfile = Str('', config=True) |
|
212 | 275 | logappend = Str('', config=True) |
|
213 | 276 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
214 | 277 | config=True) |
|
215 | 278 | pager = Str('less', config=True) |
|
216 | 279 | pdb = CBool(False, config=True) |
|
217 | 280 | pprint = CBool(True, config=True) |
|
218 | 281 | profile = Str('', config=True) |
|
219 | 282 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
220 | 283 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
221 | 284 | prompt_out = Str('Out[\\#]: ', config=True) |
|
222 | 285 | prompts_pad_left = CBool(True, config=True) |
|
223 | 286 | quiet = CBool(False, config=True) |
|
224 | 287 | |
|
225 | 288 | readline_use = CBool(True, config=True) |
|
226 | 289 | readline_merge_completions = CBool(True, config=True) |
|
227 | 290 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
228 | 291 | readline_remove_delims = Str('-/~', config=True) |
|
229 | 292 | readline_parse_and_bind = List([ |
|
230 | 293 | 'tab: complete', |
|
231 | 294 | '"\C-l": possible-completions', |
|
232 | 295 | 'set show-all-if-ambiguous on', |
|
233 | 296 | '"\C-o": tab-insert', |
|
234 | 297 | '"\M-i": " "', |
|
235 | 298 | '"\M-o": "\d\d\d\d"', |
|
236 | 299 | '"\M-I": "\d\d\d\d"', |
|
237 | 300 | '"\C-r": reverse-search-history', |
|
238 | 301 | '"\C-s": forward-search-history', |
|
239 | 302 | '"\C-p": history-search-backward', |
|
240 | 303 | '"\C-n": history-search-forward', |
|
241 | 304 | '"\e[A": history-search-backward', |
|
242 | 305 | '"\e[B": history-search-forward', |
|
243 | 306 | '"\C-k": kill-line', |
|
244 | 307 | '"\C-u": unix-line-discard', |
|
245 | 308 | ], allow_none=False, config=True) |
|
246 | 309 | |
|
247 | 310 | screen_length = Int(0, config=True) |
|
248 | 311 | |
|
249 | 312 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
250 | 313 | separate_in = SeparateStr('\n', config=True) |
|
251 | 314 | separate_out = SeparateStr('', config=True) |
|
252 | 315 | separate_out2 = SeparateStr('', config=True) |
|
253 | 316 | |
|
254 | 317 | system_header = Str('IPython system call: ', config=True) |
|
255 | 318 | system_verbose = CBool(False, config=True) |
|
256 | 319 | term_title = CBool(False, config=True) |
|
257 | 320 | wildcards_case_sensitive = CBool(True, config=True) |
|
258 | 321 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
259 | 322 | default_value='Context', config=True) |
|
260 | 323 | |
|
261 | 324 | autoexec = List(allow_none=False) |
|
262 | 325 | |
|
263 | 326 | # class attribute to indicate whether the class supports threads or not. |
|
264 | 327 | # Subclasses with thread support should override this as needed. |
|
265 | 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 | 331 | user_ns=None, user_global_ns=None, |
|
269 | 332 | banner1=None, banner2=None, display_banner=None, |
|
270 | 333 | custom_exceptions=((),None)): |
|
271 | 334 | |
|
272 | 335 | # This is where traits with a config_key argument are updated |
|
273 | 336 | # from the values on config. |
|
274 | 337 | super(InteractiveShell, self).__init__(parent, config=config) |
|
275 | 338 | |
|
276 | 339 | # These are relatively independent and stateless |
|
277 | self.init_ipythondir(ipythondir) | |
|
340 | self.init_ipython_dir(ipython_dir) | |
|
278 | 341 | self.init_instance_attrs() |
|
279 | 342 | self.init_term_title() |
|
280 | 343 | self.init_usage(usage) |
|
281 | 344 | self.init_banner(banner1, banner2, display_banner) |
|
282 | 345 | |
|
283 | 346 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
284 | 347 | self.init_create_namespaces(user_ns, user_global_ns) |
|
285 | 348 | # This has to be done after init_create_namespaces because it uses |
|
286 | 349 | # something in self.user_ns, but before init_sys_modules, which |
|
287 | 350 | # is the first thing to modify sys. |
|
288 | 351 | self.save_sys_module_state() |
|
289 | 352 | self.init_sys_modules() |
|
290 | 353 | |
|
291 | 354 | self.init_history() |
|
292 | 355 | self.init_encoding() |
|
293 | 356 | self.init_prefilter() |
|
294 | 357 | |
|
295 | 358 | Magic.__init__(self, self) |
|
296 | 359 | |
|
297 | 360 | self.init_syntax_highlighting() |
|
298 | 361 | self.init_hooks() |
|
299 | 362 | self.init_pushd_popd_magic() |
|
300 | 363 | self.init_traceback_handlers(custom_exceptions) |
|
301 | 364 | self.init_user_ns() |
|
302 | 365 | self.init_logger() |
|
303 | 366 | self.init_alias() |
|
304 | 367 | self.init_builtins() |
|
305 | 368 | |
|
306 | 369 | # pre_config_initialization |
|
307 | 370 | self.init_shadow_hist() |
|
308 | 371 | |
|
309 | 372 | # The next section should contain averything that was in ipmaker. |
|
310 | 373 | self.init_logstart() |
|
311 | 374 | |
|
312 | 375 | # The following was in post_config_initialization |
|
313 | 376 | self.init_inspector() |
|
314 | 377 | self.init_readline() |
|
315 | 378 | self.init_prompts() |
|
316 | 379 | self.init_displayhook() |
|
317 | 380 | self.init_reload_doctest() |
|
318 | 381 | self.init_magics() |
|
319 | 382 | self.init_pdb() |
|
320 | 383 | self.hooks.late_startup_hook() |
|
321 | 384 | |
|
322 | 385 | def get_ipython(self): |
|
386 | """Return the currently running IPython instance.""" | |
|
323 | 387 | return self |
|
324 | 388 | |
|
325 | 389 | #------------------------------------------------------------------------- |
|
326 | 390 | # Trait changed handlers |
|
327 | 391 | #------------------------------------------------------------------------- |
|
328 | 392 | |
|
329 | 393 | def _banner1_changed(self): |
|
330 | 394 | self.compute_banner() |
|
331 | 395 | |
|
332 | 396 | def _banner2_changed(self): |
|
333 | 397 | self.compute_banner() |
|
334 | 398 | |
|
335 | def _ipythondir_changed(self, name, new): | |
|
399 | def _ipython_dir_changed(self, name, new): | |
|
336 | 400 | if not os.path.isdir(new): |
|
337 | 401 | os.makedirs(new, mode = 0777) |
|
338 | 402 | if not os.path.isdir(self.ipython_extension_dir): |
|
339 | 403 | os.makedirs(self.ipython_extension_dir, mode = 0777) |
|
340 | 404 | |
|
341 | 405 | @property |
|
342 | 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 | 409 | @property |
|
346 | 410 | def usable_screen_length(self): |
|
347 | 411 | if self.screen_length == 0: |
|
348 | 412 | return 0 |
|
349 | 413 | else: |
|
350 | 414 | num_lines_bot = self.separate_in.count('\n')+1 |
|
351 | 415 | return self.screen_length - num_lines_bot |
|
352 | 416 | |
|
353 | 417 | def _term_title_changed(self, name, new_value): |
|
354 | 418 | self.init_term_title() |
|
355 | 419 | |
|
356 | 420 | def set_autoindent(self,value=None): |
|
357 | 421 | """Set the autoindent flag, checking for readline support. |
|
358 | 422 | |
|
359 | 423 | If called with no arguments, it acts as a toggle.""" |
|
360 | 424 | |
|
361 | 425 | if not self.has_readline: |
|
362 | 426 | if os.name == 'posix': |
|
363 | 427 | warn("The auto-indent feature requires the readline library") |
|
364 | 428 | self.autoindent = 0 |
|
365 | 429 | return |
|
366 | 430 | if value is None: |
|
367 | 431 | self.autoindent = not self.autoindent |
|
368 | 432 | else: |
|
369 | 433 | self.autoindent = value |
|
370 | 434 | |
|
371 | 435 | #------------------------------------------------------------------------- |
|
372 | 436 | # init_* methods called by __init__ |
|
373 | 437 | #------------------------------------------------------------------------- |
|
374 | 438 | |
|
375 | def init_ipythondir(self, ipythondir): | |
|
376 | if ipythondir is not None: | |
|
377 | self.ipythondir = ipythondir | |
|
378 | self.config.Global.ipythondir = self.ipythondir | |
|
439 | def init_ipython_dir(self, ipython_dir): | |
|
440 | if ipython_dir is not None: | |
|
441 | self.ipython_dir = ipython_dir | |
|
442 | self.config.Global.ipython_dir = self.ipython_dir | |
|
379 | 443 | return |
|
380 | 444 | |
|
381 | if hasattr(self.config.Global, 'ipythondir'): | |
|
382 | self.ipythondir = self.config.Global.ipythondir | |
|
445 | if hasattr(self.config.Global, 'ipython_dir'): | |
|
446 | self.ipython_dir = self.config.Global.ipython_dir | |
|
383 | 447 | else: |
|
384 | self.ipythondir = get_ipython_dir() | |
|
448 | self.ipython_dir = get_ipython_dir() | |
|
385 | 449 | |
|
386 | 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 | 453 | def init_instance_attrs(self): |
|
390 | 454 | self.jobs = BackgroundJobManager() |
|
391 | 455 | self.more = False |
|
392 | 456 | |
|
393 | 457 | # command compiler |
|
394 | 458 | self.compile = codeop.CommandCompiler() |
|
395 | 459 | |
|
396 | 460 | # User input buffer |
|
397 | 461 | self.buffer = [] |
|
398 | 462 | |
|
399 | 463 | # Make an empty namespace, which extension writers can rely on both |
|
400 | 464 | # existing and NEVER being used by ipython itself. This gives them a |
|
401 | 465 | # convenient location for storing additional information and state |
|
402 | 466 | # their extensions may require, without fear of collisions with other |
|
403 | 467 | # ipython names that may develop later. |
|
404 | 468 | self.meta = Struct() |
|
405 | 469 | |
|
406 | 470 | # Object variable to store code object waiting execution. This is |
|
407 | 471 | # used mainly by the multithreaded shells, but it can come in handy in |
|
408 | 472 | # other situations. No need to use a Queue here, since it's a single |
|
409 | 473 | # item which gets cleared once run. |
|
410 | 474 | self.code_to_run = None |
|
411 | 475 | |
|
412 | 476 | # Flag to mark unconditional exit |
|
413 | 477 | self.exit_now = False |
|
414 | 478 | |
|
415 | 479 | # Temporary files used for various purposes. Deleted at exit. |
|
416 | 480 | self.tempfiles = [] |
|
417 | 481 | |
|
418 | 482 | # Keep track of readline usage (later set by init_readline) |
|
419 | 483 | self.has_readline = False |
|
420 | 484 | |
|
421 | 485 | # keep track of where we started running (mainly for crash post-mortem) |
|
422 | 486 | # This is not being used anywhere currently. |
|
423 | 487 | self.starting_dir = os.getcwd() |
|
424 | 488 | |
|
425 | 489 | # Indentation management |
|
426 | 490 | self.indent_current_nsp = 0 |
|
427 | 491 | |
|
428 | 492 | def init_term_title(self): |
|
429 | 493 | # Enable or disable the terminal title. |
|
430 | 494 | if self.term_title: |
|
431 | 495 | toggle_set_term_title(True) |
|
432 | 496 | set_term_title('IPython: ' + abbrev_cwd()) |
|
433 | 497 | else: |
|
434 | 498 | toggle_set_term_title(False) |
|
435 | 499 | |
|
436 | 500 | def init_usage(self, usage=None): |
|
437 | 501 | if usage is None: |
|
438 | 502 | self.usage = interactive_usage |
|
439 | 503 | else: |
|
440 | 504 | self.usage = usage |
|
441 | 505 | |
|
442 | 506 | def init_encoding(self): |
|
443 | 507 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
444 | 508 | # under Win32 have it set to None, and we need to have a known valid |
|
445 | 509 | # encoding to use in the raw_input() method |
|
446 | 510 | try: |
|
447 | 511 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
448 | 512 | except AttributeError: |
|
449 | 513 | self.stdin_encoding = 'ascii' |
|
450 | 514 | |
|
451 | 515 | def init_syntax_highlighting(self): |
|
452 | 516 | # Python source parser/formatter for syntax highlighting |
|
453 | 517 | pyformat = PyColorize.Parser().format |
|
454 | 518 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
455 | 519 | |
|
456 | 520 | def init_pushd_popd_magic(self): |
|
457 | 521 | # for pushd/popd management |
|
458 | 522 | try: |
|
459 | 523 | self.home_dir = get_home_dir() |
|
460 | 524 | except HomeDirError, msg: |
|
461 | 525 | fatal(msg) |
|
462 | 526 | |
|
463 | 527 | self.dir_stack = [] |
|
464 | 528 | |
|
465 | 529 | def init_logger(self): |
|
466 | 530 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
467 | 531 | # local shortcut, this is used a LOT |
|
468 | 532 | self.log = self.logger.log |
|
469 | 533 | |
|
470 | 534 | def init_logstart(self): |
|
471 | 535 | if self.logappend: |
|
472 | 536 | self.magic_logstart(self.logappend + ' append') |
|
473 | 537 | elif self.logfile: |
|
474 | 538 | self.magic_logstart(self.logfile) |
|
475 | 539 | elif self.logstart: |
|
476 | 540 | self.magic_logstart() |
|
477 | 541 | |
|
478 | 542 | def init_builtins(self): |
|
479 | 543 | self.builtin_trap = BuiltinTrap(self) |
|
480 | 544 | |
|
481 | 545 | def init_inspector(self): |
|
482 | 546 | # Object inspector |
|
483 | 547 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
484 | 548 | PyColorize.ANSICodeColors, |
|
485 | 549 | 'NoColor', |
|
486 | 550 | self.object_info_string_level) |
|
487 | 551 | |
|
488 | 552 | def init_prompts(self): |
|
489 | 553 | # Initialize cache, set in/out prompts and printing system |
|
490 | 554 | self.outputcache = CachedOutput(self, |
|
491 | 555 | self.cache_size, |
|
492 | 556 | self.pprint, |
|
493 | 557 | input_sep = self.separate_in, |
|
494 | 558 | output_sep = self.separate_out, |
|
495 | 559 | output_sep2 = self.separate_out2, |
|
496 | 560 | ps1 = self.prompt_in1, |
|
497 | 561 | ps2 = self.prompt_in2, |
|
498 | 562 | ps_out = self.prompt_out, |
|
499 | 563 | pad_left = self.prompts_pad_left) |
|
500 | 564 | |
|
501 | 565 | # user may have over-ridden the default print hook: |
|
502 | 566 | try: |
|
503 | 567 | self.outputcache.__class__.display = self.hooks.display |
|
504 | 568 | except AttributeError: |
|
505 | 569 | pass |
|
506 | 570 | |
|
507 | 571 | def init_displayhook(self): |
|
508 | 572 | self.display_trap = DisplayTrap(self, self.outputcache) |
|
509 | 573 | |
|
510 | 574 | def init_reload_doctest(self): |
|
511 | 575 | # Do a proper resetting of doctest, including the necessary displayhook |
|
512 | 576 | # monkeypatching |
|
513 | 577 | try: |
|
514 | 578 | doctest_reload() |
|
515 | 579 | except ImportError: |
|
516 | 580 | warn("doctest module does not exist.") |
|
517 | 581 | |
|
518 | 582 | #------------------------------------------------------------------------- |
|
519 | 583 | # Things related to the banner |
|
520 | 584 | #------------------------------------------------------------------------- |
|
521 | 585 | |
|
522 | 586 | def init_banner(self, banner1, banner2, display_banner): |
|
523 | 587 | if banner1 is not None: |
|
524 | 588 | self.banner1 = banner1 |
|
525 | 589 | if banner2 is not None: |
|
526 | 590 | self.banner2 = banner2 |
|
527 | 591 | if display_banner is not None: |
|
528 | 592 | self.display_banner = display_banner |
|
529 | 593 | self.compute_banner() |
|
530 | 594 | |
|
531 | 595 | def show_banner(self, banner=None): |
|
532 | 596 | if banner is None: |
|
533 | 597 | banner = self.banner |
|
534 | 598 | self.write(banner) |
|
535 | 599 | |
|
536 | 600 | def compute_banner(self): |
|
537 | 601 | self.banner = self.banner1 + '\n' |
|
538 | 602 | if self.profile: |
|
539 | 603 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
540 | 604 | if self.banner2: |
|
541 | 605 | self.banner += '\n' + self.banner2 + '\n' |
|
542 | 606 | |
|
543 | 607 | #------------------------------------------------------------------------- |
|
544 | 608 | # Things related to injections into the sys module |
|
545 | 609 | #------------------------------------------------------------------------- |
|
546 | 610 | |
|
547 | 611 | def save_sys_module_state(self): |
|
548 | 612 | """Save the state of hooks in the sys module. |
|
549 | 613 | |
|
550 | 614 | This has to be called after self.user_ns is created. |
|
551 | 615 | """ |
|
552 | 616 | self._orig_sys_module_state = {} |
|
553 | 617 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
554 | 618 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
555 | 619 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
556 | 620 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
557 | 621 | try: |
|
558 | 622 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
559 | 623 | except KeyError: |
|
560 | 624 | pass |
|
561 | 625 | |
|
562 | 626 | def restore_sys_module_state(self): |
|
563 | 627 | """Restore the state of the sys module.""" |
|
564 | 628 | try: |
|
565 | 629 | for k, v in self._orig_sys_module_state.items(): |
|
566 | 630 | setattr(sys, k, v) |
|
567 | 631 | except AttributeError: |
|
568 | 632 | pass |
|
569 | 633 | try: |
|
570 | 634 | delattr(sys, 'ipcompleter') |
|
571 | 635 | except AttributeError: |
|
572 | 636 | pass |
|
573 | 637 | # Reset what what done in self.init_sys_modules |
|
574 | 638 | try: |
|
575 | 639 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
576 | 640 | except (AttributeError, KeyError): |
|
577 | 641 | pass |
|
578 | 642 | |
|
579 | 643 | #------------------------------------------------------------------------- |
|
580 | 644 | # Things related to hooks |
|
581 | 645 | #------------------------------------------------------------------------- |
|
582 | 646 | |
|
583 | 647 | def init_hooks(self): |
|
584 | 648 | # hooks holds pointers used for user-side customizations |
|
585 | 649 | self.hooks = Struct() |
|
586 | 650 | |
|
587 | 651 | self.strdispatchers = {} |
|
588 | 652 | |
|
589 | 653 | # Set all default hooks, defined in the IPython.hooks module. |
|
590 | 654 | import IPython.core.hooks |
|
591 | 655 | hooks = IPython.core.hooks |
|
592 | 656 | for hook_name in hooks.__all__: |
|
593 | 657 | # default hooks have priority 100, i.e. low; user hooks should have |
|
594 | 658 | # 0-100 priority |
|
595 | 659 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
596 | 660 | |
|
597 | 661 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
598 | 662 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
599 | 663 | |
|
600 | 664 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
601 | 665 | adding your function to one of these hooks, you can modify IPython's |
|
602 | 666 | behavior to call at runtime your own routines.""" |
|
603 | 667 | |
|
604 | 668 | # At some point in the future, this should validate the hook before it |
|
605 | 669 | # accepts it. Probably at least check that the hook takes the number |
|
606 | 670 | # of args it's supposed to. |
|
607 | 671 | |
|
608 | 672 | f = new.instancemethod(hook,self,self.__class__) |
|
609 | 673 | |
|
610 | 674 | # check if the hook is for strdispatcher first |
|
611 | 675 | if str_key is not None: |
|
612 | 676 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
613 | 677 | sdp.add_s(str_key, f, priority ) |
|
614 | 678 | self.strdispatchers[name] = sdp |
|
615 | 679 | return |
|
616 | 680 | if re_key is not None: |
|
617 | 681 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
618 | 682 | sdp.add_re(re.compile(re_key), f, priority ) |
|
619 | 683 | self.strdispatchers[name] = sdp |
|
620 | 684 | return |
|
621 | 685 | |
|
622 | 686 | dp = getattr(self.hooks, name, None) |
|
623 | 687 | if name not in IPython.core.hooks.__all__: |
|
624 | 688 | print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ ) |
|
625 | 689 | if not dp: |
|
626 | 690 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
627 | 691 | |
|
628 | 692 | try: |
|
629 | 693 | dp.add(f,priority) |
|
630 | 694 | except AttributeError: |
|
631 | 695 | # it was not commandchain, plain old func - replace |
|
632 | 696 | dp = f |
|
633 | 697 | |
|
634 | 698 | setattr(self.hooks,name, dp) |
|
635 | 699 | |
|
636 | 700 | #------------------------------------------------------------------------- |
|
637 | 701 | # Things related to the "main" module |
|
638 | 702 | #------------------------------------------------------------------------- |
|
639 | 703 | |
|
640 | 704 | def new_main_mod(self,ns=None): |
|
641 | 705 | """Return a new 'main' module object for user code execution. |
|
642 | 706 | """ |
|
643 | 707 | main_mod = self._user_main_module |
|
644 | 708 | init_fakemod_dict(main_mod,ns) |
|
645 | 709 | return main_mod |
|
646 | 710 | |
|
647 | 711 | def cache_main_mod(self,ns,fname): |
|
648 | 712 | """Cache a main module's namespace. |
|
649 | 713 | |
|
650 | 714 | When scripts are executed via %run, we must keep a reference to the |
|
651 | 715 | namespace of their __main__ module (a FakeModule instance) around so |
|
652 | 716 | that Python doesn't clear it, rendering objects defined therein |
|
653 | 717 | useless. |
|
654 | 718 | |
|
655 | 719 | This method keeps said reference in a private dict, keyed by the |
|
656 | 720 | absolute path of the module object (which corresponds to the script |
|
657 | 721 | path). This way, for multiple executions of the same script we only |
|
658 | 722 | keep one copy of the namespace (the last one), thus preventing memory |
|
659 | 723 | leaks from old references while allowing the objects from the last |
|
660 | 724 | execution to be accessible. |
|
661 | 725 | |
|
662 | 726 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
663 | 727 | because of how Python tears down modules (it hard-sets all their |
|
664 | 728 | references to None without regard for reference counts). This method |
|
665 | 729 | must therefore make a *copy* of the given namespace, to allow the |
|
666 | 730 | original module's __dict__ to be cleared and reused. |
|
667 | 731 | |
|
668 | 732 | |
|
669 | 733 | Parameters |
|
670 | 734 | ---------- |
|
671 | 735 | ns : a namespace (a dict, typically) |
|
672 | 736 | |
|
673 | 737 | fname : str |
|
674 | 738 | Filename associated with the namespace. |
|
675 | 739 | |
|
676 | 740 | Examples |
|
677 | 741 | -------- |
|
678 | 742 | |
|
679 | 743 | In [10]: import IPython |
|
680 | 744 | |
|
681 | 745 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
682 | 746 | |
|
683 | 747 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
684 | 748 | Out[12]: True |
|
685 | 749 | """ |
|
686 | 750 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
687 | 751 | |
|
688 | 752 | def clear_main_mod_cache(self): |
|
689 | 753 | """Clear the cache of main modules. |
|
690 | 754 | |
|
691 | 755 | Mainly for use by utilities like %reset. |
|
692 | 756 | |
|
693 | 757 | Examples |
|
694 | 758 | -------- |
|
695 | 759 | |
|
696 | 760 | In [15]: import IPython |
|
697 | 761 | |
|
698 | 762 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
699 | 763 | |
|
700 | 764 | In [17]: len(_ip._main_ns_cache) > 0 |
|
701 | 765 | Out[17]: True |
|
702 | 766 | |
|
703 | 767 | In [18]: _ip.clear_main_mod_cache() |
|
704 | 768 | |
|
705 | 769 | In [19]: len(_ip._main_ns_cache) == 0 |
|
706 | 770 | Out[19]: True |
|
707 | 771 | """ |
|
708 | 772 | self._main_ns_cache.clear() |
|
709 | 773 | |
|
710 | 774 | #------------------------------------------------------------------------- |
|
711 | 775 | # Things related to debugging |
|
712 | 776 | #------------------------------------------------------------------------- |
|
713 | 777 | |
|
714 | 778 | def init_pdb(self): |
|
715 | 779 | # Set calling of pdb on exceptions |
|
716 | 780 | # self.call_pdb is a property |
|
717 | 781 | self.call_pdb = self.pdb |
|
718 | 782 | |
|
719 | 783 | def _get_call_pdb(self): |
|
720 | 784 | return self._call_pdb |
|
721 | 785 | |
|
722 | 786 | def _set_call_pdb(self,val): |
|
723 | 787 | |
|
724 | 788 | if val not in (0,1,False,True): |
|
725 | 789 | raise ValueError,'new call_pdb value must be boolean' |
|
726 | 790 | |
|
727 | 791 | # store value in instance |
|
728 | 792 | self._call_pdb = val |
|
729 | 793 | |
|
730 | 794 | # notify the actual exception handlers |
|
731 | 795 | self.InteractiveTB.call_pdb = val |
|
732 | 796 | if self.isthreaded: |
|
733 | 797 | try: |
|
734 | 798 | self.sys_excepthook.call_pdb = val |
|
735 | 799 | except: |
|
736 | 800 | warn('Failed to activate pdb for threaded exception handler') |
|
737 | 801 | |
|
738 | 802 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
739 | 803 | 'Control auto-activation of pdb at exceptions') |
|
740 | 804 | |
|
741 | 805 | def debugger(self,force=False): |
|
742 | 806 | """Call the pydb/pdb debugger. |
|
743 | 807 | |
|
744 | 808 | Keywords: |
|
745 | 809 | |
|
746 | 810 | - force(False): by default, this routine checks the instance call_pdb |
|
747 | 811 | flag and does not actually invoke the debugger if the flag is false. |
|
748 | 812 | The 'force' option forces the debugger to activate even if the flag |
|
749 | 813 | is false. |
|
750 | 814 | """ |
|
751 | 815 | |
|
752 | 816 | if not (force or self.call_pdb): |
|
753 | 817 | return |
|
754 | 818 | |
|
755 | 819 | if not hasattr(sys,'last_traceback'): |
|
756 | 820 | error('No traceback has been produced, nothing to debug.') |
|
757 | 821 | return |
|
758 | 822 | |
|
759 | 823 | # use pydb if available |
|
760 | 824 | if debugger.has_pydb: |
|
761 | 825 | from pydb import pm |
|
762 | 826 | else: |
|
763 | 827 | # fallback to our internal debugger |
|
764 | 828 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
765 | 829 | self.history_saving_wrapper(pm)() |
|
766 | 830 | |
|
767 | 831 | #------------------------------------------------------------------------- |
|
768 | 832 | # Things related to IPython's various namespaces |
|
769 | 833 | #------------------------------------------------------------------------- |
|
770 | 834 | |
|
771 | 835 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
772 | 836 | # Create the namespace where the user will operate. user_ns is |
|
773 | 837 | # normally the only one used, and it is passed to the exec calls as |
|
774 | 838 | # the locals argument. But we do carry a user_global_ns namespace |
|
775 | 839 | # given as the exec 'globals' argument, This is useful in embedding |
|
776 | 840 | # situations where the ipython shell opens in a context where the |
|
777 | 841 | # distinction between locals and globals is meaningful. For |
|
778 | 842 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
779 | 843 | |
|
780 | 844 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
781 | 845 | # level as a dict instead of a module. This is a manual fix, but I |
|
782 | 846 | # should really track down where the problem is coming from. Alex |
|
783 | 847 | # Schmolck reported this problem first. |
|
784 | 848 | |
|
785 | 849 | # A useful post by Alex Martelli on this topic: |
|
786 | 850 | # Re: inconsistent value from __builtins__ |
|
787 | 851 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
788 | 852 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
789 | 853 | # Gruppen: comp.lang.python |
|
790 | 854 | |
|
791 | 855 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
792 | 856 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
793 | 857 | # > <type 'dict'> |
|
794 | 858 | # > >>> print type(__builtins__) |
|
795 | 859 | # > <type 'module'> |
|
796 | 860 | # > Is this difference in return value intentional? |
|
797 | 861 | |
|
798 | 862 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
799 | 863 | # or a module, and it's been that way for a long time. Whether it's |
|
800 | 864 | # intentional (or sensible), I don't know. In any case, the idea is |
|
801 | 865 | # that if you need to access the built-in namespace directly, you |
|
802 | 866 | # should start with "import __builtin__" (note, no 's') which will |
|
803 | 867 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
804 | 868 | |
|
805 | 869 | # These routines return properly built dicts as needed by the rest of |
|
806 | 870 | # the code, and can also be used by extension writers to generate |
|
807 | 871 | # properly initialized namespaces. |
|
808 |
user_ns, user_global_ns = |
|
|
809 | user_global_ns) | |
|
872 | user_ns, user_global_ns = make_user_namespaces(user_ns, user_global_ns) | |
|
810 | 873 | |
|
811 | 874 | # Assign namespaces |
|
812 | 875 | # This is the namespace where all normal user variables live |
|
813 | 876 | self.user_ns = user_ns |
|
814 | 877 | self.user_global_ns = user_global_ns |
|
815 | 878 | |
|
816 | 879 | # An auxiliary namespace that checks what parts of the user_ns were |
|
817 | 880 | # loaded at startup, so we can list later only variables defined in |
|
818 | 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 | 883 | self.user_config_ns = {} |
|
821 | 884 | |
|
822 | 885 | # A namespace to keep track of internal data structures to prevent |
|
823 | 886 | # them from cluttering user-visible stuff. Will be updated later |
|
824 | 887 | self.internal_ns = {} |
|
825 | 888 | |
|
826 | 889 | # Now that FakeModule produces a real module, we've run into a nasty |
|
827 | 890 | # problem: after script execution (via %run), the module where the user |
|
828 | 891 | # code ran is deleted. Now that this object is a true module (needed |
|
829 | 892 | # so docetst and other tools work correctly), the Python module |
|
830 | 893 | # teardown mechanism runs over it, and sets to None every variable |
|
831 | 894 | # present in that module. Top-level references to objects from the |
|
832 | 895 | # script survive, because the user_ns is updated with them. However, |
|
833 | 896 | # calling functions defined in the script that use other things from |
|
834 | 897 | # the script will fail, because the function's closure had references |
|
835 | 898 | # to the original objects, which are now all None. So we must protect |
|
836 | 899 | # these modules from deletion by keeping a cache. |
|
837 | 900 | # |
|
838 | 901 | # To avoid keeping stale modules around (we only need the one from the |
|
839 | 902 | # last run), we use a dict keyed with the full path to the script, so |
|
840 | 903 | # only the last version of the module is held in the cache. Note, |
|
841 | 904 | # however, that we must cache the module *namespace contents* (their |
|
842 | 905 | # __dict__). Because if we try to cache the actual modules, old ones |
|
843 | 906 | # (uncached) could be destroyed while still holding references (such as |
|
844 | 907 | # those held by GUI objects that tend to be long-lived)> |
|
845 | 908 | # |
|
846 | 909 | # The %reset command will flush this cache. See the cache_main_mod() |
|
847 | 910 | # and clear_main_mod_cache() methods for details on use. |
|
848 | 911 | |
|
849 | 912 | # This is the cache used for 'main' namespaces |
|
850 | 913 | self._main_ns_cache = {} |
|
851 | 914 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
852 | 915 | # copying and clearing for reuse on each %run |
|
853 | 916 | self._user_main_module = FakeModule() |
|
854 | 917 | |
|
855 | 918 | # A table holding all the namespaces IPython deals with, so that |
|
856 | 919 | # introspection facilities can search easily. |
|
857 | 920 | self.ns_table = {'user':user_ns, |
|
858 | 921 | 'user_global':user_global_ns, |
|
859 | 922 | 'internal':self.internal_ns, |
|
860 | 923 | 'builtin':__builtin__.__dict__ |
|
861 | 924 | } |
|
862 | 925 | |
|
863 | 926 | # Similarly, track all namespaces where references can be held and that |
|
864 | 927 | # we can safely clear (so it can NOT include builtin). This one can be |
|
865 | 928 | # a simple list. |
|
866 | 929 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns, |
|
867 | 930 | self.internal_ns, self._main_ns_cache ] |
|
868 | 931 | |
|
869 | 932 | def init_sys_modules(self): |
|
870 | 933 | # We need to insert into sys.modules something that looks like a |
|
871 | 934 | # module but which accesses the IPython namespace, for shelve and |
|
872 | 935 | # pickle to work interactively. Normally they rely on getting |
|
873 | 936 | # everything out of __main__, but for embedding purposes each IPython |
|
874 | 937 | # instance has its own private namespace, so we can't go shoving |
|
875 | 938 | # everything into __main__. |
|
876 | 939 | |
|
877 | 940 | # note, however, that we should only do this for non-embedded |
|
878 | 941 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
879 | 942 | # namespace. Embedded instances, on the other hand, should not do |
|
880 | 943 | # this because they need to manage the user local/global namespaces |
|
881 | 944 | # only, but they live within a 'normal' __main__ (meaning, they |
|
882 | 945 | # shouldn't overtake the execution environment of the script they're |
|
883 | 946 | # embedded in). |
|
884 | 947 | |
|
885 | 948 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
886 | 949 | |
|
887 | 950 | try: |
|
888 | 951 | main_name = self.user_ns['__name__'] |
|
889 | 952 | except KeyError: |
|
890 | 953 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
891 | 954 | else: |
|
892 | 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 | 957 | def init_user_ns(self): |
|
944 | 958 | """Initialize all user-visible namespaces to their minimum defaults. |
|
945 | 959 | |
|
946 | 960 | Certain history lists are also initialized here, as they effectively |
|
947 | 961 | act as user namespaces. |
|
948 | 962 | |
|
949 | 963 | Notes |
|
950 | 964 | ----- |
|
951 | 965 | All data structures here are only filled in, they are NOT reset by this |
|
952 | 966 | method. If they were not empty before, data will simply be added to |
|
953 | 967 | therm. |
|
954 | 968 | """ |
|
955 | # Store myself as the public api!!! | |
|
956 | self.user_ns['get_ipython'] = self.get_ipython | |
|
969 | # This function works in two parts: first we put a few things in | |
|
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 | 983 | # make global variables for user access to the histories |
|
959 |
|
|
|
960 |
|
|
|
961 |
|
|
|
984 | ns['_ih'] = self.input_hist | |
|
985 | ns['_oh'] = self.output_hist | |
|
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 | 996 | # user aliases to input and output histories |
|
964 |
|
|
|
965 |
|
|
|
997 | ns['In'] = self.input_hist | |
|
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 | 1007 | def reset(self): |
|
977 | 1008 | """Clear all internal namespaces. |
|
978 | 1009 | |
|
979 | 1010 | Note that this is much more aggressive than %reset, since it clears |
|
980 | 1011 | fully all namespaces, as well as all input/output lists. |
|
981 | 1012 | """ |
|
982 | 1013 | for ns in self.ns_refs_table: |
|
983 | 1014 | ns.clear() |
|
984 | 1015 | |
|
985 | 1016 | self.alias_manager.clear_aliases() |
|
986 | 1017 | |
|
987 | 1018 | # Clear input and output histories |
|
988 | 1019 | self.input_hist[:] = [] |
|
989 | 1020 | self.input_hist_raw[:] = [] |
|
990 | 1021 | self.output_hist.clear() |
|
991 | 1022 | |
|
992 | 1023 | # Restore the user namespaces to minimal usability |
|
993 | 1024 | self.init_user_ns() |
|
994 | 1025 | |
|
995 | 1026 | # Restore the default and user aliases |
|
996 | 1027 | self.alias_manager.init_aliases() |
|
997 | 1028 | |
|
998 | 1029 | def push(self, variables, interactive=True): |
|
999 | 1030 | """Inject a group of variables into the IPython user namespace. |
|
1000 | 1031 | |
|
1001 | 1032 | Parameters |
|
1002 | 1033 | ---------- |
|
1003 | 1034 | variables : dict, str or list/tuple of str |
|
1004 | 1035 | The variables to inject into the user's namespace. If a dict, |
|
1005 | 1036 | a simple update is done. If a str, the string is assumed to |
|
1006 | 1037 | have variable names separated by spaces. A list/tuple of str |
|
1007 | 1038 | can also be used to give the variable names. If just the variable |
|
1008 | 1039 | names are give (list/tuple/str) then the variable values looked |
|
1009 | 1040 | up in the callers frame. |
|
1010 | 1041 | interactive : bool |
|
1011 | 1042 | If True (default), the variables will be listed with the ``who`` |
|
1012 | 1043 | magic. |
|
1013 | 1044 | """ |
|
1014 | 1045 | vdict = None |
|
1015 | 1046 | |
|
1016 | 1047 | # We need a dict of name/value pairs to do namespace updates. |
|
1017 | 1048 | if isinstance(variables, dict): |
|
1018 | 1049 | vdict = variables |
|
1019 | 1050 | elif isinstance(variables, (basestring, list, tuple)): |
|
1020 | 1051 | if isinstance(variables, basestring): |
|
1021 | 1052 | vlist = variables.split() |
|
1022 | 1053 | else: |
|
1023 | 1054 | vlist = variables |
|
1024 | 1055 | vdict = {} |
|
1025 | 1056 | cf = sys._getframe(1) |
|
1026 | 1057 | for name in vlist: |
|
1027 | 1058 | try: |
|
1028 | 1059 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1029 | 1060 | except: |
|
1030 | 1061 | print ('Could not get variable %s from %s' % |
|
1031 | 1062 | (name,cf.f_code.co_name)) |
|
1032 | 1063 | else: |
|
1033 | 1064 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1034 | 1065 | |
|
1035 | 1066 | # Propagate variables to user namespace |
|
1036 | 1067 | self.user_ns.update(vdict) |
|
1037 | 1068 | |
|
1038 | 1069 | # And configure interactive visibility |
|
1039 | 1070 | config_ns = self.user_config_ns |
|
1040 | 1071 | if interactive: |
|
1041 | 1072 | for name, val in vdict.iteritems(): |
|
1042 | 1073 | config_ns.pop(name, None) |
|
1043 | 1074 | else: |
|
1044 | 1075 | for name,val in vdict.iteritems(): |
|
1045 | 1076 | config_ns[name] = val |
|
1046 | 1077 | |
|
1047 | 1078 | #------------------------------------------------------------------------- |
|
1048 | 1079 | # Things related to history management |
|
1049 | 1080 | #------------------------------------------------------------------------- |
|
1050 | 1081 | |
|
1051 | 1082 | def init_history(self): |
|
1052 | 1083 | # List of input with multi-line handling. |
|
1053 | 1084 | self.input_hist = InputList() |
|
1054 | 1085 | # This one will hold the 'raw' input history, without any |
|
1055 | 1086 | # pre-processing. This will allow users to retrieve the input just as |
|
1056 | 1087 | # it was exactly typed in by the user, with %hist -r. |
|
1057 | 1088 | self.input_hist_raw = InputList() |
|
1058 | 1089 | |
|
1059 | 1090 | # list of visited directories |
|
1060 | 1091 | try: |
|
1061 | 1092 | self.dir_hist = [os.getcwd()] |
|
1062 | 1093 | except OSError: |
|
1063 | 1094 | self.dir_hist = [] |
|
1064 | 1095 | |
|
1065 | 1096 | # dict of output history |
|
1066 | 1097 | self.output_hist = {} |
|
1067 | 1098 | |
|
1068 | 1099 | # Now the history file |
|
1069 | 1100 | if self.profile: |
|
1070 | 1101 | histfname = 'history-%s' % self.profile |
|
1071 | 1102 | else: |
|
1072 | 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 | 1106 | # Fill the history zero entry, user counter starts at 1 |
|
1076 | 1107 | self.input_hist.append('\n') |
|
1077 | 1108 | self.input_hist_raw.append('\n') |
|
1078 | 1109 | |
|
1079 | 1110 | def init_shadow_hist(self): |
|
1080 | 1111 | try: |
|
1081 | self.db = pickleshare.PickleShareDB(self.ipythondir + "/db") | |
|
1112 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
|
1082 | 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 | 1115 | print "Please set HOME environment variable to something that" |
|
1085 | 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 | 1118 | sys.exit() |
|
1088 | 1119 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1089 | 1120 | |
|
1090 | 1121 | def savehist(self): |
|
1091 | 1122 | """Save input history to a file (via readline library).""" |
|
1092 | 1123 | |
|
1093 | if not self.has_readline: | |
|
1094 | return | |
|
1095 | ||
|
1096 | 1124 | try: |
|
1097 | 1125 | self.readline.write_history_file(self.histfile) |
|
1098 | 1126 | except: |
|
1099 | 1127 | print 'Unable to save IPython command history to file: ' + \ |
|
1100 | 1128 | `self.histfile` |
|
1101 | 1129 | |
|
1102 | 1130 | def reloadhist(self): |
|
1103 | 1131 | """Reload the input history from disk file.""" |
|
1104 | 1132 | |
|
1105 | if self.has_readline: | |
|
1106 | try: | |
|
1107 |
|
|
|
1108 | self.readline.read_history_file(self.shell.histfile) | |
|
1109 | except AttributeError: | |
|
1110 | pass | |
|
1133 | try: | |
|
1134 | self.readline.clear_history() | |
|
1135 | self.readline.read_history_file(self.shell.histfile) | |
|
1136 | except AttributeError: | |
|
1137 | pass | |
|
1111 | 1138 | |
|
1112 | 1139 | def history_saving_wrapper(self, func): |
|
1113 | 1140 | """ Wrap func for readline history saving |
|
1114 | 1141 | |
|
1115 | 1142 | Convert func into callable that saves & restores |
|
1116 | 1143 | history around the call """ |
|
1117 | 1144 | |
|
1118 | 1145 | if not self.has_readline: |
|
1119 | 1146 | return func |
|
1120 | 1147 | |
|
1121 | 1148 | def wrapper(): |
|
1122 | 1149 | self.savehist() |
|
1123 | 1150 | try: |
|
1124 | 1151 | func() |
|
1125 | 1152 | finally: |
|
1126 | 1153 | readline.read_history_file(self.histfile) |
|
1127 | 1154 | return wrapper |
|
1128 | 1155 | |
|
1129 | 1156 | #------------------------------------------------------------------------- |
|
1130 | 1157 | # Things related to exception handling and tracebacks (not debugging) |
|
1131 | 1158 | #------------------------------------------------------------------------- |
|
1132 | 1159 | |
|
1133 | 1160 | def init_traceback_handlers(self, custom_exceptions): |
|
1134 | 1161 | # Syntax error handler. |
|
1135 | 1162 | self.SyntaxTB = SyntaxTB(color_scheme='NoColor') |
|
1136 | 1163 | |
|
1137 | 1164 | # The interactive one is initialized with an offset, meaning we always |
|
1138 | 1165 | # want to remove the topmost item in the traceback, which is our own |
|
1139 | 1166 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1140 | 1167 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1141 | 1168 | color_scheme='NoColor', |
|
1142 | 1169 | tb_offset = 1) |
|
1143 | 1170 | |
|
1144 | # IPython itself shouldn't crash. This will produce a detailed | |
|
1145 | # post-mortem if it does. But we only install the crash handler for | |
|
1146 | # non-threaded shells, the threaded ones use a normal verbose reporter | |
|
1147 | # and lose the crash handler. This is because exceptions in the main | |
|
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) | |
|
1171 | # The instance will store a pointer to the system-wide exception hook, | |
|
1172 | # so that runtime code (such as magics) can access it. This is because | |
|
1173 | # during the read-eval loop, it may get temporarily overwritten. | |
|
1174 | self.sys_excepthook = sys.excepthook | |
|
1156 | 1175 | |
|
1157 | 1176 | # and add any custom exception handlers the user may have specified |
|
1158 | 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 | 1179 | def set_custom_exc(self,exc_tuple,handler): |
|
1176 | 1180 | """set_custom_exc(exc_tuple,handler) |
|
1177 | 1181 | |
|
1178 | 1182 | Set a custom exception handler, which will be called if any of the |
|
1179 | 1183 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1180 | 1184 | runcode() method. |
|
1181 | 1185 | |
|
1182 | 1186 | Inputs: |
|
1183 | 1187 | |
|
1184 | 1188 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1185 | 1189 | handler for. It is very important that you use a tuple, and NOT A |
|
1186 | 1190 | LIST here, because of the way Python's except statement works. If |
|
1187 | 1191 | you only want to trap a single exception, use a singleton tuple: |
|
1188 | 1192 | |
|
1189 | 1193 | exc_tuple == (MyCustomException,) |
|
1190 | 1194 | |
|
1191 | 1195 | - handler: this must be defined as a function with the following |
|
1192 | 1196 | basic interface: def my_handler(self,etype,value,tb). |
|
1193 | 1197 | |
|
1194 | 1198 | This will be made into an instance method (via new.instancemethod) |
|
1195 | 1199 | of IPython itself, and it will be called if any of the exceptions |
|
1196 | 1200 | listed in the exc_tuple are caught. If the handler is None, an |
|
1197 | 1201 | internal basic one is used, which just prints basic info. |
|
1198 | 1202 | |
|
1199 | 1203 | WARNING: by putting in your own exception handler into IPython's main |
|
1200 | 1204 | execution loop, you run a very good chance of nasty crashes. This |
|
1201 | 1205 | facility should only be used if you really know what you are doing.""" |
|
1202 | 1206 | |
|
1203 | 1207 | assert type(exc_tuple)==type(()) , \ |
|
1204 | 1208 | "The custom exceptions must be given AS A TUPLE." |
|
1205 | 1209 | |
|
1206 | 1210 | def dummy_handler(self,etype,value,tb): |
|
1207 | 1211 | print '*** Simple custom exception handler ***' |
|
1208 | 1212 | print 'Exception type :',etype |
|
1209 | 1213 | print 'Exception value:',value |
|
1210 | 1214 | print 'Traceback :',tb |
|
1211 | 1215 | print 'Source code :','\n'.join(self.buffer) |
|
1212 | 1216 | |
|
1213 | 1217 | if handler is None: handler = dummy_handler |
|
1214 | 1218 | |
|
1215 | 1219 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1216 | 1220 | self.custom_exceptions = exc_tuple |
|
1217 | 1221 | |
|
1218 | 1222 | def excepthook(self, etype, value, tb): |
|
1219 | 1223 | """One more defense for GUI apps that call sys.excepthook. |
|
1220 | 1224 | |
|
1221 | 1225 | GUI frameworks like wxPython trap exceptions and call |
|
1222 | 1226 | sys.excepthook themselves. I guess this is a feature that |
|
1223 | 1227 | enables them to keep running after exceptions that would |
|
1224 | 1228 | otherwise kill their mainloop. This is a bother for IPython |
|
1225 | 1229 | which excepts to catch all of the program exceptions with a try: |
|
1226 | 1230 | except: statement. |
|
1227 | 1231 | |
|
1228 | 1232 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1229 | 1233 | any app directly invokes sys.excepthook, it will look to the user like |
|
1230 | 1234 | IPython crashed. In order to work around this, we can disable the |
|
1231 | 1235 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1232 | 1236 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1233 | 1237 | call sys.excepthook will generate a regular-looking exception from |
|
1234 | 1238 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1235 | 1239 | crashes. |
|
1236 | 1240 | |
|
1237 | 1241 | This hook should be used sparingly, only in places which are not likely |
|
1238 | 1242 | to be true IPython errors. |
|
1239 | 1243 | """ |
|
1240 | 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 | 1248 | """Display the exception that just occurred. |
|
1244 | 1249 | |
|
1245 | 1250 | If nothing is known about the exception, this is the method which |
|
1246 | 1251 | should be used throughout the code for presenting user tracebacks, |
|
1247 | 1252 | rather than directly invoking the InteractiveTB object. |
|
1248 | 1253 | |
|
1249 | 1254 | A specific showsyntaxerror() also exists, but this method can take |
|
1250 | 1255 | care of calling it if needed, so unless you are explicitly catching a |
|
1251 | 1256 | SyntaxError exception, don't try to analyze the stack manually and |
|
1252 | 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 | 1259 | try: |
|
1259 | 1260 | if exc_tuple is None: |
|
1260 | 1261 | etype, value, tb = sys.exc_info() |
|
1261 | 1262 | else: |
|
1262 | 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 | 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 | 1276 | self.showsyntaxerror(filename) |
|
1266 | 1277 | elif etype is UsageError: |
|
1267 | 1278 | print "UsageError:", value |
|
1268 | 1279 | else: |
|
1269 | 1280 | # WARNING: these variables are somewhat deprecated and not |
|
1270 | 1281 | # necessarily safe to use in a threaded environment, but tools |
|
1271 | 1282 | # like pdb depend on their existence, so let's set them. If we |
|
1272 | 1283 | # find problems in the field, we'll need to revisit their use. |
|
1273 | 1284 | sys.last_type = etype |
|
1274 | 1285 | sys.last_value = value |
|
1275 | 1286 | sys.last_traceback = tb |
|
1276 | 1287 | |
|
1277 | 1288 | if etype in self.custom_exceptions: |
|
1278 | 1289 | self.CustomTB(etype,value,tb) |
|
1279 | 1290 | else: |
|
1280 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) | |
|
1281 | if self.InteractiveTB.call_pdb and self.has_readline: | |
|
1282 |
|
|
|
1283 |
|
|
|
1291 | if exception_only: | |
|
1292 | m = ('An exception has occurred, use %tb to see the ' | |
|
1293 | 'full traceback.') | |
|
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 | 1302 | except KeyboardInterrupt: |
|
1285 | self.write("\nKeyboardInterrupt\n") | |
|
1303 | self.write("\nKeyboardInterrupt\n") | |
|
1304 | ||
|
1286 | 1305 | |
|
1287 | 1306 | def showsyntaxerror(self, filename=None): |
|
1288 | 1307 | """Display the syntax error that just occurred. |
|
1289 | 1308 | |
|
1290 | 1309 | This doesn't display a stack trace because there isn't one. |
|
1291 | 1310 | |
|
1292 | 1311 | If a filename is given, it is stuffed in the exception instead |
|
1293 | 1312 | of what was there before (because Python's parser always uses |
|
1294 | 1313 | "<string>" when reading from a string). |
|
1295 | 1314 | """ |
|
1296 | 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 | 1318 | sys.last_type = etype |
|
1300 | 1319 | sys.last_value = value |
|
1301 | 1320 | sys.last_traceback = last_traceback |
|
1302 | 1321 | |
|
1303 | 1322 | if filename and etype is SyntaxError: |
|
1304 | 1323 | # Work hard to stuff the correct filename in the exception |
|
1305 | 1324 | try: |
|
1306 | 1325 | msg, (dummy_filename, lineno, offset, line) = value |
|
1307 | 1326 | except: |
|
1308 | 1327 | # Not the format we expect; leave it alone |
|
1309 | 1328 | pass |
|
1310 | 1329 | else: |
|
1311 | 1330 | # Stuff in the right filename |
|
1312 | 1331 | try: |
|
1313 | 1332 | # Assume SyntaxError is a class exception |
|
1314 | 1333 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1315 | 1334 | except: |
|
1316 | 1335 | # If that failed, assume SyntaxError is a string |
|
1317 | 1336 | value = msg, (filename, lineno, offset, line) |
|
1318 | 1337 | self.SyntaxTB(etype,value,[]) |
|
1319 | 1338 | |
|
1320 | 1339 | def edit_syntax_error(self): |
|
1321 | 1340 | """The bottom half of the syntax error handler called in the main loop. |
|
1322 | 1341 | |
|
1323 | 1342 | Loop until syntax error is fixed or user cancels. |
|
1324 | 1343 | """ |
|
1325 | 1344 | |
|
1326 | 1345 | while self.SyntaxTB.last_syntax_error: |
|
1327 | 1346 | # copy and clear last_syntax_error |
|
1328 | 1347 | err = self.SyntaxTB.clear_err_state() |
|
1329 | 1348 | if not self._should_recompile(err): |
|
1330 | 1349 | return |
|
1331 | 1350 | try: |
|
1332 | 1351 | # may set last_syntax_error again if a SyntaxError is raised |
|
1333 | 1352 | self.safe_execfile(err.filename,self.user_ns) |
|
1334 | 1353 | except: |
|
1335 | 1354 | self.showtraceback() |
|
1336 | 1355 | else: |
|
1337 | 1356 | try: |
|
1338 | 1357 | f = file(err.filename) |
|
1339 | 1358 | try: |
|
1340 | 1359 | # This should be inside a display_trap block and I |
|
1341 | 1360 | # think it is. |
|
1342 | 1361 | sys.displayhook(f.read()) |
|
1343 | 1362 | finally: |
|
1344 | 1363 | f.close() |
|
1345 | 1364 | except: |
|
1346 | 1365 | self.showtraceback() |
|
1347 | 1366 | |
|
1348 | 1367 | def _should_recompile(self,e): |
|
1349 | 1368 | """Utility routine for edit_syntax_error""" |
|
1350 | 1369 | |
|
1351 | 1370 | if e.filename in ('<ipython console>','<input>','<string>', |
|
1352 | 1371 | '<console>','<BackgroundJob compilation>', |
|
1353 | 1372 | None): |
|
1354 | 1373 | |
|
1355 | 1374 | return False |
|
1356 | 1375 | try: |
|
1357 | 1376 | if (self.autoedit_syntax and |
|
1358 | 1377 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
1359 | 1378 | '[Y/n] ','y')): |
|
1360 | 1379 | return False |
|
1361 | 1380 | except EOFError: |
|
1362 | 1381 | return False |
|
1363 | 1382 | |
|
1364 | 1383 | def int0(x): |
|
1365 | 1384 | try: |
|
1366 | 1385 | return int(x) |
|
1367 | 1386 | except TypeError: |
|
1368 | 1387 | return 0 |
|
1369 | 1388 | # always pass integer line and offset values to editor hook |
|
1370 | 1389 | try: |
|
1371 | 1390 | self.hooks.fix_error_editor(e.filename, |
|
1372 | 1391 | int0(e.lineno),int0(e.offset),e.msg) |
|
1373 | 1392 | except TryNext: |
|
1374 | 1393 | warn('Could not open editor') |
|
1375 | 1394 | return False |
|
1376 | 1395 | return True |
|
1377 | 1396 | |
|
1378 | 1397 | #------------------------------------------------------------------------- |
|
1379 | 1398 | # Things related to tab completion |
|
1380 | 1399 | #------------------------------------------------------------------------- |
|
1381 | 1400 | |
|
1382 | 1401 | def complete(self, text): |
|
1383 | 1402 | """Return a sorted list of all possible completions on text. |
|
1384 | 1403 | |
|
1385 | 1404 | Inputs: |
|
1386 | 1405 | |
|
1387 | 1406 | - text: a string of text to be completed on. |
|
1388 | 1407 | |
|
1389 | 1408 | This is a wrapper around the completion mechanism, similar to what |
|
1390 | 1409 | readline does at the command line when the TAB key is hit. By |
|
1391 | 1410 | exposing it as a method, it can be used by other non-readline |
|
1392 | 1411 | environments (such as GUIs) for text completion. |
|
1393 | 1412 | |
|
1394 | 1413 | Simple usage example: |
|
1395 | 1414 | |
|
1396 | 1415 | In [7]: x = 'hello' |
|
1397 | 1416 | |
|
1398 | 1417 | In [8]: x |
|
1399 | 1418 | Out[8]: 'hello' |
|
1400 | 1419 | |
|
1401 | 1420 | In [9]: print x |
|
1402 | 1421 | hello |
|
1403 | 1422 | |
|
1404 | 1423 | In [10]: _ip.complete('x.l') |
|
1405 | 1424 | Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] |
|
1406 | 1425 | """ |
|
1407 | 1426 | |
|
1408 | 1427 | # Inject names into __builtin__ so we can complete on the added names. |
|
1409 | 1428 | with self.builtin_trap: |
|
1410 | 1429 | complete = self.Completer.complete |
|
1411 | 1430 | state = 0 |
|
1412 | 1431 | # use a dict so we get unique keys, since ipyhton's multiple |
|
1413 | 1432 | # completers can return duplicates. When we make 2.4 a requirement, |
|
1414 | 1433 | # start using sets instead, which are faster. |
|
1415 | 1434 | comps = {} |
|
1416 | 1435 | while True: |
|
1417 | 1436 | newcomp = complete(text,state,line_buffer=text) |
|
1418 | 1437 | if newcomp is None: |
|
1419 | 1438 | break |
|
1420 | 1439 | comps[newcomp] = 1 |
|
1421 | 1440 | state += 1 |
|
1422 | 1441 | outcomps = comps.keys() |
|
1423 | 1442 | outcomps.sort() |
|
1424 | 1443 | #print "T:",text,"OC:",outcomps # dbg |
|
1425 | 1444 | #print "vars:",self.user_ns.keys() |
|
1426 | 1445 | return outcomps |
|
1427 | 1446 | |
|
1428 | 1447 | def set_custom_completer(self,completer,pos=0): |
|
1429 |
""" |
|
|
1430 | ||
|
1431 | Adds a new custom completer function. | |
|
1448 | """Adds a new custom completer function. | |
|
1432 | 1449 | |
|
1433 | 1450 | The position argument (defaults to 0) is the index in the completers |
|
1434 | 1451 | list where you want the completer to be inserted.""" |
|
1435 | 1452 | |
|
1436 | 1453 | newcomp = new.instancemethod(completer,self.Completer, |
|
1437 | 1454 | self.Completer.__class__) |
|
1438 | 1455 | self.Completer.matchers.insert(pos,newcomp) |
|
1439 | 1456 | |
|
1440 | 1457 | def set_completer(self): |
|
1441 |
""" |
|
|
1458 | """Reset readline's completer to be our own.""" | |
|
1442 | 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 | 1471 | # Things related to readline |
|
1446 | 1472 | #------------------------------------------------------------------------- |
|
1447 | 1473 | |
|
1448 | 1474 | def init_readline(self): |
|
1449 | 1475 | """Command history completion/saving/reloading.""" |
|
1450 | 1476 | |
|
1477 | if self.readline_use: | |
|
1478 | import IPython.utils.rlineimpl as readline | |
|
1479 | ||
|
1451 | 1480 | self.rl_next_input = None |
|
1452 | 1481 | self.rl_do_indent = False |
|
1453 | 1482 | |
|
1454 | if not self.readline_use: | |
|
1455 | return | |
|
1456 | ||
|
1457 | import IPython.utils.rlineimpl as readline | |
|
1458 | ||
|
1459 | if not readline.have_readline: | |
|
1460 | self.has_readline = 0 | |
|
1483 | if not self.readline_use or not readline.have_readline: | |
|
1484 | self.has_readline = False | |
|
1461 | 1485 | self.readline = None |
|
1462 | # no point in bugging windows users with this every time: | |
|
1463 | warn('Readline services not available on this platform.') | |
|
1486 | # Set a number of methods that depend on readline to be no-op | |
|
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 | 1493 | else: |
|
1494 | self.has_readline = True | |
|
1495 | self.readline = readline | |
|
1465 | 1496 | sys.modules['readline'] = readline |
|
1466 | 1497 | import atexit |
|
1467 | 1498 | from IPython.core.completer import IPCompleter |
|
1468 | 1499 | self.Completer = IPCompleter(self, |
|
1469 | 1500 | self.user_ns, |
|
1470 | 1501 | self.user_global_ns, |
|
1471 | 1502 | self.readline_omit__names, |
|
1472 | 1503 | self.alias_manager.alias_table) |
|
1473 | 1504 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1474 | 1505 | self.strdispatchers['complete_command'] = sdisp |
|
1475 | 1506 | self.Completer.custom_completers = sdisp |
|
1476 | 1507 | # Platform-specific configuration |
|
1477 | 1508 | if os.name == 'nt': |
|
1478 | 1509 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1479 | 1510 | else: |
|
1480 | 1511 | self.readline_startup_hook = readline.set_startup_hook |
|
1481 | 1512 | |
|
1482 | 1513 | # Load user's initrc file (readline config) |
|
1483 | 1514 | # Or if libedit is used, load editrc. |
|
1484 | 1515 | inputrc_name = os.environ.get('INPUTRC') |
|
1485 | 1516 | if inputrc_name is None: |
|
1486 | 1517 | home_dir = get_home_dir() |
|
1487 | 1518 | if home_dir is not None: |
|
1488 | 1519 | inputrc_name = '.inputrc' |
|
1489 | 1520 | if readline.uses_libedit: |
|
1490 | 1521 | inputrc_name = '.editrc' |
|
1491 | 1522 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1492 | 1523 | if os.path.isfile(inputrc_name): |
|
1493 | 1524 | try: |
|
1494 | 1525 | readline.read_init_file(inputrc_name) |
|
1495 | 1526 | except: |
|
1496 | 1527 | warn('Problems reading readline initialization file <%s>' |
|
1497 | 1528 | % inputrc_name) |
|
1498 | 1529 | |
|
1499 | self.has_readline = 1 | |
|
1500 | self.readline = readline | |
|
1501 | 1530 | # save this in sys so embedded copies can restore it properly |
|
1502 | 1531 | sys.ipcompleter = self.Completer.complete |
|
1503 | 1532 | self.set_completer() |
|
1504 | 1533 | |
|
1505 | 1534 | # Configure readline according to user's prefs |
|
1506 | 1535 | # This is only done if GNU readline is being used. If libedit |
|
1507 | 1536 | # is being used (as on Leopard) the readline config is |
|
1508 | 1537 | # not run as the syntax for libedit is different. |
|
1509 | 1538 | if not readline.uses_libedit: |
|
1510 | 1539 | for rlcommand in self.readline_parse_and_bind: |
|
1511 | 1540 | #print "loading rl:",rlcommand # dbg |
|
1512 | 1541 | readline.parse_and_bind(rlcommand) |
|
1513 | 1542 | |
|
1514 | 1543 | # Remove some chars from the delimiters list. If we encounter |
|
1515 | 1544 | # unicode chars, discard them. |
|
1516 | 1545 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1517 | 1546 | delims = delims.translate(string._idmap, |
|
1518 | 1547 | self.readline_remove_delims) |
|
1519 | 1548 | readline.set_completer_delims(delims) |
|
1520 | 1549 | # otherwise we end up with a monster history after a while: |
|
1521 | 1550 | readline.set_history_length(1000) |
|
1522 | 1551 | try: |
|
1523 | 1552 | #print '*** Reading readline history' # dbg |
|
1524 | 1553 | readline.read_history_file(self.histfile) |
|
1525 | 1554 | except IOError: |
|
1526 | 1555 | pass # It doesn't exist yet. |
|
1527 | 1556 | |
|
1528 | 1557 | atexit.register(self.atexit_operations) |
|
1529 | 1558 | del atexit |
|
1530 | 1559 | |
|
1531 | 1560 | # Configure auto-indent for all platforms |
|
1532 | 1561 | self.set_autoindent(self.autoindent) |
|
1533 | 1562 | |
|
1534 | 1563 | def set_next_input(self, s): |
|
1535 | 1564 | """ Sets the 'default' input string for the next command line. |
|
1536 | 1565 | |
|
1537 | 1566 | Requires readline. |
|
1538 | 1567 | |
|
1539 | 1568 | Example: |
|
1540 | 1569 | |
|
1541 | 1570 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1542 | 1571 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1543 | 1572 | """ |
|
1544 | 1573 | |
|
1545 | 1574 | self.rl_next_input = s |
|
1546 | 1575 | |
|
1547 | 1576 | def pre_readline(self): |
|
1548 | 1577 | """readline hook to be used at the start of each line. |
|
1549 | 1578 | |
|
1550 | 1579 | Currently it handles auto-indent only.""" |
|
1551 | 1580 | |
|
1552 | 1581 | #debugx('self.indent_current_nsp','pre_readline:') |
|
1553 | 1582 | |
|
1554 | 1583 | if self.rl_do_indent: |
|
1555 | 1584 | self.readline.insert_text(self._indent_current_str()) |
|
1556 | 1585 | if self.rl_next_input is not None: |
|
1557 | 1586 | self.readline.insert_text(self.rl_next_input) |
|
1558 | 1587 | self.rl_next_input = None |
|
1559 | 1588 | |
|
1560 | 1589 | def _indent_current_str(self): |
|
1561 | 1590 | """return the current level of indentation as a string""" |
|
1562 | 1591 | return self.indent_current_nsp * ' ' |
|
1563 | 1592 | |
|
1564 | 1593 | #------------------------------------------------------------------------- |
|
1565 | 1594 | # Things related to magics |
|
1566 | 1595 | #------------------------------------------------------------------------- |
|
1567 | 1596 | |
|
1568 | 1597 | def init_magics(self): |
|
1569 | 1598 | # Set user colors (don't do it in the constructor above so that it |
|
1570 | 1599 | # doesn't crash if colors option is invalid) |
|
1571 | 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 | 1605 | def magic(self,arg_s): |
|
1574 | 1606 | """Call a magic function by name. |
|
1575 | 1607 | |
|
1576 | 1608 | Input: a string containing the name of the magic function to call and any |
|
1577 | 1609 | additional arguments to be passed to the magic. |
|
1578 | 1610 | |
|
1579 | 1611 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1580 | 1612 | prompt: |
|
1581 | 1613 | |
|
1582 | 1614 | In[1]: %name -opt foo bar |
|
1583 | 1615 | |
|
1584 | 1616 | To call a magic without arguments, simply use magic('name'). |
|
1585 | 1617 | |
|
1586 | 1618 | This provides a proper Python function to call IPython's magics in any |
|
1587 | 1619 | valid Python code you can type at the interpreter, including loops and |
|
1588 | 1620 | compound statements. |
|
1589 | 1621 | """ |
|
1590 | ||
|
1591 | 1622 | args = arg_s.split(' ',1) |
|
1592 | 1623 | magic_name = args[0] |
|
1593 | 1624 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1594 | 1625 | |
|
1595 | 1626 | try: |
|
1596 | 1627 | magic_args = args[1] |
|
1597 | 1628 | except IndexError: |
|
1598 | 1629 | magic_args = '' |
|
1599 | 1630 | fn = getattr(self,'magic_'+magic_name,None) |
|
1600 | 1631 | if fn is None: |
|
1601 | 1632 | error("Magic function `%s` not found." % magic_name) |
|
1602 | 1633 | else: |
|
1603 | 1634 | magic_args = self.var_expand(magic_args,1) |
|
1604 | 1635 | with nested(self.builtin_trap,): |
|
1605 | 1636 | result = fn(magic_args) |
|
1606 | 1637 | return result |
|
1607 | 1638 | |
|
1608 | 1639 | def define_magic(self, magicname, func): |
|
1609 | 1640 | """Expose own function as magic function for ipython |
|
1610 | 1641 | |
|
1611 | 1642 | def foo_impl(self,parameter_s=''): |
|
1612 | 1643 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1613 | 1644 | print 'Magic function. Passed parameter is between < >:' |
|
1614 | 1645 | print '<%s>' % parameter_s |
|
1615 | 1646 | print 'The self object is:',self |
|
1616 | 1647 | |
|
1617 | 1648 | self.define_magic('foo',foo_impl) |
|
1618 | 1649 | """ |
|
1619 | 1650 | |
|
1620 | 1651 | import new |
|
1621 | 1652 | im = new.instancemethod(func,self, self.__class__) |
|
1622 | 1653 | old = getattr(self, "magic_" + magicname, None) |
|
1623 | 1654 | setattr(self, "magic_" + magicname, im) |
|
1624 | 1655 | return old |
|
1625 | 1656 | |
|
1626 | 1657 | #------------------------------------------------------------------------- |
|
1627 | 1658 | # Things related to macros |
|
1628 | 1659 | #------------------------------------------------------------------------- |
|
1629 | 1660 | |
|
1630 | 1661 | def define_macro(self, name, themacro): |
|
1631 | 1662 | """Define a new macro |
|
1632 | 1663 | |
|
1633 | 1664 | Parameters |
|
1634 | 1665 | ---------- |
|
1635 | 1666 | name : str |
|
1636 | 1667 | The name of the macro. |
|
1637 | 1668 | themacro : str or Macro |
|
1638 | 1669 | The action to do upon invoking the macro. If a string, a new |
|
1639 | 1670 | Macro object is created by passing the string to it. |
|
1640 | 1671 | """ |
|
1641 | 1672 | |
|
1642 | 1673 | from IPython.core import macro |
|
1643 | 1674 | |
|
1644 | 1675 | if isinstance(themacro, basestring): |
|
1645 | 1676 | themacro = macro.Macro(themacro) |
|
1646 | 1677 | if not isinstance(themacro, macro.Macro): |
|
1647 | 1678 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1648 | 1679 | self.user_ns[name] = themacro |
|
1649 | 1680 | |
|
1650 | 1681 | #------------------------------------------------------------------------- |
|
1651 | 1682 | # Things related to the running of system commands |
|
1652 | 1683 | #------------------------------------------------------------------------- |
|
1653 | 1684 | |
|
1654 | 1685 | def system(self, cmd): |
|
1655 | 1686 | """Make a system call, using IPython.""" |
|
1656 | 1687 | return self.hooks.shell_hook(self.var_expand(cmd, depth=2)) |
|
1657 | 1688 | |
|
1658 | 1689 | #------------------------------------------------------------------------- |
|
1659 | 1690 | # Things related to aliases |
|
1660 | 1691 | #------------------------------------------------------------------------- |
|
1661 | 1692 | |
|
1662 | 1693 | def init_alias(self): |
|
1663 | 1694 | self.alias_manager = AliasManager(self, config=self.config) |
|
1664 | 1695 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1665 | 1696 | |
|
1666 | 1697 | #------------------------------------------------------------------------- |
|
1667 | 1698 | # Things related to the running of code |
|
1668 | 1699 | #------------------------------------------------------------------------- |
|
1669 | 1700 | |
|
1670 | 1701 | def ex(self, cmd): |
|
1671 | 1702 | """Execute a normal python statement in user namespace.""" |
|
1672 | 1703 | with nested(self.builtin_trap,): |
|
1673 | 1704 | exec cmd in self.user_global_ns, self.user_ns |
|
1674 | 1705 | |
|
1675 | 1706 | def ev(self, expr): |
|
1676 | 1707 | """Evaluate python expression expr in user namespace. |
|
1677 | 1708 | |
|
1678 | 1709 | Returns the result of evaluation |
|
1679 | 1710 | """ |
|
1680 | 1711 | with nested(self.builtin_trap,): |
|
1681 | 1712 | return eval(expr, self.user_global_ns, self.user_ns) |
|
1682 | 1713 | |
|
1683 | 1714 | def mainloop(self, display_banner=None): |
|
1684 | 1715 | """Start the mainloop. |
|
1685 | 1716 | |
|
1686 | 1717 | If an optional banner argument is given, it will override the |
|
1687 | 1718 | internally created default banner. |
|
1688 | 1719 | """ |
|
1689 | 1720 | |
|
1690 | 1721 | with nested(self.builtin_trap, self.display_trap): |
|
1691 | 1722 | |
|
1692 | 1723 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
1693 | 1724 | # ensure that it's in sync |
|
1694 | 1725 | if len(self.input_hist) != len (self.input_hist_raw): |
|
1695 | 1726 | self.input_hist_raw = InputList(self.input_hist) |
|
1696 | 1727 | |
|
1697 | 1728 | while 1: |
|
1698 | 1729 | try: |
|
1699 | 1730 | self.interact(display_banner=display_banner) |
|
1700 | 1731 | #self.interact_with_readline() |
|
1701 | 1732 | # XXX for testing of a readline-decoupled repl loop, call |
|
1702 | 1733 | # interact_with_readline above |
|
1703 | 1734 | break |
|
1704 | 1735 | except KeyboardInterrupt: |
|
1705 | 1736 | # this should not be necessary, but KeyboardInterrupt |
|
1706 | 1737 | # handling seems rather unpredictable... |
|
1707 | 1738 | self.write("\nKeyboardInterrupt in interact()\n") |
|
1708 | 1739 | |
|
1709 | 1740 | def interact_prompt(self): |
|
1710 | 1741 | """ Print the prompt (in read-eval-print loop) |
|
1711 | 1742 | |
|
1712 | 1743 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1713 | 1744 | used in standard IPython flow. |
|
1714 | 1745 | """ |
|
1715 | 1746 | if self.more: |
|
1716 | 1747 | try: |
|
1717 | 1748 | prompt = self.hooks.generate_prompt(True) |
|
1718 | 1749 | except: |
|
1719 | 1750 | self.showtraceback() |
|
1720 | 1751 | if self.autoindent: |
|
1721 | 1752 | self.rl_do_indent = True |
|
1722 | 1753 | |
|
1723 | 1754 | else: |
|
1724 | 1755 | try: |
|
1725 | 1756 | prompt = self.hooks.generate_prompt(False) |
|
1726 | 1757 | except: |
|
1727 | 1758 | self.showtraceback() |
|
1728 | 1759 | self.write(prompt) |
|
1729 | 1760 | |
|
1730 | 1761 | def interact_handle_input(self,line): |
|
1731 | 1762 | """ Handle the input line (in read-eval-print loop) |
|
1732 | 1763 | |
|
1733 | 1764 | Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
1734 | 1765 | used in standard IPython flow. |
|
1735 | 1766 | """ |
|
1736 | 1767 | if line.lstrip() == line: |
|
1737 | 1768 | self.shadowhist.add(line.strip()) |
|
1738 | 1769 | lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
1739 | 1770 | |
|
1740 | 1771 | if line.strip(): |
|
1741 | 1772 | if self.more: |
|
1742 | 1773 | self.input_hist_raw[-1] += '%s\n' % line |
|
1743 | 1774 | else: |
|
1744 | 1775 | self.input_hist_raw.append('%s\n' % line) |
|
1745 | 1776 | |
|
1746 | 1777 | |
|
1747 | 1778 | self.more = self.push_line(lineout) |
|
1748 | 1779 | if (self.SyntaxTB.last_syntax_error and |
|
1749 | 1780 | self.autoedit_syntax): |
|
1750 | 1781 | self.edit_syntax_error() |
|
1751 | 1782 | |
|
1752 | 1783 | def interact_with_readline(self): |
|
1753 | 1784 | """ Demo of using interact_handle_input, interact_prompt |
|
1754 | 1785 | |
|
1755 | 1786 | This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
1756 | 1787 | it should work like this. |
|
1757 | 1788 | """ |
|
1758 | 1789 | self.readline_startup_hook(self.pre_readline) |
|
1759 | 1790 | while not self.exit_now: |
|
1760 | 1791 | self.interact_prompt() |
|
1761 | 1792 | if self.more: |
|
1762 | 1793 | self.rl_do_indent = True |
|
1763 | 1794 | else: |
|
1764 | 1795 | self.rl_do_indent = False |
|
1765 | 1796 | line = raw_input_original().decode(self.stdin_encoding) |
|
1766 | 1797 | self.interact_handle_input(line) |
|
1767 | 1798 | |
|
1768 | 1799 | def interact(self, display_banner=None): |
|
1769 | 1800 | """Closely emulate the interactive Python console.""" |
|
1770 | 1801 | |
|
1771 | 1802 | # batch run -> do not interact |
|
1772 | 1803 | if self.exit_now: |
|
1773 | 1804 | return |
|
1774 | 1805 | |
|
1775 | 1806 | if display_banner is None: |
|
1776 | 1807 | display_banner = self.display_banner |
|
1777 | 1808 | if display_banner: |
|
1778 | 1809 | self.show_banner() |
|
1779 | 1810 | |
|
1780 | 1811 | more = 0 |
|
1781 | 1812 | |
|
1782 | 1813 | # Mark activity in the builtins |
|
1783 | 1814 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
1784 | 1815 | |
|
1785 | 1816 | if self.has_readline: |
|
1786 | 1817 | self.readline_startup_hook(self.pre_readline) |
|
1787 | 1818 | # exit_now is set by a call to %Exit or %Quit, through the |
|
1788 | 1819 | # ask_exit callback. |
|
1789 | 1820 | |
|
1790 | 1821 | while not self.exit_now: |
|
1791 | 1822 | self.hooks.pre_prompt_hook() |
|
1792 | 1823 | if more: |
|
1793 | 1824 | try: |
|
1794 | 1825 | prompt = self.hooks.generate_prompt(True) |
|
1795 | 1826 | except: |
|
1796 | 1827 | self.showtraceback() |
|
1797 | 1828 | if self.autoindent: |
|
1798 | 1829 | self.rl_do_indent = True |
|
1799 | 1830 | |
|
1800 | 1831 | else: |
|
1801 | 1832 | try: |
|
1802 | 1833 | prompt = self.hooks.generate_prompt(False) |
|
1803 | 1834 | except: |
|
1804 | 1835 | self.showtraceback() |
|
1805 | 1836 | try: |
|
1806 | 1837 | line = self.raw_input(prompt, more) |
|
1807 | 1838 | if self.exit_now: |
|
1808 | 1839 | # quick exit on sys.std[in|out] close |
|
1809 | 1840 | break |
|
1810 | 1841 | if self.autoindent: |
|
1811 | 1842 | self.rl_do_indent = False |
|
1812 | 1843 | |
|
1813 | 1844 | except KeyboardInterrupt: |
|
1814 | 1845 | #double-guard against keyboardinterrupts during kbdint handling |
|
1815 | 1846 | try: |
|
1816 | 1847 | self.write('\nKeyboardInterrupt\n') |
|
1817 | 1848 | self.resetbuffer() |
|
1818 | 1849 | # keep cache in sync with the prompt counter: |
|
1819 | 1850 | self.outputcache.prompt_count -= 1 |
|
1820 | 1851 | |
|
1821 | 1852 | if self.autoindent: |
|
1822 | 1853 | self.indent_current_nsp = 0 |
|
1823 | 1854 | more = 0 |
|
1824 | 1855 | except KeyboardInterrupt: |
|
1825 | 1856 | pass |
|
1826 | 1857 | except EOFError: |
|
1827 | 1858 | if self.autoindent: |
|
1828 | 1859 | self.rl_do_indent = False |
|
1829 |
self.readline |
|
|
1860 | if self.has_readline: | |
|
1861 | self.readline_startup_hook(None) | |
|
1830 | 1862 | self.write('\n') |
|
1831 | 1863 | self.exit() |
|
1832 | 1864 | except bdb.BdbQuit: |
|
1833 | 1865 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
1834 | 1866 | 'Because of how pdb handles the stack, it is impossible\n' |
|
1835 | 1867 | 'for IPython to properly format this particular exception.\n' |
|
1836 | 1868 | 'IPython will resume normal operation.') |
|
1837 | 1869 | except: |
|
1838 | 1870 | # exceptions here are VERY RARE, but they can be triggered |
|
1839 | 1871 | # asynchronously by signal handlers, for example. |
|
1840 | 1872 | self.showtraceback() |
|
1841 | 1873 | else: |
|
1842 | 1874 | more = self.push_line(line) |
|
1843 | 1875 | if (self.SyntaxTB.last_syntax_error and |
|
1844 | 1876 | self.autoedit_syntax): |
|
1845 | 1877 | self.edit_syntax_error() |
|
1846 | ||
|
1878 | ||
|
1847 | 1879 | # We are off again... |
|
1848 | 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 | 1885 | def safe_execfile(self, fname, *where, **kw): |
|
1851 | 1886 | """A safe version of the builtin execfile(). |
|
1852 | 1887 | |
|
1853 | 1888 | This version will never throw an exception, but instead print |
|
1854 | 1889 | helpful error messages to the screen. This only works on pure |
|
1855 | 1890 | Python files with the .py extension. |
|
1856 | 1891 | |
|
1857 | 1892 | Parameters |
|
1858 | 1893 | ---------- |
|
1859 | 1894 | fname : string |
|
1860 | 1895 | The name of the file to be executed. |
|
1861 | 1896 | where : tuple |
|
1862 | 1897 | One or two namespaces, passed to execfile() as (globals,locals). |
|
1863 | 1898 | If only one is given, it is passed as both. |
|
1864 | 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 | 1903 | kw.setdefault('exit_ignore', False) |
|
1868 | 1904 | |
|
1869 | 1905 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1870 | 1906 | |
|
1871 | 1907 | # Make sure we have a .py file |
|
1872 | 1908 | if not fname.endswith('.py'): |
|
1873 | 1909 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1874 | 1910 | |
|
1875 | 1911 | # Make sure we can open the file |
|
1876 | 1912 | try: |
|
1877 | 1913 | with open(fname) as thefile: |
|
1878 | 1914 | pass |
|
1879 | 1915 | except: |
|
1880 | 1916 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1881 | 1917 | return |
|
1882 | 1918 | |
|
1883 | 1919 | # Find things also in current directory. This is needed to mimic the |
|
1884 | 1920 | # behavior of running a script from the system command line, where |
|
1885 | 1921 | # Python inserts the script's directory into sys.path |
|
1886 | 1922 | dname = os.path.dirname(fname) |
|
1887 | 1923 | |
|
1888 | 1924 | with prepended_to_syspath(dname): |
|
1889 | 1925 | try: |
|
1890 | if sys.platform == 'win32' and sys.version_info < (2,5,1): | |
|
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) | |
|
1926 | execfile(fname,*where) | |
|
1908 | 1927 | except SystemExit, status: |
|
1909 | # Code that correctly sets the exit status flag to success (0) | |
|
1910 |
# |
|
|
1911 | # sys.exit() does NOT set the message to 0 (it's empty) so that | |
|
1912 | # will still get a traceback. Note that the structure of the | |
|
1913 | # SystemExit exception changed between Python 2.4 and 2.5, so | |
|
1914 | # the checks must be done in a version-dependent way. | |
|
1915 |
|
|
|
1916 | if status.message!=0 and not kw['exit_ignore']: | |
|
1917 | show = True | |
|
1918 | if show: | |
|
1919 | self.showtraceback() | |
|
1920 | warn('Failure executing file: <%s>' % fname) | |
|
1928 | # If the call was made with 0 or None exit status (sys.exit(0) | |
|
1929 | # or sys.exit() ), don't bother showing a traceback, as both of | |
|
1930 | # these are considered normal by the OS: | |
|
1931 | # > python -c'import sys;sys.exit(0)'; echo $? | |
|
1932 | # 0 | |
|
1933 | # > python -c'import sys;sys.exit()'; echo $? | |
|
1934 | # 0 | |
|
1935 | # For other exit status, we show the exception unless | |
|
1936 | # explicitly silenced, but only in short form. | |
|
1937 | if status.code not in (0, None) and not kw['exit_ignore']: | |
|
1938 | self.showtraceback(exception_only=True) | |
|
1921 | 1939 | except: |
|
1922 | 1940 | self.showtraceback() |
|
1923 | warn('Failure executing file: <%s>' % fname) | |
|
1924 | 1941 | |
|
1925 | 1942 | def safe_execfile_ipy(self, fname): |
|
1926 | 1943 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
1927 | 1944 | |
|
1928 | 1945 | Parameters |
|
1929 | 1946 | ---------- |
|
1930 | 1947 | fname : str |
|
1931 | 1948 | The name of the file to execute. The filename must have a |
|
1932 | 1949 | .ipy extension. |
|
1933 | 1950 | """ |
|
1934 | 1951 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
1935 | 1952 | |
|
1936 | 1953 | # Make sure we have a .py file |
|
1937 | 1954 | if not fname.endswith('.ipy'): |
|
1938 | 1955 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
1939 | 1956 | |
|
1940 | 1957 | # Make sure we can open the file |
|
1941 | 1958 | try: |
|
1942 | 1959 | with open(fname) as thefile: |
|
1943 | 1960 | pass |
|
1944 | 1961 | except: |
|
1945 | 1962 | warn('Could not open file <%s> for safe execution.' % fname) |
|
1946 | 1963 | return |
|
1947 | 1964 | |
|
1948 | 1965 | # Find things also in current directory. This is needed to mimic the |
|
1949 | 1966 | # behavior of running a script from the system command line, where |
|
1950 | 1967 | # Python inserts the script's directory into sys.path |
|
1951 | 1968 | dname = os.path.dirname(fname) |
|
1952 | 1969 | |
|
1953 | 1970 | with prepended_to_syspath(dname): |
|
1954 | 1971 | try: |
|
1955 | 1972 | with open(fname) as thefile: |
|
1956 | 1973 | script = thefile.read() |
|
1957 | 1974 | # self.runlines currently captures all exceptions |
|
1958 | 1975 | # raise in user code. It would be nice if there were |
|
1959 | 1976 | # versions of runlines, execfile that did raise, so |
|
1960 | 1977 | # we could catch the errors. |
|
1961 | 1978 | self.runlines(script, clean=True) |
|
1962 | 1979 | except: |
|
1963 | 1980 | self.showtraceback() |
|
1964 | 1981 | warn('Unknown failure executing file: <%s>' % fname) |
|
1965 | 1982 | |
|
1966 | 1983 | def _is_secondary_block_start(self, s): |
|
1967 | 1984 | if not s.endswith(':'): |
|
1968 | 1985 | return False |
|
1969 | 1986 | if (s.startswith('elif') or |
|
1970 | 1987 | s.startswith('else') or |
|
1971 | 1988 | s.startswith('except') or |
|
1972 | 1989 | s.startswith('finally')): |
|
1973 | 1990 | return True |
|
1974 | 1991 | |
|
1975 | 1992 | def cleanup_ipy_script(self, script): |
|
1976 | 1993 | """Make a script safe for self.runlines() |
|
1977 | 1994 | |
|
1978 | 1995 | Currently, IPython is lines based, with blocks being detected by |
|
1979 | 1996 | empty lines. This is a problem for block based scripts that may |
|
1980 | 1997 | not have empty lines after blocks. This script adds those empty |
|
1981 | 1998 | lines to make scripts safe for running in the current line based |
|
1982 | 1999 | IPython. |
|
1983 | 2000 | """ |
|
1984 | 2001 | res = [] |
|
1985 | 2002 | lines = script.splitlines() |
|
1986 | 2003 | level = 0 |
|
1987 | 2004 | |
|
1988 | 2005 | for l in lines: |
|
1989 | 2006 | lstripped = l.lstrip() |
|
1990 | 2007 | stripped = l.strip() |
|
1991 | 2008 | if not stripped: |
|
1992 | 2009 | continue |
|
1993 | 2010 | newlevel = len(l) - len(lstripped) |
|
1994 | 2011 | if level > 0 and newlevel == 0 and \ |
|
1995 | 2012 | not self._is_secondary_block_start(stripped): |
|
1996 | 2013 | # add empty line |
|
1997 | 2014 | res.append('') |
|
1998 | 2015 | res.append(l) |
|
1999 | 2016 | level = newlevel |
|
2000 | 2017 | |
|
2001 | 2018 | return '\n'.join(res) + '\n' |
|
2002 | 2019 | |
|
2003 | 2020 | def runlines(self, lines, clean=False): |
|
2004 | 2021 | """Run a string of one or more lines of source. |
|
2005 | 2022 | |
|
2006 | 2023 | This method is capable of running a string containing multiple source |
|
2007 | 2024 | lines, as if they had been entered at the IPython prompt. Since it |
|
2008 | 2025 | exposes IPython's processing machinery, the given strings can contain |
|
2009 | 2026 | magic calls (%magic), special shell access (!cmd), etc. |
|
2010 | 2027 | """ |
|
2011 | 2028 | |
|
2012 | 2029 | if isinstance(lines, (list, tuple)): |
|
2013 | 2030 | lines = '\n'.join(lines) |
|
2014 | 2031 | |
|
2015 | 2032 | if clean: |
|
2016 | 2033 | lines = self.cleanup_ipy_script(lines) |
|
2017 | 2034 | |
|
2018 | 2035 | # We must start with a clean buffer, in case this is run from an |
|
2019 | 2036 | # interactive IPython session (via a magic, for example). |
|
2020 | 2037 | self.resetbuffer() |
|
2021 | 2038 | lines = lines.splitlines() |
|
2022 | 2039 | more = 0 |
|
2023 | 2040 | |
|
2024 | 2041 | with nested(self.builtin_trap, self.display_trap): |
|
2025 | 2042 | for line in lines: |
|
2026 | 2043 | # skip blank lines so we don't mess up the prompt counter, but do |
|
2027 | 2044 | # NOT skip even a blank line if we are in a code block (more is |
|
2028 | 2045 | # true) |
|
2029 | 2046 | |
|
2030 | 2047 | if line or more: |
|
2031 | 2048 | # push to raw history, so hist line numbers stay in sync |
|
2032 | 2049 | self.input_hist_raw.append("# " + line + "\n") |
|
2033 | 2050 | prefiltered = self.prefilter_manager.prefilter_lines(line,more) |
|
2034 | 2051 | more = self.push_line(prefiltered) |
|
2035 | 2052 | # IPython's runsource returns None if there was an error |
|
2036 | 2053 | # compiling the code. This allows us to stop processing right |
|
2037 | 2054 | # away, so the user gets the error message at the right place. |
|
2038 | 2055 | if more is None: |
|
2039 | 2056 | break |
|
2040 | 2057 | else: |
|
2041 | 2058 | self.input_hist_raw.append("\n") |
|
2042 | 2059 | # final newline in case the input didn't have it, so that the code |
|
2043 | 2060 | # actually does get executed |
|
2044 | 2061 | if more: |
|
2045 | 2062 | self.push_line('\n') |
|
2046 | 2063 | |
|
2047 | 2064 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2048 | 2065 | """Compile and run some source in the interpreter. |
|
2049 | 2066 | |
|
2050 | 2067 | Arguments are as for compile_command(). |
|
2051 | 2068 | |
|
2052 | 2069 | One several things can happen: |
|
2053 | 2070 | |
|
2054 | 2071 | 1) The input is incorrect; compile_command() raised an |
|
2055 | 2072 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2056 | 2073 | will be printed by calling the showsyntaxerror() method. |
|
2057 | 2074 | |
|
2058 | 2075 | 2) The input is incomplete, and more input is required; |
|
2059 | 2076 | compile_command() returned None. Nothing happens. |
|
2060 | 2077 | |
|
2061 | 2078 | 3) The input is complete; compile_command() returned a code |
|
2062 | 2079 | object. The code is executed by calling self.runcode() (which |
|
2063 | 2080 | also handles run-time exceptions, except for SystemExit). |
|
2064 | 2081 | |
|
2065 | 2082 | The return value is: |
|
2066 | 2083 | |
|
2067 | 2084 | - True in case 2 |
|
2068 | 2085 | |
|
2069 | 2086 | - False in the other cases, unless an exception is raised, where |
|
2070 | 2087 | None is returned instead. This can be used by external callers to |
|
2071 | 2088 | know whether to continue feeding input or not. |
|
2072 | 2089 | |
|
2073 | 2090 | The return value can be used to decide whether to use sys.ps1 or |
|
2074 | 2091 | sys.ps2 to prompt the next line.""" |
|
2075 | 2092 | |
|
2076 | 2093 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2077 | 2094 | # this allows execution of indented pasted code. It is tempting |
|
2078 | 2095 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2079 | 2096 | # directly, but this fails for more complicated scenarios |
|
2080 | 2097 | source=source.encode(self.stdin_encoding) |
|
2081 | 2098 | if source[:1] in [' ', '\t']: |
|
2082 | 2099 | source = 'if 1:\n%s' % source |
|
2083 | 2100 | |
|
2084 | 2101 | try: |
|
2085 | 2102 | code = self.compile(source,filename,symbol) |
|
2086 | 2103 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2087 | 2104 | # Case 1 |
|
2088 | 2105 | self.showsyntaxerror(filename) |
|
2089 | 2106 | return None |
|
2090 | 2107 | |
|
2091 | 2108 | if code is None: |
|
2092 | 2109 | # Case 2 |
|
2093 | 2110 | return True |
|
2094 | 2111 | |
|
2095 | 2112 | # Case 3 |
|
2096 | 2113 | # We store the code object so that threaded shells and |
|
2097 | 2114 | # custom exception handlers can access all this info if needed. |
|
2098 | 2115 | # The source corresponding to this can be obtained from the |
|
2099 | 2116 | # buffer attribute as '\n'.join(self.buffer). |
|
2100 | 2117 | self.code_to_run = code |
|
2101 | 2118 | # now actually execute the code object |
|
2102 | 2119 | if self.runcode(code) == 0: |
|
2103 | 2120 | return False |
|
2104 | 2121 | else: |
|
2105 | 2122 | return None |
|
2106 | 2123 | |
|
2107 | 2124 | def runcode(self,code_obj): |
|
2108 | 2125 | """Execute a code object. |
|
2109 | 2126 | |
|
2110 | 2127 | When an exception occurs, self.showtraceback() is called to display a |
|
2111 | 2128 | traceback. |
|
2112 | 2129 | |
|
2113 | 2130 | Return value: a flag indicating whether the code to be run completed |
|
2114 | 2131 | successfully: |
|
2115 | 2132 | |
|
2116 | 2133 | - 0: successful execution. |
|
2117 | 2134 | - 1: an error occurred. |
|
2118 | 2135 | """ |
|
2119 | 2136 | |
|
2120 | 2137 | # Set our own excepthook in case the user code tries to call it |
|
2121 | 2138 | # directly, so that the IPython crash handler doesn't get triggered |
|
2122 | 2139 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2123 | 2140 | |
|
2124 | 2141 | # we save the original sys.excepthook in the instance, in case config |
|
2125 | 2142 | # code (such as magics) needs access to it. |
|
2126 | 2143 | self.sys_excepthook = old_excepthook |
|
2127 | 2144 | outflag = 1 # happens in more places, so it's easier as default |
|
2128 | 2145 | try: |
|
2129 | 2146 | try: |
|
2130 | 2147 | self.hooks.pre_runcode_hook() |
|
2131 | 2148 | exec code_obj in self.user_global_ns, self.user_ns |
|
2132 | 2149 | finally: |
|
2133 | 2150 | # Reset our crash handler in place |
|
2134 | 2151 | sys.excepthook = old_excepthook |
|
2135 | 2152 | except SystemExit: |
|
2136 | 2153 | self.resetbuffer() |
|
2137 | self.showtraceback() | |
|
2138 | warn("Type %exit or %quit to exit IPython " | |
|
2139 | "(%Exit or %Quit do so unconditionally).",level=1) | |
|
2154 | self.showtraceback(exception_only=True) | |
|
2155 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
|
2140 | 2156 | except self.custom_exceptions: |
|
2141 | 2157 | etype,value,tb = sys.exc_info() |
|
2142 | 2158 | self.CustomTB(etype,value,tb) |
|
2143 | 2159 | except: |
|
2144 | 2160 | self.showtraceback() |
|
2145 | 2161 | else: |
|
2146 | 2162 | outflag = 0 |
|
2147 | 2163 | if softspace(sys.stdout, 0): |
|
2148 | 2164 | |
|
2149 | 2165 | # Flush out code object which has been run (and source) |
|
2150 | 2166 | self.code_to_run = None |
|
2151 | 2167 | return outflag |
|
2152 | 2168 | |
|
2153 | 2169 | def push_line(self, line): |
|
2154 | 2170 | """Push a line to the interpreter. |
|
2155 | 2171 | |
|
2156 | 2172 | The line should not have a trailing newline; it may have |
|
2157 | 2173 | internal newlines. The line is appended to a buffer and the |
|
2158 | 2174 | interpreter's runsource() method is called with the |
|
2159 | 2175 | concatenated contents of the buffer as source. If this |
|
2160 | 2176 | indicates that the command was executed or invalid, the buffer |
|
2161 | 2177 | is reset; otherwise, the command is incomplete, and the buffer |
|
2162 | 2178 | is left as it was after the line was appended. The return |
|
2163 | 2179 | value is 1 if more input is required, 0 if the line was dealt |
|
2164 | 2180 | with in some way (this is the same as runsource()). |
|
2165 | 2181 | """ |
|
2166 | 2182 | |
|
2167 | 2183 | # autoindent management should be done here, and not in the |
|
2168 | 2184 | # interactive loop, since that one is only seen by keyboard input. We |
|
2169 | 2185 | # need this done correctly even for code run via runlines (which uses |
|
2170 | 2186 | # push). |
|
2171 | 2187 | |
|
2172 | 2188 | #print 'push line: <%s>' % line # dbg |
|
2173 | 2189 | for subline in line.splitlines(): |
|
2174 | 2190 | self._autoindent_update(subline) |
|
2175 | 2191 | self.buffer.append(line) |
|
2176 | 2192 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2177 | 2193 | if not more: |
|
2178 | 2194 | self.resetbuffer() |
|
2179 | 2195 | return more |
|
2180 | 2196 | |
|
2181 | 2197 | def _autoindent_update(self,line): |
|
2182 | 2198 | """Keep track of the indent level.""" |
|
2183 | 2199 | |
|
2184 | 2200 | #debugx('line') |
|
2185 | 2201 | #debugx('self.indent_current_nsp') |
|
2186 | 2202 | if self.autoindent: |
|
2187 | 2203 | if line: |
|
2188 | 2204 | inisp = num_ini_spaces(line) |
|
2189 | 2205 | if inisp < self.indent_current_nsp: |
|
2190 | 2206 | self.indent_current_nsp = inisp |
|
2191 | 2207 | |
|
2192 | 2208 | if line[-1] == ':': |
|
2193 | 2209 | self.indent_current_nsp += 4 |
|
2194 | 2210 | elif dedent_re.match(line): |
|
2195 | 2211 | self.indent_current_nsp -= 4 |
|
2196 | 2212 | else: |
|
2197 | 2213 | self.indent_current_nsp = 0 |
|
2198 | 2214 | |
|
2199 | 2215 | def resetbuffer(self): |
|
2200 | 2216 | """Reset the input buffer.""" |
|
2201 | 2217 | self.buffer[:] = [] |
|
2202 | 2218 | |
|
2203 | 2219 | def raw_input(self,prompt='',continue_prompt=False): |
|
2204 | 2220 | """Write a prompt and read a line. |
|
2205 | 2221 | |
|
2206 | 2222 | The returned line does not include the trailing newline. |
|
2207 | 2223 | When the user enters the EOF key sequence, EOFError is raised. |
|
2208 | 2224 | |
|
2209 | 2225 | Optional inputs: |
|
2210 | 2226 | |
|
2211 | 2227 | - prompt(''): a string to be printed to prompt the user. |
|
2212 | 2228 | |
|
2213 | 2229 | - continue_prompt(False): whether this line is the first one or a |
|
2214 | 2230 | continuation in a sequence of inputs. |
|
2215 | 2231 | """ |
|
2216 | 2232 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
2217 | 2233 | |
|
2218 | 2234 | # Code run by the user may have modified the readline completer state. |
|
2219 | 2235 | # We must ensure that our completer is back in place. |
|
2220 | 2236 | |
|
2221 | 2237 | if self.has_readline: |
|
2222 | 2238 | self.set_completer() |
|
2223 | 2239 | |
|
2224 | 2240 | try: |
|
2225 | 2241 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
2226 | 2242 | except ValueError: |
|
2227 | 2243 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
2228 | 2244 | " or sys.stdout.close()!\nExiting IPython!") |
|
2229 | 2245 | self.ask_exit() |
|
2230 | 2246 | return "" |
|
2231 | 2247 | |
|
2232 | 2248 | # Try to be reasonably smart about not re-indenting pasted input more |
|
2233 | 2249 | # than necessary. We do this by trimming out the auto-indent initial |
|
2234 | 2250 | # spaces, if the user's actual input started itself with whitespace. |
|
2235 | 2251 | #debugx('self.buffer[-1]') |
|
2236 | 2252 | |
|
2237 | 2253 | if self.autoindent: |
|
2238 | 2254 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
2239 | 2255 | line = line[self.indent_current_nsp:] |
|
2240 | 2256 | self.indent_current_nsp = 0 |
|
2241 | 2257 | |
|
2242 | 2258 | # store the unfiltered input before the user has any chance to modify |
|
2243 | 2259 | # it. |
|
2244 | 2260 | if line.strip(): |
|
2245 | 2261 | if continue_prompt: |
|
2246 | 2262 | self.input_hist_raw[-1] += '%s\n' % line |
|
2247 | 2263 | if self.has_readline and self.readline_use: |
|
2248 | 2264 | try: |
|
2249 | 2265 | histlen = self.readline.get_current_history_length() |
|
2250 | 2266 | if histlen > 1: |
|
2251 | 2267 | newhist = self.input_hist_raw[-1].rstrip() |
|
2252 | 2268 | self.readline.remove_history_item(histlen-1) |
|
2253 | 2269 | self.readline.replace_history_item(histlen-2, |
|
2254 | 2270 | newhist.encode(self.stdin_encoding)) |
|
2255 | 2271 | except AttributeError: |
|
2256 | 2272 | pass # re{move,place}_history_item are new in 2.4. |
|
2257 | 2273 | else: |
|
2258 | 2274 | self.input_hist_raw.append('%s\n' % line) |
|
2259 | 2275 | # only entries starting at first column go to shadow history |
|
2260 | 2276 | if line.lstrip() == line: |
|
2261 | 2277 | self.shadowhist.add(line.strip()) |
|
2262 | 2278 | elif not continue_prompt: |
|
2263 | 2279 | self.input_hist_raw.append('\n') |
|
2264 | 2280 | try: |
|
2265 | 2281 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
2266 | 2282 | except: |
|
2267 | 2283 | # blanket except, in case a user-defined prefilter crashes, so it |
|
2268 | 2284 | # can't take all of ipython with it. |
|
2269 | 2285 | self.showtraceback() |
|
2270 | 2286 | return '' |
|
2271 | 2287 | else: |
|
2272 | 2288 | return lineout |
|
2273 | 2289 | |
|
2274 | 2290 | #------------------------------------------------------------------------- |
|
2275 | 2291 | # Working with components |
|
2276 | 2292 | #------------------------------------------------------------------------- |
|
2277 | 2293 | |
|
2278 | 2294 | def get_component(self, name=None, klass=None): |
|
2279 | 2295 | """Fetch a component by name and klass in my tree.""" |
|
2280 | 2296 | c = Component.get_instances(root=self, name=name, klass=klass) |
|
2297 | if len(c) == 0: | |
|
2298 | return None | |
|
2281 | 2299 | if len(c) == 1: |
|
2282 | 2300 | return c[0] |
|
2283 | 2301 | else: |
|
2284 | 2302 | return c |
|
2285 | 2303 | |
|
2286 | 2304 | #------------------------------------------------------------------------- |
|
2287 | 2305 | # IPython extensions |
|
2288 | 2306 | #------------------------------------------------------------------------- |
|
2289 | 2307 | |
|
2290 | 2308 | def load_extension(self, module_str): |
|
2291 | 2309 | """Load an IPython extension by its module name. |
|
2292 | 2310 | |
|
2293 | 2311 | An IPython extension is an importable Python module that has |
|
2294 | 2312 | a function with the signature:: |
|
2295 | 2313 | |
|
2296 | 2314 | def load_ipython_extension(ipython): |
|
2297 | 2315 | # Do things with ipython |
|
2298 | 2316 | |
|
2299 | 2317 | This function is called after your extension is imported and the |
|
2300 | 2318 | currently active :class:`InteractiveShell` instance is passed as |
|
2301 | 2319 | the only argument. You can do anything you want with IPython at |
|
2302 | 2320 | that point, including defining new magic and aliases, adding new |
|
2303 | 2321 | components, etc. |
|
2304 | 2322 | |
|
2305 | 2323 | The :func:`load_ipython_extension` will be called again is you |
|
2306 | 2324 | load or reload the extension again. It is up to the extension |
|
2307 | 2325 | author to add code to manage that. |
|
2308 | 2326 | |
|
2309 | 2327 | You can put your extension modules anywhere you want, as long as |
|
2310 | 2328 | they can be imported by Python's standard import mechanism. However, |
|
2311 | 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 | 2331 | is added to ``sys.path`` automatically. |
|
2314 | 2332 | """ |
|
2315 | 2333 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2316 | 2334 | |
|
2317 | 2335 | if module_str not in sys.modules: |
|
2318 | 2336 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2319 | 2337 | __import__(module_str) |
|
2320 | 2338 | mod = sys.modules[module_str] |
|
2321 | self._call_load_ipython_extension(mod) | |
|
2339 | return self._call_load_ipython_extension(mod) | |
|
2322 | 2340 | |
|
2323 | 2341 | def unload_extension(self, module_str): |
|
2324 | 2342 | """Unload an IPython extension by its module name. |
|
2325 | 2343 | |
|
2326 | 2344 | This function looks up the extension's name in ``sys.modules`` and |
|
2327 | 2345 | simply calls ``mod.unload_ipython_extension(self)``. |
|
2328 | 2346 | """ |
|
2329 | 2347 | if module_str in sys.modules: |
|
2330 | 2348 | mod = sys.modules[module_str] |
|
2331 | 2349 | self._call_unload_ipython_extension(mod) |
|
2332 | 2350 | |
|
2333 | 2351 | def reload_extension(self, module_str): |
|
2334 | 2352 | """Reload an IPython extension by calling reload. |
|
2335 | 2353 | |
|
2336 | 2354 | If the module has not been loaded before, |
|
2337 | 2355 | :meth:`InteractiveShell.load_extension` is called. Otherwise |
|
2338 | 2356 | :func:`reload` is called and then the :func:`load_ipython_extension` |
|
2339 | 2357 | function of the module, if it exists is called. |
|
2340 | 2358 | """ |
|
2341 | 2359 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
2342 | 2360 | |
|
2343 | 2361 | with prepended_to_syspath(self.ipython_extension_dir): |
|
2344 | 2362 | if module_str in sys.modules: |
|
2345 | 2363 | mod = sys.modules[module_str] |
|
2346 | 2364 | reload(mod) |
|
2347 | 2365 | self._call_load_ipython_extension(mod) |
|
2348 | 2366 | else: |
|
2349 | 2367 | self.load_extension(module_str) |
|
2350 | 2368 | |
|
2351 | 2369 | def _call_load_ipython_extension(self, mod): |
|
2352 | 2370 | if hasattr(mod, 'load_ipython_extension'): |
|
2353 | mod.load_ipython_extension(self) | |
|
2371 | return mod.load_ipython_extension(self) | |
|
2354 | 2372 | |
|
2355 | 2373 | def _call_unload_ipython_extension(self, mod): |
|
2356 | 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 | 2378 | # Things related to the prefilter |
|
2361 | 2379 | #------------------------------------------------------------------------- |
|
2362 | 2380 | |
|
2363 | 2381 | def init_prefilter(self): |
|
2364 | 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 | 2389 | # Utilities |
|
2368 | 2390 | #------------------------------------------------------------------------- |
|
2369 | 2391 | |
|
2370 | 2392 | def getoutput(self, cmd): |
|
2371 | 2393 | return getoutput(self.var_expand(cmd,depth=2), |
|
2372 | 2394 | header=self.system_header, |
|
2373 | 2395 | verbose=self.system_verbose) |
|
2374 | 2396 | |
|
2375 | 2397 | def getoutputerror(self, cmd): |
|
2376 | 2398 | return getoutputerror(self.var_expand(cmd,depth=2), |
|
2377 | 2399 | header=self.system_header, |
|
2378 | 2400 | verbose=self.system_verbose) |
|
2379 | 2401 | |
|
2380 | 2402 | def var_expand(self,cmd,depth=0): |
|
2381 | 2403 | """Expand python variables in a string. |
|
2382 | 2404 | |
|
2383 | 2405 | The depth argument indicates how many frames above the caller should |
|
2384 | 2406 | be walked to look for the local namespace where to expand variables. |
|
2385 | 2407 | |
|
2386 | 2408 | The global namespace for expansion is always the user's interactive |
|
2387 | 2409 | namespace. |
|
2388 | 2410 | """ |
|
2389 | 2411 | |
|
2390 | 2412 | return str(ItplNS(cmd, |
|
2391 | 2413 | self.user_ns, # globals |
|
2392 | 2414 | # Skip our own frame in searching for locals: |
|
2393 | 2415 | sys._getframe(depth+1).f_locals # locals |
|
2394 | 2416 | )) |
|
2395 | 2417 | |
|
2396 | 2418 | def mktempfile(self,data=None): |
|
2397 | 2419 | """Make a new tempfile and return its filename. |
|
2398 | 2420 | |
|
2399 | 2421 | This makes a call to tempfile.mktemp, but it registers the created |
|
2400 | 2422 | filename internally so ipython cleans it up at exit time. |
|
2401 | 2423 | |
|
2402 | 2424 | Optional inputs: |
|
2403 | 2425 | |
|
2404 | 2426 | - data(None): if data is given, it gets written out to the temp file |
|
2405 | 2427 | immediately, and the file is closed again.""" |
|
2406 | 2428 | |
|
2407 | 2429 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2408 | 2430 | self.tempfiles.append(filename) |
|
2409 | 2431 | |
|
2410 | 2432 | if data: |
|
2411 | 2433 | tmp_file = open(filename,'w') |
|
2412 | 2434 | tmp_file.write(data) |
|
2413 | 2435 | tmp_file.close() |
|
2414 | 2436 | return filename |
|
2415 | 2437 | |
|
2416 | 2438 | def write(self,data): |
|
2417 | 2439 | """Write a string to the default output""" |
|
2418 | 2440 | Term.cout.write(data) |
|
2419 | 2441 | |
|
2420 | 2442 | def write_err(self,data): |
|
2421 | 2443 | """Write a string to the default error output""" |
|
2422 | 2444 | Term.cerr.write(data) |
|
2423 | 2445 | |
|
2424 | 2446 | def ask_yes_no(self,prompt,default=True): |
|
2425 | 2447 | if self.quiet: |
|
2426 | 2448 | return True |
|
2427 | 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 | 2487 | # Things related to IPython exiting |
|
2431 | 2488 | #------------------------------------------------------------------------- |
|
2432 | 2489 | |
|
2433 | 2490 | def ask_exit(self): |
|
2434 |
""" |
|
|
2491 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
|
2435 | 2492 | self.exit_now = True |
|
2436 | 2493 | |
|
2437 | 2494 | def exit(self): |
|
2438 | 2495 | """Handle interactive exit. |
|
2439 | 2496 | |
|
2440 | 2497 | This method calls the ask_exit callback.""" |
|
2441 | 2498 | if self.confirm_exit: |
|
2442 | 2499 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
2443 | 2500 | self.ask_exit() |
|
2444 | 2501 | else: |
|
2445 | 2502 | self.ask_exit() |
|
2446 | 2503 | |
|
2447 | 2504 | def atexit_operations(self): |
|
2448 | 2505 | """This will be executed at the time of exit. |
|
2449 | 2506 | |
|
2450 | 2507 | Saving of persistent data should be performed here. |
|
2451 | 2508 | """ |
|
2452 | 2509 | self.savehist() |
|
2453 | 2510 | |
|
2454 | 2511 | # Cleanup all tempfiles left around |
|
2455 | 2512 | for tfile in self.tempfiles: |
|
2456 | 2513 | try: |
|
2457 | 2514 | os.unlink(tfile) |
|
2458 | 2515 | except OSError: |
|
2459 | 2516 | pass |
|
2460 | 2517 | |
|
2461 | 2518 | # Clear all user namespaces to release all references cleanly. |
|
2462 | 2519 | self.reset() |
|
2463 | 2520 | |
|
2464 | 2521 | # Run user hooks |
|
2465 | 2522 | self.hooks.shutdown_hook() |
|
2466 | 2523 | |
|
2467 | 2524 | def cleanup(self): |
|
2468 | 2525 | self.restore_sys_module_state() |
|
2469 | 2526 | |
|
2470 | 2527 |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 |
|
1 | NO CONTENT: file was removed |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
The requested commit or file is too big and content was truncated. Show full diff |
|
1 | 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 | |
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