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 | #----------------------------------------------------------------------------- | |
|
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__ | |
|
40 | 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) |
|
265 | try: | |
|
247 | 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: | |
|
248 | 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() | |
|
273 | 297 | |
|
274 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
|
275 | 298 | |
|
276 | # arguments = [(('-f','--file'),dict(type=str,dest='file'))] | |
|
277 | arguments = () | |
|
299 | class ArgParseConfigLoader(CommandLineConfigLoader): | |
|
300 | #: Global default for arguments (see argparse docs for details) | |
|
301 | argument_default = NoConfigDefault | |
|
278 | 302 | |
|
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 _ |
|
|
364 | def _add_other_arguments(self): | |
|
365 | """Meant for subclasses to add their own arguments.""" | |
|
366 | pass | |
|
367 | ||
|
368 | def _parse_args(self, args): | |
|
317 | 369 | """self.parser->self.parsed_data""" |
|
318 | if args is None: | |
|
319 | self.parsed_data, self.extra_args = self.parser.parse_known_args() | |
|
320 | else: | |
|
321 | 370 |
|
|
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 | 69 |
|
|
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: |
|
|
393 | self.log.warn("Error loading config file: %s" % | |
|
233 | 394 |
|
|
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) |
|
421 | if self.override_config is None: | |
|
255 | 422 | config._merge(self.file_config) |
|
256 | 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.""" |
|
461 | if self._exiting: | |
|
462 | pass | |
|
463 | else: | |
|
283 | 464 | self.log.critical("Aborting application: %s" % self.name, exc_info=True) |
|
465 | self._exiting = True | |
|
284 | 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 | 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 | 315 | |
|
271 | ||
|
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 | 566 | try_magic = [] |
|
544 | 567 | |
|
545 | ||
|
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 | long_header=1, | |
|
139 | call_pdb=self.call_pdb, | |
|
140 | ) | |
|
141 | if self.call_pdb: | |
|
142 | TBhandler(etype,evalue,etb) | |
|
143 | return | |
|
144 | else: | |
|
138 | 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.""" |
|
169 | import platform | |
|
162 | 170 | |
|
163 | sec_sep = '\n\n'+'*'*75+'\n\n' | |
|
171 | sec_sep = self.section_sep | |
|
164 | 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 | 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 | 171 |
|
|
172 | 172 |
|
|
173 | 173 | |
|
174 | 174 |
|
|
175 | 175 |
|
|
176 | 176 |
|
|
177 | 177 |
|
|
178 | 178 |
|
|
179 | 179 |
|
|
180 | 180 |
|
|
181 | 181 |
|
|
182 | 182 |
|
|
183 | 183 |
|
|
184 | 184 | |
|
185 | self.shell = ipapi.get() | |
|
186 | ||
|
185 | 187 |
|
|
186 | 188 | |
|
187 | 189 |
|
|
188 | 190 |
|
|
189 | 191 |
|
|
190 | 192 |
|
|
191 | 193 |
|
|
192 | 194 | |
|
193 | 195 |
|
|
194 | 196 |
|
|
195 | 197 | |
|
196 |
|
|
|
197 |
|
|
|
198 | self.old_all_completions = self.shell.Completer.all_completions | |
|
199 | self.shell.Completer.all_completions=self.all_completions | |
|
198 | 200 | |
|
199 | 201 |
|
|
200 | 202 |
|
|
201 | 203 |
|
|
202 | 204 |
|
|
203 | 205 |
|
|
204 | 206 | |
|
205 | 207 |
|
|
206 | 208 | |
|
207 | 209 |
|
|
208 | 210 |
|
|
209 | 211 |
|
|
210 | 212 | |
|
211 | 213 |
|
|
212 | 214 |
|
|
213 | 215 |
|
|
214 | 216 | |
|
215 | 217 |
|
|
216 | 218 |
|
|
217 | 219 | |
|
218 | 220 |
|
|
219 | 221 |
|
|
220 | 222 | |
|
221 | 223 |
|
|
222 | 224 |
|
|
223 | 225 | |
|
224 | 226 |
|
|
225 | 227 | |
|
226 | 228 |
|
|
227 | 229 |
|
|
228 | 230 |
|
|
229 | 231 | |
|
230 | ||
|
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")) | |
|
253 | ||
|
254 | # Create color table: we copy the default one from the traceback | |
|
255 | # module and add a few attributes needed for debugging | |
|
256 | self.color_scheme_table = exception_colors() | |
|
257 | ||
|
258 | # shorthands | |
|
259 | C = coloransi.TermColors | |
|
260 | cst = self.color_scheme_table | |
|
261 | ||
|
262 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
|
263 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
|
264 | ||
|
265 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
|
266 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
|
267 | ||
|
268 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
|
269 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
|
270 | ||
|
271 | self.set_colors(color_scheme) | |
|
272 | ||
|
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 | 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. | |
|
18 | By default, input history is printed without line numbers so it can be | |
|
19 | directly pasted into an editor. | |
|
21 | 20 | |
|
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. | |
|
22 | 24 | |
|
23 | 25 | Options: |
|
24 | 26 | |
|
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. | |
|
28 | ||
|
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]), |
|
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: | |
|
126 | 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, (557 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.' |
|
|
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.') | |
|
99 | 73 | ), |
|
100 | (('-noautomagic',), dict( | |
|
101 |
action='store_false', dest='InteractiveShell.automagic', |
|
|
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.") | |
|
306 | action='store_true', dest='Global.force_interact', | |
|
307 | help= | |
|
308 | "If running code from the command line, become interactive afterwards." | |
|
309 | ) | |
|
310 | ), | |
|
311 | ||
|
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') | |
|
270 | 317 | ), |
|
271 | (('-wthread',), dict( | |
|
272 | action='store_true', dest='Global.wthread', default=NoConfigDefault, | |
|
273 | help="Enable wxPython event loop integration.") | |
|
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'].") | |
|
274 | 325 | ), |
|
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.") | |
|
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)") | |
|
278 | 333 | ), |
|
279 | (('-gthread',), dict( | |
|
280 |
action='store_true', dest='Global. |
|
|
281 |
help="Enable |
|
|
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)") | |
|
282 | 343 | ), |
|
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 | 344 | ) |
|
289 | 345 | |
|
346 | #----------------------------------------------------------------------------- | |
|
347 | # Main classes and functions | |
|
348 | #----------------------------------------------------------------------------- | |
|
290 | 349 | |
|
291 | class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader): | |
|
350 | class IPythonApp(Application): | |
|
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 | |
|
292 | 356 | |
|
293 | arguments = cl_args | |
|
357 | config_file_name = default_config_file_name | |
|
294 | 358 | |
|
359 | cl_arguments = Application.cl_arguments + cl_args | |
|
295 | 360 | |
|
296 | _default_config_file_name = 'ipython_config.py' | |
|
361 | # Private and configuration attributes | |
|
362 | _CrashHandler = crashhandler.IPythonCrashHandler | |
|
297 | 363 | |
|
298 | class IPythonApp(Application): | |
|
299 | name = 'ipython' | |
|
300 | config_file_name = _default_config_file_name | |
|
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 | |
|
535 | if gui or Global.pylab: | |
|
426 | 536 | try: |
|
427 |
|
|
|
428 | if config.Global.wthread: | |
|
429 | self.log.info("Enabling wx GUI event loop integration") | |
|
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) | |
|
537 | self.log.info("Enabling GUI event loop integration, " | |
|
538 | "toolkit=%s, pylab=%s" % (gui, Global.pylab) ) | |
|
539 | activate(gui) | |
|
437 | 540 | except: |
|
438 | 541 | self.log.warn("Error in enabling GUI event loop integration:") |
|
439 | 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 | |
|
957 | ||
|
958 | # make global variables for user access to the histories | |
|
959 | self.user_ns['_ih'] = self.input_hist | |
|
960 | self.user_ns['_oh'] = self.output_hist | |
|
961 | self.user_ns['_dh'] = self.dir_hist | |
|
962 | ||
|
963 | # user aliases to input and output histories | |
|
964 | self.user_ns['In'] = self.input_hist | |
|
965 | self.user_ns['Out'] = self.output_hist | |
|
966 | ||
|
967 | self.user_ns['_sh'] = shadowns | |
|
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 = {} | |
|
968 | 975 | |
|
969 | 976 | # Put 'help' in the user namespace |
|
970 | 977 | try: |
|
971 | 978 | from site import _Helper |
|
972 |
|
|
|
979 | ns['help'] = _Helper() | |
|
973 | 980 | except ImportError: |
|
974 | 981 | warn('help() not available - check site.py') |
|
975 | 982 | |
|
983 | # make global variables for user access to the histories | |
|
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 | |
|
995 | ||
|
996 | # user aliases to input and output histories | |
|
997 | ns['In'] = self.input_hist | |
|
998 | ns['Out'] = self.output_hist | |
|
999 | ||
|
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) | |
|
1005 | ||
|
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 | 1133 |
|
|
1107 | 1134 |
|
|
1108 | 1135 |
|
|
1109 | 1136 |
|
|
1110 | 1137 |
|
|
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 | 1258 | |
|
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 | 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 |
|
1263 | 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 | |
|
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: |
|
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: | |
|
1280 | 1297 | self.InteractiveTB(etype,value,tb,tb_offset=tb_offset) |
|
1281 |
if self.InteractiveTB.call_pdb |
|
|
1298 | if self.InteractiveTB.call_pdb: | |
|
1282 | 1299 | # pdb mucks up readline, fix it back |
|
1283 | 1300 | self.set_completer() |
|
1301 | ||
|
1284 | 1302 | except KeyboardInterrupt: |
|
1285 | 1303 | self.write("\nKeyboardInterrupt\n") |
|
1286 | 1304 | |
|
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 |
|
1860 | if self.has_readline: | |
|
1829 | 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 | 1926 |
|
|
1905 | except SyntaxError: | |
|
1906 | self.showsyntaxerror() | |
|
1907 | warn('Failure executing file: <%s>' % fname) | |
|
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,3553 +1,3613 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #***************************************************************************** |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #***************************************************************************** |
|
12 | 12 | |
|
13 | 13 | #**************************************************************************** |
|
14 | 14 | # Modules and globals |
|
15 | 15 | |
|
16 | 16 | # Python standard modules |
|
17 | 17 | import __builtin__ |
|
18 | 18 | import bdb |
|
19 | 19 | import inspect |
|
20 | 20 | import os |
|
21 | 21 | import pdb |
|
22 | 22 | import pydoc |
|
23 | 23 | import sys |
|
24 | import shutil | |
|
24 | 25 | import re |
|
25 | 26 | import tempfile |
|
26 | 27 | import time |
|
27 | 28 | import cPickle as pickle |
|
28 | 29 | import textwrap |
|
29 | 30 | from cStringIO import StringIO |
|
30 | 31 | from getopt import getopt,GetoptError |
|
31 | 32 | from pprint import pprint, pformat |
|
32 | 33 | |
|
33 | 34 | # cProfile was added in Python2.5 |
|
34 | 35 | try: |
|
35 | 36 | import cProfile as profile |
|
36 | 37 | import pstats |
|
37 | 38 | except ImportError: |
|
38 | 39 | # profile isn't bundled by default in Debian for license reasons |
|
39 | 40 | try: |
|
40 | 41 | import profile,pstats |
|
41 | 42 | except ImportError: |
|
42 | 43 | profile = pstats = None |
|
43 | 44 | |
|
44 | 45 | # Homebrewed |
|
45 | 46 | import IPython |
|
46 | from IPython.utils import wildcard | |
|
47 | import IPython.utils.generics | |
|
48 | ||
|
47 | 49 | from IPython.core import debugger, oinspect |
|
48 | 50 | from IPython.core.error import TryNext |
|
51 | from IPython.core.error import UsageError | |
|
49 | 52 | from IPython.core.fakemodule import FakeModule |
|
53 | from IPython.core.macro import Macro | |
|
54 | from IPython.core.page import page | |
|
50 | 55 | from IPython.core.prefilter import ESC_MAGIC |
|
56 | from IPython.core.pylabtools import mpl_runner | |
|
57 | from IPython.lib.inputhook import enable_gui | |
|
51 | 58 | from IPython.external.Itpl import Itpl, itpl, printpl,itplns |
|
59 | from IPython.testing import decorators as testdec | |
|
60 | from IPython.utils import platutils | |
|
61 | from IPython.utils import wildcard | |
|
52 | 62 | from IPython.utils.PyColorize import Parser |
|
53 | 63 | from IPython.utils.ipstruct import Struct |
|
54 | from IPython.core.macro import Macro | |
|
64 | ||
|
65 | # XXX - We need to switch to explicit imports here with genutils | |
|
55 | 66 | from IPython.utils.genutils import * |
|
56 | from IPython.core.page import page | |
|
57 | from IPython.utils import platutils | |
|
58 | import IPython.utils.generics | |
|
59 | from IPython.core.error import UsageError | |
|
60 | from IPython.testing import decorators as testdec | |
|
61 | 67 | |
|
62 | 68 | #*************************************************************************** |
|
63 | 69 | # Utility functions |
|
64 | 70 | def on_off(tag): |
|
65 | 71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
66 | 72 | return ['OFF','ON'][tag] |
|
67 | 73 | |
|
68 | 74 | class Bunch: pass |
|
69 | 75 | |
|
70 | 76 | def compress_dhist(dh): |
|
71 | 77 | head, tail = dh[:-10], dh[-10:] |
|
72 | 78 | |
|
73 | 79 | newhead = [] |
|
74 | 80 | done = set() |
|
75 | 81 | for h in head: |
|
76 | 82 | if h in done: |
|
77 | 83 | continue |
|
78 | 84 | newhead.append(h) |
|
79 | 85 | done.add(h) |
|
80 | 86 | |
|
81 | 87 | return newhead + tail |
|
82 | 88 | |
|
83 | 89 | |
|
84 | 90 | #*************************************************************************** |
|
85 | 91 | # Main class implementing Magic functionality |
|
92 | ||
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
|
95 | # on with super() calls, Component and the MRO... For now leave it as-is, but | |
|
96 | # eventually this needs to be clarified. | |
|
97 | ||
|
86 | 98 | class Magic: |
|
87 | 99 | """Magic functions for InteractiveShell. |
|
88 | 100 | |
|
89 | 101 | Shell functions which can be reached as %function_name. All magic |
|
90 | 102 | functions should accept a string, which they can parse for their own |
|
91 | 103 | needs. This can make some functions easier to type, eg `%cd ../` |
|
92 | 104 | vs. `%cd("../")` |
|
93 | 105 | |
|
94 | 106 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
95 | 107 | at the command line, but it is is needed in the definition. """ |
|
96 | 108 | |
|
97 | 109 | # class globals |
|
98 | 110 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
99 | 111 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
100 | 112 | |
|
101 | 113 | #...................................................................... |
|
102 | 114 | # some utility functions |
|
103 | 115 | |
|
104 | 116 | def __init__(self,shell): |
|
105 | 117 | |
|
106 | 118 | self.options_table = {} |
|
107 | 119 | if profile is None: |
|
108 | 120 | self.magic_prun = self.profile_missing_notice |
|
109 | 121 | self.shell = shell |
|
110 | 122 | |
|
111 | 123 | # namespace for holding state we may need |
|
112 | 124 | self._magic_state = Bunch() |
|
113 | 125 | |
|
114 | 126 | def profile_missing_notice(self, *args, **kwargs): |
|
115 | 127 | error("""\ |
|
116 | 128 | The profile module could not be found. It has been removed from the standard |
|
117 | 129 | python packages because of its non-free license. To use profiling, install the |
|
118 | 130 | python-profiler package from non-free.""") |
|
119 | 131 | |
|
120 | 132 | def default_option(self,fn,optstr): |
|
121 | 133 | """Make an entry in the options_table for fn, with value optstr""" |
|
122 | 134 | |
|
123 | 135 | if fn not in self.lsmagic(): |
|
124 | 136 | error("%s is not a magic function" % fn) |
|
125 | 137 | self.options_table[fn] = optstr |
|
126 | 138 | |
|
127 | 139 | def lsmagic(self): |
|
128 | 140 | """Return a list of currently available magic functions. |
|
129 | 141 | |
|
130 | 142 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
131 | 143 | ['magic_ls','magic_cd',...]""" |
|
132 | 144 | |
|
133 | 145 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
134 | 146 | |
|
135 | 147 | # magics in class definition |
|
136 | 148 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
137 | 149 | callable(Magic.__dict__[fn]) |
|
138 | 150 | # in instance namespace (run-time user additions) |
|
139 | 151 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
140 | 152 | callable(self.__dict__[fn]) |
|
141 | 153 | # and bound magics by user (so they can access self): |
|
142 | 154 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
143 | 155 | callable(self.__class__.__dict__[fn]) |
|
144 | 156 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
145 | 157 | filter(inst_magic,self.__dict__.keys()) + \ |
|
146 | 158 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
147 | 159 | out = [] |
|
148 | 160 | for fn in set(magics): |
|
149 | 161 | out.append(fn.replace('magic_','',1)) |
|
150 | 162 | out.sort() |
|
151 | 163 | return out |
|
152 | 164 | |
|
153 | 165 | def extract_input_slices(self,slices,raw=False): |
|
154 | 166 | """Return as a string a set of input history slices. |
|
155 | 167 | |
|
156 | 168 | Inputs: |
|
157 | 169 | |
|
158 | 170 | - slices: the set of slices is given as a list of strings (like |
|
159 | 171 | ['1','4:8','9'], since this function is for use by magic functions |
|
160 | 172 | which get their arguments as strings. |
|
161 | 173 | |
|
162 | 174 | Optional inputs: |
|
163 | 175 | |
|
164 | 176 | - raw(False): by default, the processed input is used. If this is |
|
165 | 177 | true, the raw input history is used instead. |
|
166 | 178 | |
|
167 | 179 | Note that slices can be called with two notations: |
|
168 | 180 | |
|
169 | 181 | N:M -> standard python form, means including items N...(M-1). |
|
170 | 182 | |
|
171 | 183 | N-M -> include items N..M (closed endpoint).""" |
|
172 | 184 | |
|
173 | 185 | if raw: |
|
174 | 186 | hist = self.shell.input_hist_raw |
|
175 | 187 | else: |
|
176 | 188 | hist = self.shell.input_hist |
|
177 | 189 | |
|
178 | 190 | cmds = [] |
|
179 | 191 | for chunk in slices: |
|
180 | 192 | if ':' in chunk: |
|
181 | 193 | ini,fin = map(int,chunk.split(':')) |
|
182 | 194 | elif '-' in chunk: |
|
183 | 195 | ini,fin = map(int,chunk.split('-')) |
|
184 | 196 | fin += 1 |
|
185 | 197 | else: |
|
186 | 198 | ini = int(chunk) |
|
187 | 199 | fin = ini+1 |
|
188 | 200 | cmds.append(hist[ini:fin]) |
|
189 | 201 | return cmds |
|
190 | 202 | |
|
191 | 203 | def _ofind(self, oname, namespaces=None): |
|
192 | 204 | """Find an object in the available namespaces. |
|
193 | 205 | |
|
194 | 206 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
195 | 207 | |
|
196 | 208 | Has special code to detect magic functions. |
|
197 | 209 | """ |
|
198 | 210 | |
|
199 | 211 | oname = oname.strip() |
|
200 | 212 | |
|
201 | 213 | alias_ns = None |
|
202 | 214 | if namespaces is None: |
|
203 | 215 | # Namespaces to search in: |
|
204 | 216 | # Put them in a list. The order is important so that we |
|
205 | 217 | # find things in the same order that Python finds them. |
|
206 | 218 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
207 | 219 | ('IPython internal', self.shell.internal_ns), |
|
208 | 220 | ('Python builtin', __builtin__.__dict__), |
|
209 | 221 | ('Alias', self.shell.alias_manager.alias_table), |
|
210 | 222 | ] |
|
211 | 223 | alias_ns = self.shell.alias_manager.alias_table |
|
212 | 224 | |
|
213 | 225 | # initialize results to 'null' |
|
214 | 226 | found = 0; obj = None; ospace = None; ds = None; |
|
215 | 227 | ismagic = 0; isalias = 0; parent = None |
|
216 | 228 | |
|
217 | 229 | # Look for the given name by splitting it in parts. If the head is |
|
218 | 230 | # found, then we look for all the remaining parts as members, and only |
|
219 | 231 | # declare success if we can find them all. |
|
220 | 232 | oname_parts = oname.split('.') |
|
221 | 233 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
222 | 234 | for nsname,ns in namespaces: |
|
223 | 235 | try: |
|
224 | 236 | obj = ns[oname_head] |
|
225 | 237 | except KeyError: |
|
226 | 238 | continue |
|
227 | 239 | else: |
|
228 | 240 | #print 'oname_rest:', oname_rest # dbg |
|
229 | 241 | for part in oname_rest: |
|
230 | 242 | try: |
|
231 | 243 | parent = obj |
|
232 | 244 | obj = getattr(obj,part) |
|
233 | 245 | except: |
|
234 | 246 | # Blanket except b/c some badly implemented objects |
|
235 | 247 | # allow __getattr__ to raise exceptions other than |
|
236 | 248 | # AttributeError, which then crashes IPython. |
|
237 | 249 | break |
|
238 | 250 | else: |
|
239 | 251 | # If we finish the for loop (no break), we got all members |
|
240 | 252 | found = 1 |
|
241 | 253 | ospace = nsname |
|
242 | 254 | if ns == alias_ns: |
|
243 | 255 | isalias = 1 |
|
244 | 256 | break # namespace loop |
|
245 | 257 | |
|
246 | 258 | # Try to see if it's magic |
|
247 | 259 | if not found: |
|
248 | 260 | if oname.startswith(ESC_MAGIC): |
|
249 | 261 | oname = oname[1:] |
|
250 | 262 | obj = getattr(self,'magic_'+oname,None) |
|
251 | 263 | if obj is not None: |
|
252 | 264 | found = 1 |
|
253 | 265 | ospace = 'IPython internal' |
|
254 | 266 | ismagic = 1 |
|
255 | 267 | |
|
256 | 268 | # Last try: special-case some literals like '', [], {}, etc: |
|
257 | 269 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
258 | 270 | obj = eval(oname_head) |
|
259 | 271 | found = 1 |
|
260 | 272 | ospace = 'Interactive' |
|
261 | 273 | |
|
262 | 274 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
263 | 275 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
264 | 276 | |
|
265 | 277 | def arg_err(self,func): |
|
266 | 278 | """Print docstring if incorrect arguments were passed""" |
|
267 | 279 | print 'Error in arguments:' |
|
268 | 280 | print OInspect.getdoc(func) |
|
269 | 281 | |
|
270 | 282 | def format_latex(self,strng): |
|
271 | 283 | """Format a string for latex inclusion.""" |
|
272 | 284 | |
|
273 | 285 | # Characters that need to be escaped for latex: |
|
274 | 286 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
275 | 287 | # Magic command names as headers: |
|
276 | 288 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
277 | 289 | re.MULTILINE) |
|
278 | 290 | # Magic commands |
|
279 | 291 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
280 | 292 | re.MULTILINE) |
|
281 | 293 | # Paragraph continue |
|
282 | 294 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
283 | 295 | |
|
284 | 296 | # The "\n" symbol |
|
285 | 297 | newline_re = re.compile(r'\\n') |
|
286 | 298 | |
|
287 | 299 | # Now build the string for output: |
|
288 | 300 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
289 | 301 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
290 | 302 | strng) |
|
291 | 303 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
292 | 304 | strng = par_re.sub(r'\\\\',strng) |
|
293 | 305 | strng = escape_re.sub(r'\\\1',strng) |
|
294 | 306 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
295 | 307 | return strng |
|
296 | 308 | |
|
297 | 309 | def format_screen(self,strng): |
|
298 | 310 | """Format a string for screen printing. |
|
299 | 311 | |
|
300 | 312 | This removes some latex-type format codes.""" |
|
301 | 313 | # Paragraph continue |
|
302 | 314 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
303 | 315 | strng = par_re.sub('',strng) |
|
304 | 316 | return strng |
|
305 | 317 | |
|
306 | 318 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
307 | 319 | """Parse options passed to an argument string. |
|
308 | 320 | |
|
309 | 321 | The interface is similar to that of getopt(), but it returns back a |
|
310 | 322 | Struct with the options as keys and the stripped argument string still |
|
311 | 323 | as a string. |
|
312 | 324 | |
|
313 | 325 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
314 | 326 | This allows us to easily expand variables, glob files, quote |
|
315 | 327 | arguments, etc. |
|
316 | 328 | |
|
317 | 329 | Options: |
|
318 | 330 | -mode: default 'string'. If given as 'list', the argument string is |
|
319 | 331 | returned as a list (split on whitespace) instead of a string. |
|
320 | 332 | |
|
321 | 333 | -list_all: put all option values in lists. Normally only options |
|
322 | 334 | appearing more than once are put in a list. |
|
323 | 335 | |
|
324 | 336 | -posix (True): whether to split the input line in POSIX mode or not, |
|
325 | 337 | as per the conventions outlined in the shlex module from the |
|
326 | 338 | standard library.""" |
|
327 | 339 | |
|
328 | 340 | # inject default options at the beginning of the input line |
|
329 | 341 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
330 | 342 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
331 | 343 | |
|
332 | 344 | mode = kw.get('mode','string') |
|
333 | 345 | if mode not in ['string','list']: |
|
334 | 346 | raise ValueError,'incorrect mode given: %s' % mode |
|
335 | 347 | # Get options |
|
336 | 348 | list_all = kw.get('list_all',0) |
|
337 |
posix = kw.get('posix', |
|
|
349 | posix = kw.get('posix', os.name == 'posix') | |
|
338 | 350 | |
|
339 | 351 | # Check if we have more than one argument to warrant extra processing: |
|
340 | 352 | odict = {} # Dictionary with options |
|
341 | 353 | args = arg_str.split() |
|
342 | 354 | if len(args) >= 1: |
|
343 | 355 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
344 | 356 | # need to look for options |
|
345 | 357 | argv = arg_split(arg_str,posix) |
|
346 | 358 | # Do regular option processing |
|
347 | 359 | try: |
|
348 | 360 | opts,args = getopt(argv,opt_str,*long_opts) |
|
349 | 361 | except GetoptError,e: |
|
350 | 362 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
351 | 363 | " ".join(long_opts))) |
|
352 | 364 | for o,a in opts: |
|
353 | 365 | if o.startswith('--'): |
|
354 | 366 | o = o[2:] |
|
355 | 367 | else: |
|
356 | 368 | o = o[1:] |
|
357 | 369 | try: |
|
358 | 370 | odict[o].append(a) |
|
359 | 371 | except AttributeError: |
|
360 | 372 | odict[o] = [odict[o],a] |
|
361 | 373 | except KeyError: |
|
362 | 374 | if list_all: |
|
363 | 375 | odict[o] = [a] |
|
364 | 376 | else: |
|
365 | 377 | odict[o] = a |
|
366 | 378 | |
|
367 | 379 | # Prepare opts,args for return |
|
368 | 380 | opts = Struct(odict) |
|
369 | 381 | if mode == 'string': |
|
370 | 382 | args = ' '.join(args) |
|
371 | 383 | |
|
372 | 384 | return opts,args |
|
373 | 385 | |
|
374 | 386 | #...................................................................... |
|
375 | 387 | # And now the actual magic functions |
|
376 | 388 | |
|
377 | 389 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
378 | 390 | def magic_lsmagic(self, parameter_s = ''): |
|
379 | 391 | """List currently available magic functions.""" |
|
380 | 392 | mesc = ESC_MAGIC |
|
381 | 393 | print 'Available magic functions:\n'+mesc+\ |
|
382 | 394 | (' '+mesc).join(self.lsmagic()) |
|
383 | 395 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
384 | 396 | return None |
|
385 | 397 | |
|
386 | 398 | def magic_magic(self, parameter_s = ''): |
|
387 | 399 | """Print information about the magic function system. |
|
388 | 400 | |
|
389 | 401 | Supported formats: -latex, -brief, -rest |
|
390 | 402 | """ |
|
391 | 403 | |
|
392 | 404 | mode = '' |
|
393 | 405 | try: |
|
394 | 406 | if parameter_s.split()[0] == '-latex': |
|
395 | 407 | mode = 'latex' |
|
396 | 408 | if parameter_s.split()[0] == '-brief': |
|
397 | 409 | mode = 'brief' |
|
398 | 410 | if parameter_s.split()[0] == '-rest': |
|
399 | 411 | mode = 'rest' |
|
400 | 412 | rest_docs = [] |
|
401 | 413 | except: |
|
402 | 414 | pass |
|
403 | 415 | |
|
404 | 416 | magic_docs = [] |
|
405 | 417 | for fname in self.lsmagic(): |
|
406 | 418 | mname = 'magic_' + fname |
|
407 | 419 | for space in (Magic,self,self.__class__): |
|
408 | 420 | try: |
|
409 | 421 | fn = space.__dict__[mname] |
|
410 | 422 | except KeyError: |
|
411 | 423 | pass |
|
412 | 424 | else: |
|
413 | 425 | break |
|
414 | 426 | if mode == 'brief': |
|
415 | 427 | # only first line |
|
416 | 428 | if fn.__doc__: |
|
417 | 429 | fndoc = fn.__doc__.split('\n',1)[0] |
|
418 | 430 | else: |
|
419 | 431 | fndoc = 'No documentation' |
|
420 | 432 | else: |
|
421 | 433 | if fn.__doc__: |
|
422 | 434 | fndoc = fn.__doc__.rstrip() |
|
423 | 435 | else: |
|
424 | 436 | fndoc = 'No documentation' |
|
425 | 437 | |
|
426 | 438 | |
|
427 | 439 | if mode == 'rest': |
|
428 | 440 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
429 | 441 | fname,fndoc)) |
|
430 | 442 | |
|
431 | 443 | else: |
|
432 | 444 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
433 | 445 | fname,fndoc)) |
|
434 | 446 | |
|
435 | 447 | magic_docs = ''.join(magic_docs) |
|
436 | 448 | |
|
437 | 449 | if mode == 'rest': |
|
438 | 450 | return "".join(rest_docs) |
|
439 | 451 | |
|
440 | 452 | if mode == 'latex': |
|
441 | 453 | print self.format_latex(magic_docs) |
|
442 | 454 | return |
|
443 | 455 | else: |
|
444 | 456 | magic_docs = self.format_screen(magic_docs) |
|
445 | 457 | if mode == 'brief': |
|
446 | 458 | return magic_docs |
|
447 | 459 | |
|
448 | 460 | outmsg = """ |
|
449 | 461 | IPython's 'magic' functions |
|
450 | 462 | =========================== |
|
451 | 463 | |
|
452 | 464 | The magic function system provides a series of functions which allow you to |
|
453 | 465 | control the behavior of IPython itself, plus a lot of system-type |
|
454 | 466 | features. All these functions are prefixed with a % character, but parameters |
|
455 | 467 | are given without parentheses or quotes. |
|
456 | 468 | |
|
457 | 469 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
458 | 470 | %automagic function), you don't need to type in the % explicitly. By default, |
|
459 | 471 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
460 | 472 | |
|
461 | 473 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
462 | 474 | to 'mydir', if it exists. |
|
463 | 475 | |
|
464 | 476 | You can define your own magic functions to extend the system. See the supplied |
|
465 | 477 | ipythonrc and example-magic.py files for details (in your ipython |
|
466 | 478 | configuration directory, typically $HOME/.ipython/). |
|
467 | 479 | |
|
468 | 480 | You can also define your own aliased names for magic functions. In your |
|
469 | 481 | ipythonrc file, placing a line like: |
|
470 | 482 | |
|
471 | 483 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
472 | 484 | |
|
473 | 485 | will define %pf as a new name for %profile. |
|
474 | 486 | |
|
475 | 487 | You can also call magics in code using the magic() function, which IPython |
|
476 | 488 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
477 | 489 | |
|
478 | 490 | For a list of the available magic functions, use %lsmagic. For a description |
|
479 | 491 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
480 | 492 | |
|
481 | 493 | Currently the magic system has the following functions:\n""" |
|
482 | 494 | |
|
483 | 495 | mesc = ESC_MAGIC |
|
484 | 496 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
485 | 497 | "\n\n%s%s\n\n%s" % (outmsg, |
|
486 | 498 | magic_docs,mesc,mesc, |
|
487 | 499 | (' '+mesc).join(self.lsmagic()), |
|
488 | 500 | Magic.auto_status[self.shell.automagic] ) ) |
|
489 | 501 | |
|
490 | 502 | page(outmsg,screen_lines=self.shell.usable_screen_length) |
|
491 | 503 | |
|
492 | 504 | |
|
493 | 505 | def magic_autoindent(self, parameter_s = ''): |
|
494 | 506 | """Toggle autoindent on/off (if available).""" |
|
495 | 507 | |
|
496 | 508 | self.shell.set_autoindent() |
|
497 | 509 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
498 | 510 | |
|
499 | 511 | |
|
500 | 512 | def magic_automagic(self, parameter_s = ''): |
|
501 | 513 | """Make magic functions callable without having to type the initial %. |
|
502 | 514 | |
|
503 | 515 | Without argumentsl toggles on/off (when off, you must call it as |
|
504 | 516 | %automagic, of course). With arguments it sets the value, and you can |
|
505 | 517 | use any of (case insensitive): |
|
506 | 518 | |
|
507 | 519 | - on,1,True: to activate |
|
508 | 520 | |
|
509 | 521 | - off,0,False: to deactivate. |
|
510 | 522 | |
|
511 | 523 | Note that magic functions have lowest priority, so if there's a |
|
512 | 524 | variable whose name collides with that of a magic fn, automagic won't |
|
513 | 525 | work for that function (you get the variable instead). However, if you |
|
514 | 526 | delete the variable (del var), the previously shadowed magic function |
|
515 | 527 | becomes visible to automagic again.""" |
|
516 | 528 | |
|
517 | 529 | arg = parameter_s.lower() |
|
518 | 530 | if parameter_s in ('on','1','true'): |
|
519 | 531 | self.shell.automagic = True |
|
520 | 532 | elif parameter_s in ('off','0','false'): |
|
521 | 533 | self.shell.automagic = False |
|
522 | 534 | else: |
|
523 | 535 | self.shell.automagic = not self.shell.automagic |
|
524 | 536 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
525 | 537 | |
|
526 | 538 | @testdec.skip_doctest |
|
527 | 539 | def magic_autocall(self, parameter_s = ''): |
|
528 | 540 | """Make functions callable without having to type parentheses. |
|
529 | 541 | |
|
530 | 542 | Usage: |
|
531 | 543 | |
|
532 | 544 | %autocall [mode] |
|
533 | 545 | |
|
534 | 546 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
535 | 547 | value is toggled on and off (remembering the previous state). |
|
536 | 548 | |
|
537 | 549 | In more detail, these values mean: |
|
538 | 550 | |
|
539 | 551 | 0 -> fully disabled |
|
540 | 552 | |
|
541 | 553 | 1 -> active, but do not apply if there are no arguments on the line. |
|
542 | 554 | |
|
543 | 555 | In this mode, you get: |
|
544 | 556 | |
|
545 | 557 | In [1]: callable |
|
546 | 558 | Out[1]: <built-in function callable> |
|
547 | 559 | |
|
548 | 560 | In [2]: callable 'hello' |
|
549 | 561 | ------> callable('hello') |
|
550 | 562 | Out[2]: False |
|
551 | 563 | |
|
552 | 564 | 2 -> Active always. Even if no arguments are present, the callable |
|
553 | 565 | object is called: |
|
554 | 566 | |
|
555 | 567 | In [2]: float |
|
556 | 568 | ------> float() |
|
557 | 569 | Out[2]: 0.0 |
|
558 | 570 | |
|
559 | 571 | Note that even with autocall off, you can still use '/' at the start of |
|
560 | 572 | a line to treat the first argument on the command line as a function |
|
561 | 573 | and add parentheses to it: |
|
562 | 574 | |
|
563 | 575 | In [8]: /str 43 |
|
564 | 576 | ------> str(43) |
|
565 | 577 | Out[8]: '43' |
|
566 | 578 | |
|
567 | 579 | # all-random (note for auto-testing) |
|
568 | 580 | """ |
|
569 | 581 | |
|
570 | 582 | if parameter_s: |
|
571 | 583 | arg = int(parameter_s) |
|
572 | 584 | else: |
|
573 | 585 | arg = 'toggle' |
|
574 | 586 | |
|
575 | 587 | if not arg in (0,1,2,'toggle'): |
|
576 | 588 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
577 | 589 | return |
|
578 | 590 | |
|
579 | 591 | if arg in (0,1,2): |
|
580 | 592 | self.shell.autocall = arg |
|
581 | 593 | else: # toggle |
|
582 | 594 | if self.shell.autocall: |
|
583 | 595 | self._magic_state.autocall_save = self.shell.autocall |
|
584 | 596 | self.shell.autocall = 0 |
|
585 | 597 | else: |
|
586 | 598 | try: |
|
587 | 599 | self.shell.autocall = self._magic_state.autocall_save |
|
588 | 600 | except AttributeError: |
|
589 | 601 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
590 | 602 | |
|
591 | 603 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
592 | 604 | |
|
593 | 605 | def magic_system_verbose(self, parameter_s = ''): |
|
594 | 606 | """Set verbose printing of system calls. |
|
595 | 607 | |
|
596 | 608 | If called without an argument, act as a toggle""" |
|
597 | 609 | |
|
598 | 610 | if parameter_s: |
|
599 | 611 | val = bool(eval(parameter_s)) |
|
600 | 612 | else: |
|
601 | 613 | val = None |
|
602 | 614 | |
|
603 | 615 | if self.shell.system_verbose: |
|
604 | 616 | self.shell.system_verbose = False |
|
605 | 617 | else: |
|
606 | 618 | self.shell.system_verbose = True |
|
607 | 619 | print "System verbose printing is:",\ |
|
608 | 620 | ['OFF','ON'][self.shell.system_verbose] |
|
609 | 621 | |
|
610 | 622 | |
|
611 | 623 | def magic_page(self, parameter_s=''): |
|
612 | 624 | """Pretty print the object and display it through a pager. |
|
613 | 625 | |
|
614 | 626 | %page [options] OBJECT |
|
615 | 627 | |
|
616 | 628 | If no object is given, use _ (last output). |
|
617 | 629 | |
|
618 | 630 | Options: |
|
619 | 631 | |
|
620 | 632 | -r: page str(object), don't pretty-print it.""" |
|
621 | 633 | |
|
622 | 634 | # After a function contributed by Olivier Aubert, slightly modified. |
|
623 | 635 | |
|
624 | 636 | # Process options/args |
|
625 | 637 | opts,args = self.parse_options(parameter_s,'r') |
|
626 | 638 | raw = 'r' in opts |
|
627 | 639 | |
|
628 | 640 | oname = args and args or '_' |
|
629 | 641 | info = self._ofind(oname) |
|
630 | 642 | if info['found']: |
|
631 | 643 | txt = (raw and str or pformat)( info['obj'] ) |
|
632 | 644 | page(txt) |
|
633 | 645 | else: |
|
634 | 646 | print 'Object `%s` not found' % oname |
|
635 | 647 | |
|
636 | 648 | def magic_profile(self, parameter_s=''): |
|
637 | 649 | """Print your currently active IPyhton profile.""" |
|
638 | 650 | if self.shell.profile: |
|
639 | 651 | printpl('Current IPython profile: $self.shell.profile.') |
|
640 | 652 | else: |
|
641 | 653 | print 'No profile active.' |
|
642 | 654 | |
|
643 | 655 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
644 | 656 | """Provide detailed information about an object. |
|
645 | 657 | |
|
646 | 658 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
647 | 659 | |
|
648 | 660 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
649 | 661 | |
|
650 | 662 | |
|
651 | 663 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
652 | 664 | detail_level = 0 |
|
653 | 665 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
654 | 666 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
655 | 667 | pinfo,qmark1,oname,qmark2 = \ |
|
656 | 668 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
657 | 669 | if pinfo or qmark1 or qmark2: |
|
658 | 670 | detail_level = 1 |
|
659 | 671 | if "*" in oname: |
|
660 | 672 | self.magic_psearch(oname) |
|
661 | 673 | else: |
|
662 | 674 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
663 | 675 | namespaces=namespaces) |
|
664 | 676 | |
|
665 | 677 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
666 | 678 | """Print the definition header for any callable object. |
|
667 | 679 | |
|
668 | 680 | If the object is a class, print the constructor information.""" |
|
669 | 681 | self._inspect('pdef',parameter_s, namespaces) |
|
670 | 682 | |
|
671 | 683 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
672 | 684 | """Print the docstring for an object. |
|
673 | 685 | |
|
674 | 686 | If the given object is a class, it will print both the class and the |
|
675 | 687 | constructor docstrings.""" |
|
676 | 688 | self._inspect('pdoc',parameter_s, namespaces) |
|
677 | 689 | |
|
678 | 690 | def magic_psource(self, parameter_s='', namespaces=None): |
|
679 | 691 | """Print (or run through pager) the source code for an object.""" |
|
680 | 692 | self._inspect('psource',parameter_s, namespaces) |
|
681 | 693 | |
|
682 | 694 | def magic_pfile(self, parameter_s=''): |
|
683 | 695 | """Print (or run through pager) the file where an object is defined. |
|
684 | 696 | |
|
685 | 697 | The file opens at the line where the object definition begins. IPython |
|
686 | 698 | will honor the environment variable PAGER if set, and otherwise will |
|
687 | 699 | do its best to print the file in a convenient form. |
|
688 | 700 | |
|
689 | 701 | If the given argument is not an object currently defined, IPython will |
|
690 | 702 | try to interpret it as a filename (automatically adding a .py extension |
|
691 | 703 | if needed). You can thus use %pfile as a syntax highlighting code |
|
692 | 704 | viewer.""" |
|
693 | 705 | |
|
694 | 706 | # first interpret argument as an object name |
|
695 | 707 | out = self._inspect('pfile',parameter_s) |
|
696 | 708 | # if not, try the input as a filename |
|
697 | 709 | if out == 'not found': |
|
698 | 710 | try: |
|
699 | 711 | filename = get_py_filename(parameter_s) |
|
700 | 712 | except IOError,msg: |
|
701 | 713 | print msg |
|
702 | 714 | return |
|
703 | 715 | page(self.shell.inspector.format(file(filename).read())) |
|
704 | 716 | |
|
705 | 717 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
706 | 718 | """Generic interface to the inspector system. |
|
707 | 719 | |
|
708 | 720 | This function is meant to be called by pdef, pdoc & friends.""" |
|
709 | 721 | |
|
710 | 722 | #oname = oname.strip() |
|
711 | 723 | #print '1- oname: <%r>' % oname # dbg |
|
712 | 724 | try: |
|
713 | 725 | oname = oname.strip().encode('ascii') |
|
714 | 726 | #print '2- oname: <%r>' % oname # dbg |
|
715 | 727 | except UnicodeEncodeError: |
|
716 | 728 | print 'Python identifiers can only contain ascii characters.' |
|
717 | 729 | return 'not found' |
|
718 | 730 | |
|
719 | 731 | info = Struct(self._ofind(oname, namespaces)) |
|
720 | 732 | |
|
721 | 733 | if info.found: |
|
722 | 734 | try: |
|
723 | 735 | IPython.utils.generics.inspect_object(info.obj) |
|
724 | 736 | return |
|
725 | 737 | except TryNext: |
|
726 | 738 | pass |
|
727 | 739 | # Get the docstring of the class property if it exists. |
|
728 | 740 | path = oname.split('.') |
|
729 | 741 | root = '.'.join(path[:-1]) |
|
730 | 742 | if info.parent is not None: |
|
731 | 743 | try: |
|
732 | 744 | target = getattr(info.parent, '__class__') |
|
733 | 745 | # The object belongs to a class instance. |
|
734 | 746 | try: |
|
735 | 747 | target = getattr(target, path[-1]) |
|
736 | 748 | # The class defines the object. |
|
737 | 749 | if isinstance(target, property): |
|
738 | 750 | oname = root + '.__class__.' + path[-1] |
|
739 | 751 | info = Struct(self._ofind(oname)) |
|
740 | 752 | except AttributeError: pass |
|
741 | 753 | except AttributeError: pass |
|
742 | 754 | |
|
743 | 755 | pmethod = getattr(self.shell.inspector,meth) |
|
744 | 756 | formatter = info.ismagic and self.format_screen or None |
|
745 | 757 | if meth == 'pdoc': |
|
746 | 758 | pmethod(info.obj,oname,formatter) |
|
747 | 759 | elif meth == 'pinfo': |
|
748 | 760 | pmethod(info.obj,oname,formatter,info,**kw) |
|
749 | 761 | else: |
|
750 | 762 | pmethod(info.obj,oname) |
|
751 | 763 | else: |
|
752 | 764 | print 'Object `%s` not found.' % oname |
|
753 | 765 | return 'not found' # so callers can take other action |
|
754 | 766 | |
|
755 | 767 | def magic_psearch(self, parameter_s=''): |
|
756 | 768 | """Search for object in namespaces by wildcard. |
|
757 | 769 | |
|
758 | 770 | %psearch [options] PATTERN [OBJECT TYPE] |
|
759 | 771 | |
|
760 | 772 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
761 | 773 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
762 | 774 | rest of the command line must be unchanged (options come first), so |
|
763 | 775 | for example the following forms are equivalent |
|
764 | 776 | |
|
765 | 777 | %psearch -i a* function |
|
766 | 778 | -i a* function? |
|
767 | 779 | ?-i a* function |
|
768 | 780 | |
|
769 | 781 | Arguments: |
|
770 | 782 | |
|
771 | 783 | PATTERN |
|
772 | 784 | |
|
773 | 785 | where PATTERN is a string containing * as a wildcard similar to its |
|
774 | 786 | use in a shell. The pattern is matched in all namespaces on the |
|
775 | 787 | search path. By default objects starting with a single _ are not |
|
776 | 788 | matched, many IPython generated objects have a single |
|
777 | 789 | underscore. The default is case insensitive matching. Matching is |
|
778 | 790 | also done on the attributes of objects and not only on the objects |
|
779 | 791 | in a module. |
|
780 | 792 | |
|
781 | 793 | [OBJECT TYPE] |
|
782 | 794 | |
|
783 | 795 | Is the name of a python type from the types module. The name is |
|
784 | 796 | given in lowercase without the ending type, ex. StringType is |
|
785 | 797 | written string. By adding a type here only objects matching the |
|
786 | 798 | given type are matched. Using all here makes the pattern match all |
|
787 | 799 | types (this is the default). |
|
788 | 800 | |
|
789 | 801 | Options: |
|
790 | 802 | |
|
791 | 803 | -a: makes the pattern match even objects whose names start with a |
|
792 | 804 | single underscore. These names are normally ommitted from the |
|
793 | 805 | search. |
|
794 | 806 | |
|
795 | 807 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
796 | 808 | these options is given, the default is read from your ipythonrc |
|
797 | 809 | file. The option name which sets this value is |
|
798 | 810 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
799 | 811 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
800 | 812 | search. |
|
801 | 813 | |
|
802 | 814 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
803 | 815 | specifiy can be searched in any of the following namespaces: |
|
804 | 816 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
805 | 817 | 'builtin' and 'user' are the search defaults. Note that you should |
|
806 | 818 | not use quotes when specifying namespaces. |
|
807 | 819 | |
|
808 | 820 | 'Builtin' contains the python module builtin, 'user' contains all |
|
809 | 821 | user data, 'alias' only contain the shell aliases and no python |
|
810 | 822 | objects, 'internal' contains objects used by IPython. The |
|
811 | 823 | 'user_global' namespace is only used by embedded IPython instances, |
|
812 | 824 | and it contains module-level globals. You can add namespaces to the |
|
813 | 825 | search with -s or exclude them with -e (these options can be given |
|
814 | 826 | more than once). |
|
815 | 827 | |
|
816 | 828 | Examples: |
|
817 | 829 | |
|
818 | 830 | %psearch a* -> objects beginning with an a |
|
819 | 831 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
820 | 832 | %psearch a* function -> all functions beginning with an a |
|
821 | 833 | %psearch re.e* -> objects beginning with an e in module re |
|
822 | 834 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
823 | 835 | %psearch r*.* string -> all strings in modules beginning with r |
|
824 | 836 | |
|
825 | 837 | Case sensitve search: |
|
826 | 838 | |
|
827 | 839 | %psearch -c a* list all object beginning with lower case a |
|
828 | 840 | |
|
829 | 841 | Show objects beginning with a single _: |
|
830 | 842 | |
|
831 | 843 | %psearch -a _* list objects beginning with a single underscore""" |
|
832 | 844 | try: |
|
833 | 845 | parameter_s = parameter_s.encode('ascii') |
|
834 | 846 | except UnicodeEncodeError: |
|
835 | 847 | print 'Python identifiers can only contain ascii characters.' |
|
836 | 848 | return |
|
837 | 849 | |
|
838 | 850 | # default namespaces to be searched |
|
839 | 851 | def_search = ['user','builtin'] |
|
840 | 852 | |
|
841 | 853 | # Process options/args |
|
842 | 854 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
843 | 855 | opt = opts.get |
|
844 | 856 | shell = self.shell |
|
845 | 857 | psearch = shell.inspector.psearch |
|
846 | 858 | |
|
847 | 859 | # select case options |
|
848 | 860 | if opts.has_key('i'): |
|
849 | 861 | ignore_case = True |
|
850 | 862 | elif opts.has_key('c'): |
|
851 | 863 | ignore_case = False |
|
852 | 864 | else: |
|
853 | 865 | ignore_case = not shell.wildcards_case_sensitive |
|
854 | 866 | |
|
855 | 867 | # Build list of namespaces to search from user options |
|
856 | 868 | def_search.extend(opt('s',[])) |
|
857 | 869 | ns_exclude = ns_exclude=opt('e',[]) |
|
858 | 870 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
859 | 871 | |
|
860 | 872 | # Call the actual search |
|
861 | 873 | try: |
|
862 | 874 | psearch(args,shell.ns_table,ns_search, |
|
863 | 875 | show_all=opt('a'),ignore_case=ignore_case) |
|
864 | 876 | except: |
|
865 | 877 | shell.showtraceback() |
|
866 | 878 | |
|
867 | 879 | def magic_who_ls(self, parameter_s=''): |
|
868 | 880 | """Return a sorted list of all interactive variables. |
|
869 | 881 | |
|
870 | 882 | If arguments are given, only variables of types matching these |
|
871 | 883 | arguments are returned.""" |
|
872 | 884 | |
|
873 | 885 | user_ns = self.shell.user_ns |
|
874 | 886 | internal_ns = self.shell.internal_ns |
|
875 | 887 | user_config_ns = self.shell.user_config_ns |
|
876 |
out = [ |
|
|
877 | typelist = parameter_s.split() | |
|
888 | out = [ i for i in user_ns | |
|
889 | if not i.startswith('_') \ | |
|
890 | and not (i in internal_ns or i in user_config_ns) ] | |
|
878 | 891 | |
|
879 | for i in user_ns: | |
|
880 | if not (i.startswith('_') or i.startswith('_i')) \ | |
|
881 | and not (i in internal_ns or i in user_config_ns): | |
|
892 | typelist = parameter_s.split() | |
|
882 | 893 |
|
|
883 | if type(user_ns[i]).__name__ in typelist: | |
|
884 | out.append(i) | |
|
885 | else: | |
|
886 | out.append(i) | |
|
894 | typeset = set(typelist) | |
|
895 | out = [i for i in out if type(i).__name__ in typeset] | |
|
896 | ||
|
887 | 897 | out.sort() |
|
888 | 898 | return out |
|
889 | 899 | |
|
890 | 900 | def magic_who(self, parameter_s=''): |
|
891 | 901 | """Print all interactive variables, with some minimal formatting. |
|
892 | 902 | |
|
893 | 903 | If any arguments are given, only variables whose type matches one of |
|
894 | 904 | these are printed. For example: |
|
895 | 905 | |
|
896 | 906 | %who function str |
|
897 | 907 | |
|
898 | 908 | will only list functions and strings, excluding all other types of |
|
899 | 909 | variables. To find the proper type names, simply use type(var) at a |
|
900 | 910 | command line to see how python prints type names. For example: |
|
901 | 911 | |
|
902 | 912 | In [1]: type('hello')\\ |
|
903 | 913 | Out[1]: <type 'str'> |
|
904 | 914 | |
|
905 | 915 | indicates that the type name for strings is 'str'. |
|
906 | 916 | |
|
907 | 917 | %who always excludes executed names loaded through your configuration |
|
908 | 918 | file and things which are internal to IPython. |
|
909 | 919 | |
|
910 | 920 | This is deliberate, as typically you may load many modules and the |
|
911 | 921 | purpose of %who is to show you only what you've manually defined.""" |
|
912 | 922 | |
|
913 | 923 | varlist = self.magic_who_ls(parameter_s) |
|
914 | 924 | if not varlist: |
|
915 | 925 | if parameter_s: |
|
916 | 926 | print 'No variables match your requested type.' |
|
917 | 927 | else: |
|
918 | 928 | print 'Interactive namespace is empty.' |
|
919 | 929 | return |
|
920 | 930 | |
|
921 | 931 | # if we have variables, move on... |
|
922 | 932 | count = 0 |
|
923 | 933 | for i in varlist: |
|
924 | 934 | print i+'\t', |
|
925 | 935 | count += 1 |
|
926 | 936 | if count > 8: |
|
927 | 937 | count = 0 |
|
928 | 938 | |
|
929 | 939 | |
|
930 | 940 | |
|
931 | 941 | def magic_whos(self, parameter_s=''): |
|
932 | 942 | """Like %who, but gives some extra information about each variable. |
|
933 | 943 | |
|
934 | 944 | The same type filtering of %who can be applied here. |
|
935 | 945 | |
|
936 | 946 | For all variables, the type is printed. Additionally it prints: |
|
937 | 947 | |
|
938 | 948 | - For {},[],(): their length. |
|
939 | 949 | |
|
940 | 950 | - For numpy and Numeric arrays, a summary with shape, number of |
|
941 | 951 | elements, typecode and size in memory. |
|
942 | 952 | |
|
943 | 953 | - Everything else: a string representation, snipping their middle if |
|
944 | 954 | too long.""" |
|
945 | 955 | |
|
946 | 956 | varnames = self.magic_who_ls(parameter_s) |
|
947 | 957 | if not varnames: |
|
948 | 958 | if parameter_s: |
|
949 | 959 | print 'No variables match your requested type.' |
|
950 | 960 | else: |
|
951 | 961 | print 'Interactive namespace is empty.' |
|
952 | 962 | return |
|
953 | 963 | |
|
954 | 964 | # if we have variables, move on... |
|
955 | 965 | |
|
956 | 966 | # for these types, show len() instead of data: |
|
957 | 967 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
958 | 968 | |
|
959 | 969 | # for numpy/Numeric arrays, display summary info |
|
960 | 970 | try: |
|
961 | 971 | import numpy |
|
962 | 972 | except ImportError: |
|
963 | 973 | ndarray_type = None |
|
964 | 974 | else: |
|
965 | 975 | ndarray_type = numpy.ndarray.__name__ |
|
966 | 976 | try: |
|
967 | 977 | import Numeric |
|
968 | 978 | except ImportError: |
|
969 | 979 | array_type = None |
|
970 | 980 | else: |
|
971 | 981 | array_type = Numeric.ArrayType.__name__ |
|
972 | 982 | |
|
973 | 983 | # Find all variable names and types so we can figure out column sizes |
|
974 | 984 | def get_vars(i): |
|
975 | 985 | return self.shell.user_ns[i] |
|
976 | 986 | |
|
977 | 987 | # some types are well known and can be shorter |
|
978 | 988 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
979 | 989 | def type_name(v): |
|
980 | 990 | tn = type(v).__name__ |
|
981 | 991 | return abbrevs.get(tn,tn) |
|
982 | 992 | |
|
983 | 993 | varlist = map(get_vars,varnames) |
|
984 | 994 | |
|
985 | 995 | typelist = [] |
|
986 | 996 | for vv in varlist: |
|
987 | 997 | tt = type_name(vv) |
|
988 | 998 | |
|
989 | 999 | if tt=='instance': |
|
990 | 1000 | typelist.append( abbrevs.get(str(vv.__class__), |
|
991 | 1001 | str(vv.__class__))) |
|
992 | 1002 | else: |
|
993 | 1003 | typelist.append(tt) |
|
994 | 1004 | |
|
995 | 1005 | # column labels and # of spaces as separator |
|
996 | 1006 | varlabel = 'Variable' |
|
997 | 1007 | typelabel = 'Type' |
|
998 | 1008 | datalabel = 'Data/Info' |
|
999 | 1009 | colsep = 3 |
|
1000 | 1010 | # variable format strings |
|
1001 | 1011 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
1002 | 1012 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
1003 | 1013 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1004 | 1014 | # find the size of the columns to format the output nicely |
|
1005 | 1015 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1006 | 1016 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1007 | 1017 | # table header |
|
1008 | 1018 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1009 | 1019 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1010 | 1020 | # and the table itself |
|
1011 | 1021 | kb = 1024 |
|
1012 | 1022 | Mb = 1048576 # kb**2 |
|
1013 | 1023 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1014 | 1024 | print itpl(vformat), |
|
1015 | 1025 | if vtype in seq_types: |
|
1016 | 1026 | print len(var) |
|
1017 | 1027 | elif vtype in [array_type,ndarray_type]: |
|
1018 | 1028 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1019 | 1029 | if vtype==ndarray_type: |
|
1020 | 1030 | # numpy |
|
1021 | 1031 | vsize = var.size |
|
1022 | 1032 | vbytes = vsize*var.itemsize |
|
1023 | 1033 | vdtype = var.dtype |
|
1024 | 1034 | else: |
|
1025 | 1035 | # Numeric |
|
1026 | 1036 | vsize = Numeric.size(var) |
|
1027 | 1037 | vbytes = vsize*var.itemsize() |
|
1028 | 1038 | vdtype = var.typecode() |
|
1029 | 1039 | |
|
1030 | 1040 | if vbytes < 100000: |
|
1031 | 1041 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1032 | 1042 | else: |
|
1033 | 1043 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1034 | 1044 | if vbytes < Mb: |
|
1035 | 1045 | print '(%s kb)' % (vbytes/kb,) |
|
1036 | 1046 | else: |
|
1037 | 1047 | print '(%s Mb)' % (vbytes/Mb,) |
|
1038 | 1048 | else: |
|
1039 | 1049 | try: |
|
1040 | 1050 | vstr = str(var) |
|
1041 | 1051 | except UnicodeEncodeError: |
|
1042 | 1052 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1043 | 1053 | 'backslashreplace') |
|
1044 | 1054 | vstr = vstr.replace('\n','\\n') |
|
1045 | 1055 | if len(vstr) < 50: |
|
1046 | 1056 | print vstr |
|
1047 | 1057 | else: |
|
1048 | 1058 | printpl(vfmt_short) |
|
1049 | 1059 | |
|
1050 | 1060 | def magic_reset(self, parameter_s=''): |
|
1051 | 1061 | """Resets the namespace by removing all names defined by the user. |
|
1052 | 1062 | |
|
1053 | 1063 | Input/Output history are left around in case you need them. |
|
1054 | 1064 | |
|
1055 | 1065 | Parameters |
|
1056 | 1066 | ---------- |
|
1057 | 1067 | -y : force reset without asking for confirmation. |
|
1058 | 1068 | |
|
1059 | 1069 | Examples |
|
1060 | 1070 | -------- |
|
1061 | 1071 | In [6]: a = 1 |
|
1062 | 1072 | |
|
1063 | 1073 | In [7]: a |
|
1064 | 1074 | Out[7]: 1 |
|
1065 | 1075 | |
|
1066 | 1076 | In [8]: 'a' in _ip.user_ns |
|
1067 | 1077 | Out[8]: True |
|
1068 | 1078 | |
|
1069 | 1079 | In [9]: %reset -f |
|
1070 | 1080 | |
|
1071 | 1081 | In [10]: 'a' in _ip.user_ns |
|
1072 | 1082 | Out[10]: False |
|
1073 | 1083 | """ |
|
1074 | 1084 | |
|
1075 | 1085 | if parameter_s == '-f': |
|
1076 | 1086 | ans = True |
|
1077 | 1087 | else: |
|
1078 | 1088 | ans = self.shell.ask_yes_no( |
|
1079 | 1089 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1080 | 1090 | if not ans: |
|
1081 | 1091 | print 'Nothing done.' |
|
1082 | 1092 | return |
|
1083 | 1093 | user_ns = self.shell.user_ns |
|
1084 | 1094 | for i in self.magic_who_ls(): |
|
1085 | 1095 | del(user_ns[i]) |
|
1086 | 1096 | |
|
1087 | 1097 | # Also flush the private list of module references kept for script |
|
1088 | 1098 | # execution protection |
|
1089 | 1099 | self.shell.clear_main_mod_cache() |
|
1090 | 1100 | |
|
1091 | 1101 | def magic_logstart(self,parameter_s=''): |
|
1092 | 1102 | """Start logging anywhere in a session. |
|
1093 | 1103 | |
|
1094 | 1104 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1095 | 1105 | |
|
1096 | 1106 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1097 | 1107 | current directory, in 'rotate' mode (see below). |
|
1098 | 1108 | |
|
1099 | 1109 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1100 | 1110 | history up to that point and then continues logging. |
|
1101 | 1111 | |
|
1102 | 1112 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1103 | 1113 | of (note that the modes are given unquoted):\\ |
|
1104 | 1114 | append: well, that says it.\\ |
|
1105 | 1115 | backup: rename (if exists) to name~ and start name.\\ |
|
1106 | 1116 | global: single logfile in your home dir, appended to.\\ |
|
1107 | 1117 | over : overwrite existing log.\\ |
|
1108 | 1118 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1109 | 1119 | |
|
1110 | 1120 | Options: |
|
1111 | 1121 | |
|
1112 | 1122 | -o: log also IPython's output. In this mode, all commands which |
|
1113 | 1123 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1114 | 1124 | their corresponding input line. The output lines are always |
|
1115 | 1125 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1116 | 1126 | Python code. |
|
1117 | 1127 | |
|
1118 | 1128 | Since this marker is always the same, filtering only the output from |
|
1119 | 1129 | a log is very easy, using for example a simple awk call: |
|
1120 | 1130 | |
|
1121 | 1131 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1122 | 1132 | |
|
1123 | 1133 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1124 | 1134 | input, so that user lines are logged in their final form, converted |
|
1125 | 1135 | into valid Python. For example, %Exit is logged as |
|
1126 | 1136 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1127 | 1137 | exactly as typed, with no transformations applied. |
|
1128 | 1138 | |
|
1129 | 1139 | -t: put timestamps before each input line logged (these are put in |
|
1130 | 1140 | comments).""" |
|
1131 | 1141 | |
|
1132 | 1142 | opts,par = self.parse_options(parameter_s,'ort') |
|
1133 | 1143 | log_output = 'o' in opts |
|
1134 | 1144 | log_raw_input = 'r' in opts |
|
1135 | 1145 | timestamp = 't' in opts |
|
1136 | 1146 | |
|
1137 | 1147 | logger = self.shell.logger |
|
1138 | 1148 | |
|
1139 | 1149 | # if no args are given, the defaults set in the logger constructor by |
|
1140 | 1150 | # ipytohn remain valid |
|
1141 | 1151 | if par: |
|
1142 | 1152 | try: |
|
1143 | 1153 | logfname,logmode = par.split() |
|
1144 | 1154 | except: |
|
1145 | 1155 | logfname = par |
|
1146 | 1156 | logmode = 'backup' |
|
1147 | 1157 | else: |
|
1148 | 1158 | logfname = logger.logfname |
|
1149 | 1159 | logmode = logger.logmode |
|
1150 | 1160 | # put logfname into rc struct as if it had been called on the command |
|
1151 | 1161 | # line, so it ends up saved in the log header Save it in case we need |
|
1152 | 1162 | # to restore it... |
|
1153 | 1163 | old_logfile = self.shell.logfile |
|
1154 | 1164 | if logfname: |
|
1155 | 1165 | logfname = os.path.expanduser(logfname) |
|
1156 | 1166 | self.shell.logfile = logfname |
|
1157 | 1167 | |
|
1158 | 1168 | loghead = '# IPython log file\n\n' |
|
1159 | 1169 | try: |
|
1160 | 1170 | started = logger.logstart(logfname,loghead,logmode, |
|
1161 | 1171 | log_output,timestamp,log_raw_input) |
|
1162 | 1172 | except: |
|
1163 | 1173 | rc.opts.logfile = old_logfile |
|
1164 | 1174 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1165 | 1175 | else: |
|
1166 | 1176 | # log input history up to this point, optionally interleaving |
|
1167 | 1177 | # output if requested |
|
1168 | 1178 | |
|
1169 | 1179 | if timestamp: |
|
1170 | 1180 | # disable timestamping for the previous history, since we've |
|
1171 | 1181 | # lost those already (no time machine here). |
|
1172 | 1182 | logger.timestamp = False |
|
1173 | 1183 | |
|
1174 | 1184 | if log_raw_input: |
|
1175 | 1185 | input_hist = self.shell.input_hist_raw |
|
1176 | 1186 | else: |
|
1177 | 1187 | input_hist = self.shell.input_hist |
|
1178 | 1188 | |
|
1179 | 1189 | if log_output: |
|
1180 | 1190 | log_write = logger.log_write |
|
1181 | 1191 | output_hist = self.shell.output_hist |
|
1182 | 1192 | for n in range(1,len(input_hist)-1): |
|
1183 | 1193 | log_write(input_hist[n].rstrip()) |
|
1184 | 1194 | if n in output_hist: |
|
1185 | 1195 | log_write(repr(output_hist[n]),'output') |
|
1186 | 1196 | else: |
|
1187 | 1197 | logger.log_write(input_hist[1:]) |
|
1188 | 1198 | if timestamp: |
|
1189 | 1199 | # re-enable timestamping |
|
1190 | 1200 | logger.timestamp = True |
|
1191 | 1201 | |
|
1192 | 1202 | print ('Activating auto-logging. ' |
|
1193 | 1203 | 'Current session state plus future input saved.') |
|
1194 | 1204 | logger.logstate() |
|
1195 | 1205 | |
|
1196 | 1206 | def magic_logstop(self,parameter_s=''): |
|
1197 | 1207 | """Fully stop logging and close log file. |
|
1198 | 1208 | |
|
1199 | 1209 | In order to start logging again, a new %logstart call needs to be made, |
|
1200 | 1210 | possibly (though not necessarily) with a new filename, mode and other |
|
1201 | 1211 | options.""" |
|
1202 | 1212 | self.logger.logstop() |
|
1203 | 1213 | |
|
1204 | 1214 | def magic_logoff(self,parameter_s=''): |
|
1205 | 1215 | """Temporarily stop logging. |
|
1206 | 1216 | |
|
1207 | 1217 | You must have previously started logging.""" |
|
1208 | 1218 | self.shell.logger.switch_log(0) |
|
1209 | 1219 | |
|
1210 | 1220 | def magic_logon(self,parameter_s=''): |
|
1211 | 1221 | """Restart logging. |
|
1212 | 1222 | |
|
1213 | 1223 | This function is for restarting logging which you've temporarily |
|
1214 | 1224 | stopped with %logoff. For starting logging for the first time, you |
|
1215 | 1225 | must use the %logstart function, which allows you to specify an |
|
1216 | 1226 | optional log filename.""" |
|
1217 | 1227 | |
|
1218 | 1228 | self.shell.logger.switch_log(1) |
|
1219 | 1229 | |
|
1220 | 1230 | def magic_logstate(self,parameter_s=''): |
|
1221 | 1231 | """Print the status of the logging system.""" |
|
1222 | 1232 | |
|
1223 | 1233 | self.shell.logger.logstate() |
|
1224 | 1234 | |
|
1225 | 1235 | def magic_pdb(self, parameter_s=''): |
|
1226 | 1236 | """Control the automatic calling of the pdb interactive debugger. |
|
1227 | 1237 | |
|
1228 | 1238 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1229 | 1239 | argument it works as a toggle. |
|
1230 | 1240 | |
|
1231 | 1241 | When an exception is triggered, IPython can optionally call the |
|
1232 | 1242 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1233 | 1243 | this feature on and off. |
|
1234 | 1244 | |
|
1235 | 1245 | The initial state of this feature is set in your ipythonrc |
|
1236 | 1246 | configuration file (the variable is called 'pdb'). |
|
1237 | 1247 | |
|
1238 | 1248 | If you want to just activate the debugger AFTER an exception has fired, |
|
1239 | 1249 | without having to type '%pdb on' and rerunning your code, you can use |
|
1240 | 1250 | the %debug magic.""" |
|
1241 | 1251 | |
|
1242 | 1252 | par = parameter_s.strip().lower() |
|
1243 | 1253 | |
|
1244 | 1254 | if par: |
|
1245 | 1255 | try: |
|
1246 | 1256 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1247 | 1257 | except KeyError: |
|
1248 | 1258 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1249 | 1259 | 'or nothing for a toggle.') |
|
1250 | 1260 | return |
|
1251 | 1261 | else: |
|
1252 | 1262 | # toggle |
|
1253 | 1263 | new_pdb = not self.shell.call_pdb |
|
1254 | 1264 | |
|
1255 | 1265 | # set on the shell |
|
1256 | 1266 | self.shell.call_pdb = new_pdb |
|
1257 | 1267 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1258 | 1268 | |
|
1259 | 1269 | def magic_debug(self, parameter_s=''): |
|
1260 | 1270 | """Activate the interactive debugger in post-mortem mode. |
|
1261 | 1271 | |
|
1262 | 1272 | If an exception has just occurred, this lets you inspect its stack |
|
1263 | 1273 | frames interactively. Note that this will always work only on the last |
|
1264 | 1274 | traceback that occurred, so you must call this quickly after an |
|
1265 | 1275 | exception that you wish to inspect has fired, because if another one |
|
1266 | 1276 | occurs, it clobbers the previous one. |
|
1267 | 1277 | |
|
1268 | 1278 | If you want IPython to automatically do this on every exception, see |
|
1269 | 1279 | the %pdb magic for more details. |
|
1270 | 1280 | """ |
|
1271 | ||
|
1272 | 1281 | self.shell.debugger(force=True) |
|
1273 | 1282 | |
|
1274 | 1283 | @testdec.skip_doctest |
|
1275 | 1284 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1276 | 1285 | opts=None,arg_lst=None,prog_ns=None): |
|
1277 | 1286 | |
|
1278 | 1287 | """Run a statement through the python code profiler. |
|
1279 | 1288 | |
|
1280 | 1289 | Usage: |
|
1281 | 1290 | %prun [options] statement |
|
1282 | 1291 | |
|
1283 | 1292 | The given statement (which doesn't require quote marks) is run via the |
|
1284 | 1293 | python profiler in a manner similar to the profile.run() function. |
|
1285 | 1294 | Namespaces are internally managed to work correctly; profile.run |
|
1286 | 1295 | cannot be used in IPython because it makes certain assumptions about |
|
1287 | 1296 | namespaces which do not hold under IPython. |
|
1288 | 1297 | |
|
1289 | 1298 | Options: |
|
1290 | 1299 | |
|
1291 | 1300 | -l <limit>: you can place restrictions on what or how much of the |
|
1292 | 1301 | profile gets printed. The limit value can be: |
|
1293 | 1302 | |
|
1294 | 1303 | * A string: only information for function names containing this string |
|
1295 | 1304 | is printed. |
|
1296 | 1305 | |
|
1297 | 1306 | * An integer: only these many lines are printed. |
|
1298 | 1307 | |
|
1299 | 1308 | * A float (between 0 and 1): this fraction of the report is printed |
|
1300 | 1309 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1301 | 1310 | |
|
1302 | 1311 | You can combine several limits with repeated use of the option. For |
|
1303 | 1312 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1304 | 1313 | information about class constructors. |
|
1305 | 1314 | |
|
1306 | 1315 | -r: return the pstats.Stats object generated by the profiling. This |
|
1307 | 1316 | object has all the information about the profile in it, and you can |
|
1308 | 1317 | later use it for further analysis or in other functions. |
|
1309 | 1318 | |
|
1310 | 1319 | -s <key>: sort profile by given key. You can provide more than one key |
|
1311 | 1320 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1312 | 1321 | default sorting key is 'time'. |
|
1313 | 1322 | |
|
1314 | 1323 | The following is copied verbatim from the profile documentation |
|
1315 | 1324 | referenced below: |
|
1316 | 1325 | |
|
1317 | 1326 | When more than one key is provided, additional keys are used as |
|
1318 | 1327 | secondary criteria when the there is equality in all keys selected |
|
1319 | 1328 | before them. |
|
1320 | 1329 | |
|
1321 | 1330 | Abbreviations can be used for any key names, as long as the |
|
1322 | 1331 | abbreviation is unambiguous. The following are the keys currently |
|
1323 | 1332 | defined: |
|
1324 | 1333 | |
|
1325 | 1334 | Valid Arg Meaning |
|
1326 | 1335 | "calls" call count |
|
1327 | 1336 | "cumulative" cumulative time |
|
1328 | 1337 | "file" file name |
|
1329 | 1338 | "module" file name |
|
1330 | 1339 | "pcalls" primitive call count |
|
1331 | 1340 | "line" line number |
|
1332 | 1341 | "name" function name |
|
1333 | 1342 | "nfl" name/file/line |
|
1334 | 1343 | "stdname" standard name |
|
1335 | 1344 | "time" internal time |
|
1336 | 1345 | |
|
1337 | 1346 | Note that all sorts on statistics are in descending order (placing |
|
1338 | 1347 | most time consuming items first), where as name, file, and line number |
|
1339 | 1348 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1340 | 1349 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1341 | 1350 | sort of the name as printed, which means that the embedded line |
|
1342 | 1351 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1343 | 1352 | would (if the file names were the same) appear in the string order |
|
1344 | 1353 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1345 | 1354 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1346 | 1355 | sort_stats("name", "file", "line"). |
|
1347 | 1356 | |
|
1348 | 1357 | -T <filename>: save profile results as shown on screen to a text |
|
1349 | 1358 | file. The profile is still shown on screen. |
|
1350 | 1359 | |
|
1351 | 1360 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1352 | 1361 | filename. This data is in a format understod by the pstats module, and |
|
1353 | 1362 | is generated by a call to the dump_stats() method of profile |
|
1354 | 1363 | objects. The profile is still shown on screen. |
|
1355 | 1364 | |
|
1356 | 1365 | If you want to run complete programs under the profiler's control, use |
|
1357 | 1366 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1358 | 1367 | contains profiler specific options as described here. |
|
1359 | 1368 | |
|
1360 | 1369 | You can read the complete documentation for the profile module with:: |
|
1361 | 1370 | |
|
1362 | 1371 | In [1]: import profile; profile.help() |
|
1363 | 1372 | """ |
|
1364 | 1373 | |
|
1365 | 1374 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1366 | 1375 | # protect user quote marks |
|
1367 | 1376 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1368 | 1377 | |
|
1369 | 1378 | if user_mode: # regular user call |
|
1370 | 1379 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1371 | 1380 | list_all=1) |
|
1372 | 1381 | namespace = self.shell.user_ns |
|
1373 | 1382 | else: # called to run a program by %run -p |
|
1374 | 1383 | try: |
|
1375 | 1384 | filename = get_py_filename(arg_lst[0]) |
|
1376 | 1385 | except IOError,msg: |
|
1377 | 1386 | error(msg) |
|
1378 | 1387 | return |
|
1379 | 1388 | |
|
1380 | 1389 | arg_str = 'execfile(filename,prog_ns)' |
|
1381 | 1390 | namespace = locals() |
|
1382 | 1391 | |
|
1383 | 1392 | opts.merge(opts_def) |
|
1384 | 1393 | |
|
1385 | 1394 | prof = profile.Profile() |
|
1386 | 1395 | try: |
|
1387 | 1396 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1388 | 1397 | sys_exit = '' |
|
1389 | 1398 | except SystemExit: |
|
1390 | 1399 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1391 | 1400 | |
|
1392 | 1401 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1393 | 1402 | |
|
1394 | 1403 | lims = opts.l |
|
1395 | 1404 | if lims: |
|
1396 | 1405 | lims = [] # rebuild lims with ints/floats/strings |
|
1397 | 1406 | for lim in opts.l: |
|
1398 | 1407 | try: |
|
1399 | 1408 | lims.append(int(lim)) |
|
1400 | 1409 | except ValueError: |
|
1401 | 1410 | try: |
|
1402 | 1411 | lims.append(float(lim)) |
|
1403 | 1412 | except ValueError: |
|
1404 | 1413 | lims.append(lim) |
|
1405 | 1414 | |
|
1406 | 1415 | # Trap output. |
|
1407 | 1416 | stdout_trap = StringIO() |
|
1408 | 1417 | |
|
1409 | 1418 | if hasattr(stats,'stream'): |
|
1410 | 1419 | # In newer versions of python, the stats object has a 'stream' |
|
1411 | 1420 | # attribute to write into. |
|
1412 | 1421 | stats.stream = stdout_trap |
|
1413 | 1422 | stats.print_stats(*lims) |
|
1414 | 1423 | else: |
|
1415 | 1424 | # For older versions, we manually redirect stdout during printing |
|
1416 | 1425 | sys_stdout = sys.stdout |
|
1417 | 1426 | try: |
|
1418 | 1427 | sys.stdout = stdout_trap |
|
1419 | 1428 | stats.print_stats(*lims) |
|
1420 | 1429 | finally: |
|
1421 | 1430 | sys.stdout = sys_stdout |
|
1422 | 1431 | |
|
1423 | 1432 | output = stdout_trap.getvalue() |
|
1424 | 1433 | output = output.rstrip() |
|
1425 | 1434 | |
|
1426 | 1435 | page(output,screen_lines=self.shell.usable_screen_length) |
|
1427 | 1436 | print sys_exit, |
|
1428 | 1437 | |
|
1429 | 1438 | dump_file = opts.D[0] |
|
1430 | 1439 | text_file = opts.T[0] |
|
1431 | 1440 | if dump_file: |
|
1432 | 1441 | prof.dump_stats(dump_file) |
|
1433 | 1442 | print '\n*** Profile stats marshalled to file',\ |
|
1434 | 1443 | `dump_file`+'.',sys_exit |
|
1435 | 1444 | if text_file: |
|
1436 | 1445 | pfile = file(text_file,'w') |
|
1437 | 1446 | pfile.write(output) |
|
1438 | 1447 | pfile.close() |
|
1439 | 1448 | print '\n*** Profile printout saved to text file',\ |
|
1440 | 1449 | `text_file`+'.',sys_exit |
|
1441 | 1450 | |
|
1442 | 1451 | if opts.has_key('r'): |
|
1443 | 1452 | return stats |
|
1444 | 1453 | else: |
|
1445 | 1454 | return None |
|
1446 | 1455 | |
|
1447 | 1456 | @testdec.skip_doctest |
|
1448 | 1457 | def magic_run(self, parameter_s ='',runner=None, |
|
1449 | 1458 | file_finder=get_py_filename): |
|
1450 | 1459 | """Run the named file inside IPython as a program. |
|
1451 | 1460 | |
|
1452 | 1461 | Usage:\\ |
|
1453 | 1462 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1454 | 1463 | |
|
1455 | 1464 | Parameters after the filename are passed as command-line arguments to |
|
1456 | 1465 | the program (put in sys.argv). Then, control returns to IPython's |
|
1457 | 1466 | prompt. |
|
1458 | 1467 | |
|
1459 | 1468 | This is similar to running at a system prompt:\\ |
|
1460 | 1469 | $ python file args\\ |
|
1461 | 1470 | but with the advantage of giving you IPython's tracebacks, and of |
|
1462 | 1471 | loading all variables into your interactive namespace for further use |
|
1463 | 1472 | (unless -p is used, see below). |
|
1464 | 1473 | |
|
1465 | 1474 | The file is executed in a namespace initially consisting only of |
|
1466 | 1475 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1467 | 1476 | sees its environment as if it were being run as a stand-alone program |
|
1468 | 1477 | (except for sharing global objects such as previously imported |
|
1469 | 1478 | modules). But after execution, the IPython interactive namespace gets |
|
1470 | 1479 | updated with all variables defined in the program (except for __name__ |
|
1471 | 1480 | and sys.argv). This allows for very convenient loading of code for |
|
1472 | 1481 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1473 | 1482 | |
|
1474 | 1483 | Options: |
|
1475 | 1484 | |
|
1476 | 1485 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1477 | 1486 | without extension (as python does under import). This allows running |
|
1478 | 1487 | scripts and reloading the definitions in them without calling code |
|
1479 | 1488 | protected by an ' if __name__ == "__main__" ' clause. |
|
1480 | 1489 | |
|
1481 | 1490 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1482 | 1491 | is useful if you are experimenting with code written in a text editor |
|
1483 | 1492 | which depends on variables defined interactively. |
|
1484 | 1493 | |
|
1485 | 1494 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1486 | 1495 | being run. This is particularly useful if IPython is being used to |
|
1487 | 1496 | run unittests, which always exit with a sys.exit() call. In such |
|
1488 | 1497 | cases you are interested in the output of the test results, not in |
|
1489 | 1498 | seeing a traceback of the unittest module. |
|
1490 | 1499 | |
|
1491 | 1500 | -t: print timing information at the end of the run. IPython will give |
|
1492 | 1501 | you an estimated CPU time consumption for your script, which under |
|
1493 | 1502 | Unix uses the resource module to avoid the wraparound problems of |
|
1494 | 1503 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1495 | 1504 | is also given (for Windows platforms this is reported as 0.0). |
|
1496 | 1505 | |
|
1497 | 1506 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1498 | 1507 | must be an integer indicating how many times you want the script to |
|
1499 | 1508 | run. The final timing report will include total and per run results. |
|
1500 | 1509 | |
|
1501 | 1510 | For example (testing the script uniq_stable.py): |
|
1502 | 1511 | |
|
1503 | 1512 | In [1]: run -t uniq_stable |
|
1504 | 1513 | |
|
1505 | 1514 | IPython CPU timings (estimated):\\ |
|
1506 | 1515 | User : 0.19597 s.\\ |
|
1507 | 1516 | System: 0.0 s.\\ |
|
1508 | 1517 | |
|
1509 | 1518 | In [2]: run -t -N5 uniq_stable |
|
1510 | 1519 | |
|
1511 | 1520 | IPython CPU timings (estimated):\\ |
|
1512 | 1521 | Total runs performed: 5\\ |
|
1513 | 1522 | Times : Total Per run\\ |
|
1514 | 1523 | User : 0.910862 s, 0.1821724 s.\\ |
|
1515 | 1524 | System: 0.0 s, 0.0 s. |
|
1516 | 1525 | |
|
1517 | 1526 | -d: run your program under the control of pdb, the Python debugger. |
|
1518 | 1527 | This allows you to execute your program step by step, watch variables, |
|
1519 | 1528 | etc. Internally, what IPython does is similar to calling: |
|
1520 | 1529 | |
|
1521 | 1530 | pdb.run('execfile("YOURFILENAME")') |
|
1522 | 1531 | |
|
1523 | 1532 | with a breakpoint set on line 1 of your file. You can change the line |
|
1524 | 1533 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1525 | 1534 | (where N must be an integer). For example: |
|
1526 | 1535 | |
|
1527 | 1536 | %run -d -b40 myscript |
|
1528 | 1537 | |
|
1529 | 1538 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1530 | 1539 | the first breakpoint must be set on a line which actually does |
|
1531 | 1540 | something (not a comment or docstring) for it to stop execution. |
|
1532 | 1541 | |
|
1533 | 1542 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1534 | 1543 | first enter 'c' (without qoutes) to start execution up to the first |
|
1535 | 1544 | breakpoint. |
|
1536 | 1545 | |
|
1537 | 1546 | Entering 'help' gives information about the use of the debugger. You |
|
1538 | 1547 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1539 | 1548 | at a prompt. |
|
1540 | 1549 | |
|
1541 | 1550 | -p: run program under the control of the Python profiler module (which |
|
1542 | 1551 | prints a detailed report of execution times, function calls, etc). |
|
1543 | 1552 | |
|
1544 | 1553 | You can pass other options after -p which affect the behavior of the |
|
1545 | 1554 | profiler itself. See the docs for %prun for details. |
|
1546 | 1555 | |
|
1547 | 1556 | In this mode, the program's variables do NOT propagate back to the |
|
1548 | 1557 | IPython interactive namespace (because they remain in the namespace |
|
1549 | 1558 | where the profiler executes them). |
|
1550 | 1559 | |
|
1551 | 1560 | Internally this triggers a call to %prun, see its documentation for |
|
1552 | 1561 | details on the options available specifically for profiling. |
|
1553 | 1562 | |
|
1554 | 1563 | There is one special usage for which the text above doesn't apply: |
|
1555 | 1564 | if the filename ends with .ipy, the file is run as ipython script, |
|
1556 | 1565 | just as if the commands were written on IPython prompt. |
|
1557 | 1566 | """ |
|
1558 | 1567 | |
|
1559 | 1568 | # get arguments and set sys.argv for program to be run. |
|
1560 | 1569 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1561 | 1570 | mode='list',list_all=1) |
|
1562 | 1571 | |
|
1563 | 1572 | try: |
|
1564 | 1573 | filename = file_finder(arg_lst[0]) |
|
1565 | 1574 | except IndexError: |
|
1566 | 1575 | warn('you must provide at least a filename.') |
|
1567 | 1576 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1568 | 1577 | return |
|
1569 | 1578 | except IOError,msg: |
|
1570 | 1579 | error(msg) |
|
1571 | 1580 | return |
|
1572 | 1581 | |
|
1573 | 1582 | if filename.lower().endswith('.ipy'): |
|
1574 | self.safe_execfile_ipy(filename) | |
|
1583 | self.shell.safe_execfile_ipy(filename) | |
|
1575 | 1584 | return |
|
1576 | 1585 | |
|
1577 | 1586 | # Control the response to exit() calls made by the script being run |
|
1578 | 1587 | exit_ignore = opts.has_key('e') |
|
1579 | 1588 | |
|
1580 | 1589 | # Make sure that the running script gets a proper sys.argv as if it |
|
1581 | 1590 | # were run from a system shell. |
|
1582 | 1591 | save_argv = sys.argv # save it for later restoring |
|
1583 | 1592 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1584 | 1593 | |
|
1585 | 1594 | if opts.has_key('i'): |
|
1586 | 1595 | # Run in user's interactive namespace |
|
1587 | 1596 | prog_ns = self.shell.user_ns |
|
1588 | 1597 | __name__save = self.shell.user_ns['__name__'] |
|
1589 | 1598 | prog_ns['__name__'] = '__main__' |
|
1590 | 1599 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1591 | 1600 | else: |
|
1592 | 1601 | # Run in a fresh, empty namespace |
|
1593 | 1602 | if opts.has_key('n'): |
|
1594 | 1603 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1595 | 1604 | else: |
|
1596 | 1605 | name = '__main__' |
|
1597 | 1606 | |
|
1598 | 1607 | main_mod = self.shell.new_main_mod() |
|
1599 | 1608 | prog_ns = main_mod.__dict__ |
|
1600 | 1609 | prog_ns['__name__'] = name |
|
1601 | 1610 | |
|
1602 | 1611 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1603 | 1612 | # set the __file__ global in the script's namespace |
|
1604 | 1613 | prog_ns['__file__'] = filename |
|
1605 | 1614 | |
|
1606 | 1615 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1607 | 1616 | # that, if we overwrite __main__, we replace it at the end |
|
1608 | 1617 | main_mod_name = prog_ns['__name__'] |
|
1609 | 1618 | |
|
1610 | 1619 | if main_mod_name == '__main__': |
|
1611 | 1620 | restore_main = sys.modules['__main__'] |
|
1612 | 1621 | else: |
|
1613 | 1622 | restore_main = False |
|
1614 | 1623 | |
|
1615 | 1624 | # This needs to be undone at the end to prevent holding references to |
|
1616 | 1625 | # every single object ever created. |
|
1617 | 1626 | sys.modules[main_mod_name] = main_mod |
|
1618 | 1627 | |
|
1619 | 1628 | stats = None |
|
1620 | 1629 | try: |
|
1621 | 1630 | self.shell.savehist() |
|
1622 | 1631 | |
|
1623 | 1632 | if opts.has_key('p'): |
|
1624 | 1633 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1625 | 1634 | else: |
|
1626 | 1635 | if opts.has_key('d'): |
|
1627 | 1636 | deb = debugger.Pdb(self.shell.colors) |
|
1628 | 1637 | # reset Breakpoint state, which is moronically kept |
|
1629 | 1638 | # in a class |
|
1630 | 1639 | bdb.Breakpoint.next = 1 |
|
1631 | 1640 | bdb.Breakpoint.bplist = {} |
|
1632 | 1641 | bdb.Breakpoint.bpbynumber = [None] |
|
1633 | 1642 | # Set an initial breakpoint to stop execution |
|
1634 | 1643 | maxtries = 10 |
|
1635 | 1644 | bp = int(opts.get('b',[1])[0]) |
|
1636 | 1645 | checkline = deb.checkline(filename,bp) |
|
1637 | 1646 | if not checkline: |
|
1638 | 1647 | for bp in range(bp+1,bp+maxtries+1): |
|
1639 | 1648 | if deb.checkline(filename,bp): |
|
1640 | 1649 | break |
|
1641 | 1650 | else: |
|
1642 | 1651 | msg = ("\nI failed to find a valid line to set " |
|
1643 | 1652 | "a breakpoint\n" |
|
1644 | 1653 | "after trying up to line: %s.\n" |
|
1645 | 1654 | "Please set a valid breakpoint manually " |
|
1646 | 1655 | "with the -b option." % bp) |
|
1647 | 1656 | error(msg) |
|
1648 | 1657 | return |
|
1649 | 1658 | # if we find a good linenumber, set the breakpoint |
|
1650 | 1659 | deb.do_break('%s:%s' % (filename,bp)) |
|
1651 | 1660 | # Start file run |
|
1652 | 1661 | print "NOTE: Enter 'c' at the", |
|
1653 | 1662 | print "%s prompt to start your script." % deb.prompt |
|
1654 | 1663 | try: |
|
1655 | 1664 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1656 | 1665 | |
|
1657 | 1666 | except: |
|
1658 | 1667 | etype, value, tb = sys.exc_info() |
|
1659 | 1668 | # Skip three frames in the traceback: the %run one, |
|
1660 | 1669 | # one inside bdb.py, and the command-line typed by the |
|
1661 | 1670 | # user (run by exec in pdb itself). |
|
1662 | 1671 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1663 | 1672 | else: |
|
1664 | 1673 | if runner is None: |
|
1665 | 1674 | runner = self.shell.safe_execfile |
|
1666 | 1675 | if opts.has_key('t'): |
|
1667 | 1676 | # timed execution |
|
1668 | 1677 | try: |
|
1669 | 1678 | nruns = int(opts['N'][0]) |
|
1670 | 1679 | if nruns < 1: |
|
1671 | 1680 | error('Number of runs must be >=1') |
|
1672 | 1681 | return |
|
1673 | 1682 | except (KeyError): |
|
1674 | 1683 | nruns = 1 |
|
1675 | 1684 | if nruns == 1: |
|
1676 | 1685 | t0 = clock2() |
|
1677 | 1686 | runner(filename,prog_ns,prog_ns, |
|
1678 | 1687 | exit_ignore=exit_ignore) |
|
1679 | 1688 | t1 = clock2() |
|
1680 | 1689 | t_usr = t1[0]-t0[0] |
|
1681 | 1690 | t_sys = t1[1]-t0[1] |
|
1682 | 1691 | print "\nIPython CPU timings (estimated):" |
|
1683 | 1692 | print " User : %10s s." % t_usr |
|
1684 | 1693 | print " System: %10s s." % t_sys |
|
1685 | 1694 | else: |
|
1686 | 1695 | runs = range(nruns) |
|
1687 | 1696 | t0 = clock2() |
|
1688 | 1697 | for nr in runs: |
|
1689 | 1698 | runner(filename,prog_ns,prog_ns, |
|
1690 | 1699 | exit_ignore=exit_ignore) |
|
1691 | 1700 | t1 = clock2() |
|
1692 | 1701 | t_usr = t1[0]-t0[0] |
|
1693 | 1702 | t_sys = t1[1]-t0[1] |
|
1694 | 1703 | print "\nIPython CPU timings (estimated):" |
|
1695 | 1704 | print "Total runs performed:",nruns |
|
1696 | 1705 | print " Times : %10s %10s" % ('Total','Per run') |
|
1697 | 1706 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1698 | 1707 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1699 | 1708 | |
|
1700 | 1709 | else: |
|
1701 | 1710 | # regular execution |
|
1702 | 1711 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1703 | 1712 | |
|
1704 | 1713 | if opts.has_key('i'): |
|
1705 | 1714 | self.shell.user_ns['__name__'] = __name__save |
|
1706 | 1715 | else: |
|
1707 | 1716 | # The shell MUST hold a reference to prog_ns so after %run |
|
1708 | 1717 | # exits, the python deletion mechanism doesn't zero it out |
|
1709 | 1718 | # (leaving dangling references). |
|
1710 | 1719 | self.shell.cache_main_mod(prog_ns,filename) |
|
1711 | 1720 | # update IPython interactive namespace |
|
1712 | 1721 | |
|
1713 | 1722 | # Some forms of read errors on the file may mean the |
|
1714 | 1723 | # __name__ key was never set; using pop we don't have to |
|
1715 | 1724 | # worry about a possible KeyError. |
|
1716 | 1725 | prog_ns.pop('__name__', None) |
|
1717 | 1726 | |
|
1718 | 1727 | self.shell.user_ns.update(prog_ns) |
|
1719 | 1728 | finally: |
|
1720 | 1729 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1721 | 1730 | # being a module to becoming a dict missing some key data after |
|
1722 | 1731 | # %run. As best I can see, this is NOT something IPython is doing |
|
1723 | 1732 | # at all, and similar problems have been reported before: |
|
1724 | 1733 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1725 | 1734 | # Since this seems to be done by the interpreter itself, the best |
|
1726 | 1735 | # we can do is to at least restore __builtins__ for the user on |
|
1727 | 1736 | # exit. |
|
1728 | 1737 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1729 | 1738 | |
|
1730 | 1739 | # Ensure key global structures are restored |
|
1731 | 1740 | sys.argv = save_argv |
|
1732 | 1741 | if restore_main: |
|
1733 | 1742 | sys.modules['__main__'] = restore_main |
|
1734 | 1743 | else: |
|
1735 | 1744 | # Remove from sys.modules the reference to main_mod we'd |
|
1736 | 1745 | # added. Otherwise it will trap references to objects |
|
1737 | 1746 | # contained therein. |
|
1738 | 1747 | del sys.modules[main_mod_name] |
|
1739 | 1748 | |
|
1740 | 1749 | self.shell.reloadhist() |
|
1741 | 1750 | |
|
1742 | 1751 | return stats |
|
1743 | 1752 | |
|
1744 | 1753 | @testdec.skip_doctest |
|
1745 | 1754 | def magic_timeit(self, parameter_s =''): |
|
1746 | 1755 | """Time execution of a Python statement or expression |
|
1747 | 1756 | |
|
1748 | 1757 | Usage:\\ |
|
1749 | 1758 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1750 | 1759 | |
|
1751 | 1760 | Time execution of a Python statement or expression using the timeit |
|
1752 | 1761 | module. |
|
1753 | 1762 | |
|
1754 | 1763 | Options: |
|
1755 | 1764 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1756 | 1765 | is not given, a fitting value is chosen. |
|
1757 | 1766 | |
|
1758 | 1767 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1759 | 1768 | Default: 3 |
|
1760 | 1769 | |
|
1761 | 1770 | -t: use time.time to measure the time, which is the default on Unix. |
|
1762 | 1771 | This function measures wall time. |
|
1763 | 1772 | |
|
1764 | 1773 | -c: use time.clock to measure the time, which is the default on |
|
1765 | 1774 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1766 | 1775 | instead and returns the CPU user time. |
|
1767 | 1776 | |
|
1768 | 1777 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1769 | 1778 | Default: 3 |
|
1770 | 1779 | |
|
1771 | 1780 | |
|
1772 | 1781 | Examples: |
|
1773 | 1782 | |
|
1774 | 1783 | In [1]: %timeit pass |
|
1775 | 1784 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1776 | 1785 | |
|
1777 | 1786 | In [2]: u = None |
|
1778 | 1787 | |
|
1779 | 1788 | In [3]: %timeit u is None |
|
1780 | 1789 | 10000000 loops, best of 3: 184 ns per loop |
|
1781 | 1790 | |
|
1782 | 1791 | In [4]: %timeit -r 4 u == None |
|
1783 | 1792 | 1000000 loops, best of 4: 242 ns per loop |
|
1784 | 1793 | |
|
1785 | 1794 | In [5]: import time |
|
1786 | 1795 | |
|
1787 | 1796 | In [6]: %timeit -n1 time.sleep(2) |
|
1788 | 1797 | 1 loops, best of 3: 2 s per loop |
|
1789 | 1798 | |
|
1790 | 1799 | |
|
1791 | 1800 | The times reported by %timeit will be slightly higher than those |
|
1792 | 1801 | reported by the timeit.py script when variables are accessed. This is |
|
1793 | 1802 | due to the fact that %timeit executes the statement in the namespace |
|
1794 | 1803 | of the shell, compared with timeit.py, which uses a single setup |
|
1795 | 1804 | statement to import function or create variables. Generally, the bias |
|
1796 | 1805 | does not matter as long as results from timeit.py are not mixed with |
|
1797 | 1806 | those from %timeit.""" |
|
1798 | 1807 | |
|
1799 | 1808 | import timeit |
|
1800 | 1809 | import math |
|
1801 | 1810 | |
|
1802 | 1811 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1803 | 1812 | # certain terminals. Until we figure out a robust way of |
|
1804 | 1813 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1805 | 1814 | # microseconds. I am really NOT happy about disabling the proper |
|
1806 | 1815 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1807 | 1816 | # right solution for this is, I'm all ears... |
|
1808 | 1817 | # |
|
1809 | 1818 | # Note: using |
|
1810 | 1819 | # |
|
1811 | 1820 | # s = u'\xb5' |
|
1812 | 1821 | # s.encode(sys.getdefaultencoding()) |
|
1813 | 1822 | # |
|
1814 | 1823 | # is not sufficient, as I've seen terminals where that fails but |
|
1815 | 1824 | # print s |
|
1816 | 1825 | # |
|
1817 | 1826 | # succeeds |
|
1818 | 1827 | # |
|
1819 | 1828 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1820 | 1829 | |
|
1821 | 1830 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1822 | 1831 | units = [u"s", u"ms",u'us',"ns"] |
|
1823 | 1832 | |
|
1824 | 1833 | scaling = [1, 1e3, 1e6, 1e9] |
|
1825 | 1834 | |
|
1826 | 1835 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1827 | 1836 | posix=False) |
|
1828 | 1837 | if stmt == "": |
|
1829 | 1838 | return |
|
1830 | 1839 | timefunc = timeit.default_timer |
|
1831 | 1840 | number = int(getattr(opts, "n", 0)) |
|
1832 | 1841 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1833 | 1842 | precision = int(getattr(opts, "p", 3)) |
|
1834 | 1843 | if hasattr(opts, "t"): |
|
1835 | 1844 | timefunc = time.time |
|
1836 | 1845 | if hasattr(opts, "c"): |
|
1837 | 1846 | timefunc = clock |
|
1838 | 1847 | |
|
1839 | 1848 | timer = timeit.Timer(timer=timefunc) |
|
1840 | 1849 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1841 | 1850 | # but is there a better way to achieve that the code stmt has access |
|
1842 | 1851 | # to the shell namespace? |
|
1843 | 1852 | |
|
1844 | 1853 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1845 | 1854 | 'setup': "pass"} |
|
1846 | 1855 | # Track compilation time so it can be reported if too long |
|
1847 | 1856 | # Minimum time above which compilation time will be reported |
|
1848 | 1857 | tc_min = 0.1 |
|
1849 | 1858 | |
|
1850 | 1859 | t0 = clock() |
|
1851 | 1860 | code = compile(src, "<magic-timeit>", "exec") |
|
1852 | 1861 | tc = clock()-t0 |
|
1853 | 1862 | |
|
1854 | 1863 | ns = {} |
|
1855 | 1864 | exec code in self.shell.user_ns, ns |
|
1856 | 1865 | timer.inner = ns["inner"] |
|
1857 | 1866 | |
|
1858 | 1867 | if number == 0: |
|
1859 | 1868 | # determine number so that 0.2 <= total time < 2.0 |
|
1860 | 1869 | number = 1 |
|
1861 | 1870 | for i in range(1, 10): |
|
1862 | 1871 | if timer.timeit(number) >= 0.2: |
|
1863 | 1872 | break |
|
1864 | 1873 | number *= 10 |
|
1865 | 1874 | |
|
1866 | 1875 | best = min(timer.repeat(repeat, number)) / number |
|
1867 | 1876 | |
|
1868 | 1877 | if best > 0.0: |
|
1869 | 1878 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1870 | 1879 | else: |
|
1871 | 1880 | order = 3 |
|
1872 | 1881 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1873 | 1882 | precision, |
|
1874 | 1883 | best * scaling[order], |
|
1875 | 1884 | units[order]) |
|
1876 | 1885 | if tc > tc_min: |
|
1877 | 1886 | print "Compiler time: %.2f s" % tc |
|
1878 | 1887 | |
|
1879 | 1888 | @testdec.skip_doctest |
|
1880 | 1889 | def magic_time(self,parameter_s = ''): |
|
1881 | 1890 | """Time execution of a Python statement or expression. |
|
1882 | 1891 | |
|
1883 | 1892 | The CPU and wall clock times are printed, and the value of the |
|
1884 | 1893 | expression (if any) is returned. Note that under Win32, system time |
|
1885 | 1894 | is always reported as 0, since it can not be measured. |
|
1886 | 1895 | |
|
1887 | 1896 | This function provides very basic timing functionality. In Python |
|
1888 | 1897 | 2.3, the timeit module offers more control and sophistication, so this |
|
1889 | 1898 | could be rewritten to use it (patches welcome). |
|
1890 | 1899 | |
|
1891 | 1900 | Some examples: |
|
1892 | 1901 | |
|
1893 | 1902 | In [1]: time 2**128 |
|
1894 | 1903 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1895 | 1904 | Wall time: 0.00 |
|
1896 | 1905 | Out[1]: 340282366920938463463374607431768211456L |
|
1897 | 1906 | |
|
1898 | 1907 | In [2]: n = 1000000 |
|
1899 | 1908 | |
|
1900 | 1909 | In [3]: time sum(range(n)) |
|
1901 | 1910 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1902 | 1911 | Wall time: 1.37 |
|
1903 | 1912 | Out[3]: 499999500000L |
|
1904 | 1913 | |
|
1905 | 1914 | In [4]: time print 'hello world' |
|
1906 | 1915 | hello world |
|
1907 | 1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1908 | 1917 | Wall time: 0.00 |
|
1909 | 1918 | |
|
1910 | 1919 | Note that the time needed by Python to compile the given expression |
|
1911 | 1920 | will be reported if it is more than 0.1s. In this example, the |
|
1912 | 1921 | actual exponentiation is done by Python at compilation time, so while |
|
1913 | 1922 | the expression can take a noticeable amount of time to compute, that |
|
1914 | 1923 | time is purely due to the compilation: |
|
1915 | 1924 | |
|
1916 | 1925 | In [5]: time 3**9999; |
|
1917 | 1926 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1918 | 1927 | Wall time: 0.00 s |
|
1919 | 1928 | |
|
1920 | 1929 | In [6]: time 3**999999; |
|
1921 | 1930 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1922 | 1931 | Wall time: 0.00 s |
|
1923 | 1932 | Compiler : 0.78 s |
|
1924 | 1933 | """ |
|
1925 | 1934 | |
|
1926 | 1935 | # fail immediately if the given expression can't be compiled |
|
1927 | 1936 | |
|
1928 | 1937 | expr = self.shell.prefilter(parameter_s,False) |
|
1929 | 1938 | |
|
1930 | 1939 | # Minimum time above which compilation time will be reported |
|
1931 | 1940 | tc_min = 0.1 |
|
1932 | 1941 | |
|
1933 | 1942 | try: |
|
1934 | 1943 | mode = 'eval' |
|
1935 | 1944 | t0 = clock() |
|
1936 | 1945 | code = compile(expr,'<timed eval>',mode) |
|
1937 | 1946 | tc = clock()-t0 |
|
1938 | 1947 | except SyntaxError: |
|
1939 | 1948 | mode = 'exec' |
|
1940 | 1949 | t0 = clock() |
|
1941 | 1950 | code = compile(expr,'<timed exec>',mode) |
|
1942 | 1951 | tc = clock()-t0 |
|
1943 | 1952 | # skew measurement as little as possible |
|
1944 | 1953 | glob = self.shell.user_ns |
|
1945 | 1954 | clk = clock2 |
|
1946 | 1955 | wtime = time.time |
|
1947 | 1956 | # time execution |
|
1948 | 1957 | wall_st = wtime() |
|
1949 | 1958 | if mode=='eval': |
|
1950 | 1959 | st = clk() |
|
1951 | 1960 | out = eval(code,glob) |
|
1952 | 1961 | end = clk() |
|
1953 | 1962 | else: |
|
1954 | 1963 | st = clk() |
|
1955 | 1964 | exec code in glob |
|
1956 | 1965 | end = clk() |
|
1957 | 1966 | out = None |
|
1958 | 1967 | wall_end = wtime() |
|
1959 | 1968 | # Compute actual times and report |
|
1960 | 1969 | wall_time = wall_end-wall_st |
|
1961 | 1970 | cpu_user = end[0]-st[0] |
|
1962 | 1971 | cpu_sys = end[1]-st[1] |
|
1963 | 1972 | cpu_tot = cpu_user+cpu_sys |
|
1964 | 1973 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1965 | 1974 | (cpu_user,cpu_sys,cpu_tot) |
|
1966 | 1975 | print "Wall time: %.2f s" % wall_time |
|
1967 | 1976 | if tc > tc_min: |
|
1968 | 1977 | print "Compiler : %.2f s" % tc |
|
1969 | 1978 | return out |
|
1970 | 1979 | |
|
1971 | 1980 | @testdec.skip_doctest |
|
1972 | 1981 | def magic_macro(self,parameter_s = ''): |
|
1973 | 1982 | """Define a set of input lines as a macro for future re-execution. |
|
1974 | 1983 | |
|
1975 | 1984 | Usage:\\ |
|
1976 | 1985 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1977 | 1986 | |
|
1978 | 1987 | Options: |
|
1979 | 1988 | |
|
1980 | 1989 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1981 | 1990 | so that magics are loaded in their transformed version to valid |
|
1982 | 1991 | Python. If this option is given, the raw input as typed as the |
|
1983 | 1992 | command line is used instead. |
|
1984 | 1993 | |
|
1985 | 1994 | This will define a global variable called `name` which is a string |
|
1986 | 1995 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1987 | 1996 | above) from your input history into a single string. This variable |
|
1988 | 1997 | acts like an automatic function which re-executes those lines as if |
|
1989 | 1998 | you had typed them. You just type 'name' at the prompt and the code |
|
1990 | 1999 | executes. |
|
1991 | 2000 | |
|
1992 | 2001 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1993 | 2002 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1994 | 2003 | using the lines numbered 5,6 and 7. |
|
1995 | 2004 | |
|
1996 | 2005 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1997 | 2006 | notation, where N:M means numbers N through M-1. |
|
1998 | 2007 | |
|
1999 | 2008 | For example, if your history contains (%hist prints it): |
|
2000 | 2009 | |
|
2001 | 2010 | 44: x=1 |
|
2002 | 2011 | 45: y=3 |
|
2003 | 2012 | 46: z=x+y |
|
2004 | 2013 | 47: print x |
|
2005 | 2014 | 48: a=5 |
|
2006 | 2015 | 49: print 'x',x,'y',y |
|
2007 | 2016 | |
|
2008 | 2017 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2009 | 2018 | called my_macro with: |
|
2010 | 2019 | |
|
2011 | 2020 | In [55]: %macro my_macro 44-47 49 |
|
2012 | 2021 | |
|
2013 | 2022 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2014 | 2023 | in one pass. |
|
2015 | 2024 | |
|
2016 | 2025 | You don't need to give the line-numbers in order, and any given line |
|
2017 | 2026 | number can appear multiple times. You can assemble macros with any |
|
2018 | 2027 | lines from your input history in any order. |
|
2019 | 2028 | |
|
2020 | 2029 | The macro is a simple object which holds its value in an attribute, |
|
2021 | 2030 | but IPython's display system checks for macros and executes them as |
|
2022 | 2031 | code instead of printing them when you type their name. |
|
2023 | 2032 | |
|
2024 | 2033 | You can view a macro's contents by explicitly printing it with: |
|
2025 | 2034 | |
|
2026 | 2035 | 'print macro_name'. |
|
2027 | 2036 | |
|
2028 | 2037 | For one-off cases which DON'T contain magic function calls in them you |
|
2029 | 2038 | can obtain similar results by explicitly executing slices from your |
|
2030 | 2039 | input history with: |
|
2031 | 2040 | |
|
2032 | 2041 | In [60]: exec In[44:48]+In[49]""" |
|
2033 | 2042 | |
|
2034 | 2043 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2035 | 2044 | if not args: |
|
2036 | 2045 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2037 | 2046 | macs.sort() |
|
2038 | 2047 | return macs |
|
2039 | 2048 | if len(args) == 1: |
|
2040 | 2049 | raise UsageError( |
|
2041 | 2050 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2042 | 2051 | name,ranges = args[0], args[1:] |
|
2043 | 2052 | |
|
2044 | 2053 | #print 'rng',ranges # dbg |
|
2045 | 2054 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2046 | 2055 | macro = Macro(lines) |
|
2047 | 2056 | self.shell.define_macro(name, macro) |
|
2048 | 2057 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2049 | 2058 | print 'Macro contents:' |
|
2050 | 2059 | print macro, |
|
2051 | 2060 | |
|
2052 | 2061 | def magic_save(self,parameter_s = ''): |
|
2053 | 2062 | """Save a set of lines to a given filename. |
|
2054 | 2063 | |
|
2055 | 2064 | Usage:\\ |
|
2056 | 2065 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2057 | 2066 | |
|
2058 | 2067 | Options: |
|
2059 | 2068 | |
|
2060 | 2069 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2061 | 2070 | so that magics are loaded in their transformed version to valid |
|
2062 | 2071 | Python. If this option is given, the raw input as typed as the |
|
2063 | 2072 | command line is used instead. |
|
2064 | 2073 | |
|
2065 | 2074 | This function uses the same syntax as %macro for line extraction, but |
|
2066 | 2075 | instead of creating a macro it saves the resulting string to the |
|
2067 | 2076 | filename you specify. |
|
2068 | 2077 | |
|
2069 | 2078 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2070 | 2079 | it asks for confirmation before overwriting existing files.""" |
|
2071 | 2080 | |
|
2072 | 2081 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2073 | 2082 | fname,ranges = args[0], args[1:] |
|
2074 | 2083 | if not fname.endswith('.py'): |
|
2075 | 2084 | fname += '.py' |
|
2076 | 2085 | if os.path.isfile(fname): |
|
2077 | 2086 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2078 | 2087 | if ans.lower() not in ['y','yes']: |
|
2079 | 2088 | print 'Operation cancelled.' |
|
2080 | 2089 | return |
|
2081 | 2090 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2082 | 2091 | f = file(fname,'w') |
|
2083 | 2092 | f.write(cmds) |
|
2084 | 2093 | f.close() |
|
2085 | 2094 | print 'The following commands were written to file `%s`:' % fname |
|
2086 | 2095 | print cmds |
|
2087 | 2096 | |
|
2088 | 2097 | def _edit_macro(self,mname,macro): |
|
2089 | 2098 | """open an editor with the macro data in a file""" |
|
2090 | 2099 | filename = self.shell.mktempfile(macro.value) |
|
2091 | 2100 | self.shell.hooks.editor(filename) |
|
2092 | 2101 | |
|
2093 | 2102 | # and make a new macro object, to replace the old one |
|
2094 | 2103 | mfile = open(filename) |
|
2095 | 2104 | mvalue = mfile.read() |
|
2096 | 2105 | mfile.close() |
|
2097 | 2106 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2098 | 2107 | |
|
2099 | 2108 | def magic_ed(self,parameter_s=''): |
|
2100 | 2109 | """Alias to %edit.""" |
|
2101 | 2110 | return self.magic_edit(parameter_s) |
|
2102 | 2111 | |
|
2103 | 2112 | @testdec.skip_doctest |
|
2104 | 2113 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2105 | 2114 | """Bring up an editor and execute the resulting code. |
|
2106 | 2115 | |
|
2107 | 2116 | Usage: |
|
2108 | 2117 | %edit [options] [args] |
|
2109 | 2118 | |
|
2110 | 2119 | %edit runs IPython's editor hook. The default version of this hook is |
|
2111 | 2120 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2112 | 2121 | environment variable $EDITOR. If this isn't found, it will default to |
|
2113 | 2122 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2114 | 2123 | docstring for how to change the editor hook. |
|
2115 | 2124 | |
|
2116 | 2125 | You can also set the value of this editor via the command line option |
|
2117 | 2126 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2118 | 2127 | specifically for IPython an editor different from your typical default |
|
2119 | 2128 | (and for Windows users who typically don't set environment variables). |
|
2120 | 2129 | |
|
2121 | 2130 | This command allows you to conveniently edit multi-line code right in |
|
2122 | 2131 | your IPython session. |
|
2123 | 2132 | |
|
2124 | 2133 | If called without arguments, %edit opens up an empty editor with a |
|
2125 | 2134 | temporary file and will execute the contents of this file when you |
|
2126 | 2135 | close it (don't forget to save it!). |
|
2127 | 2136 | |
|
2128 | 2137 | |
|
2129 | 2138 | Options: |
|
2130 | 2139 | |
|
2131 | 2140 | -n <number>: open the editor at a specified line number. By default, |
|
2132 | 2141 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2133 | 2142 | you can configure this by providing your own modified hook if your |
|
2134 | 2143 | favorite editor supports line-number specifications with a different |
|
2135 | 2144 | syntax. |
|
2136 | 2145 | |
|
2137 | 2146 | -p: this will call the editor with the same data as the previous time |
|
2138 | 2147 | it was used, regardless of how long ago (in your current session) it |
|
2139 | 2148 | was. |
|
2140 | 2149 | |
|
2141 | 2150 | -r: use 'raw' input. This option only applies to input taken from the |
|
2142 | 2151 | user's history. By default, the 'processed' history is used, so that |
|
2143 | 2152 | magics are loaded in their transformed version to valid Python. If |
|
2144 | 2153 | this option is given, the raw input as typed as the command line is |
|
2145 | 2154 | used instead. When you exit the editor, it will be executed by |
|
2146 | 2155 | IPython's own processor. |
|
2147 | 2156 | |
|
2148 | 2157 | -x: do not execute the edited code immediately upon exit. This is |
|
2149 | 2158 | mainly useful if you are editing programs which need to be called with |
|
2150 | 2159 | command line arguments, which you can then do using %run. |
|
2151 | 2160 | |
|
2152 | 2161 | |
|
2153 | 2162 | Arguments: |
|
2154 | 2163 | |
|
2155 | 2164 | If arguments are given, the following possibilites exist: |
|
2156 | 2165 | |
|
2157 | 2166 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2158 | 2167 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2159 | 2168 | loaded into the editor. The syntax is the same of the %macro command. |
|
2160 | 2169 | |
|
2161 | 2170 | - If the argument doesn't start with a number, it is evaluated as a |
|
2162 | 2171 | variable and its contents loaded into the editor. You can thus edit |
|
2163 | 2172 | any string which contains python code (including the result of |
|
2164 | 2173 | previous edits). |
|
2165 | 2174 | |
|
2166 | 2175 | - If the argument is the name of an object (other than a string), |
|
2167 | 2176 | IPython will try to locate the file where it was defined and open the |
|
2168 | 2177 | editor at the point where it is defined. You can use `%edit function` |
|
2169 | 2178 | to load an editor exactly at the point where 'function' is defined, |
|
2170 | 2179 | edit it and have the file be executed automatically. |
|
2171 | 2180 | |
|
2172 | 2181 | If the object is a macro (see %macro for details), this opens up your |
|
2173 | 2182 | specified editor with a temporary file containing the macro's data. |
|
2174 | 2183 | Upon exit, the macro is reloaded with the contents of the file. |
|
2175 | 2184 | |
|
2176 | 2185 | Note: opening at an exact line is only supported under Unix, and some |
|
2177 | 2186 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2178 | 2187 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2179 | 2188 | (X)Emacs, vi, jed, pico and joe all do. |
|
2180 | 2189 | |
|
2181 | 2190 | - If the argument is not found as a variable, IPython will look for a |
|
2182 | 2191 | file with that name (adding .py if necessary) and load it into the |
|
2183 | 2192 | editor. It will execute its contents with execfile() when you exit, |
|
2184 | 2193 | loading any code in the file into your interactive namespace. |
|
2185 | 2194 | |
|
2186 | 2195 | After executing your code, %edit will return as output the code you |
|
2187 | 2196 | typed in the editor (except when it was an existing file). This way |
|
2188 | 2197 | you can reload the code in further invocations of %edit as a variable, |
|
2189 | 2198 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2190 | 2199 | the output. |
|
2191 | 2200 | |
|
2192 | 2201 | Note that %edit is also available through the alias %ed. |
|
2193 | 2202 | |
|
2194 | 2203 | This is an example of creating a simple function inside the editor and |
|
2195 | 2204 | then modifying it. First, start up the editor: |
|
2196 | 2205 | |
|
2197 | 2206 | In [1]: ed |
|
2198 | 2207 | Editing... done. Executing edited code... |
|
2199 | 2208 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2200 | 2209 | |
|
2201 | 2210 | We can then call the function foo(): |
|
2202 | 2211 | |
|
2203 | 2212 | In [2]: foo() |
|
2204 | 2213 | foo() was defined in an editing session |
|
2205 | 2214 | |
|
2206 | 2215 | Now we edit foo. IPython automatically loads the editor with the |
|
2207 | 2216 | (temporary) file where foo() was previously defined: |
|
2208 | 2217 | |
|
2209 | 2218 | In [3]: ed foo |
|
2210 | 2219 | Editing... done. Executing edited code... |
|
2211 | 2220 | |
|
2212 | 2221 | And if we call foo() again we get the modified version: |
|
2213 | 2222 | |
|
2214 | 2223 | In [4]: foo() |
|
2215 | 2224 | foo() has now been changed! |
|
2216 | 2225 | |
|
2217 | 2226 | Here is an example of how to edit a code snippet successive |
|
2218 | 2227 | times. First we call the editor: |
|
2219 | 2228 | |
|
2220 | 2229 | In [5]: ed |
|
2221 | 2230 | Editing... done. Executing edited code... |
|
2222 | 2231 | hello |
|
2223 | 2232 | Out[5]: "print 'hello'n" |
|
2224 | 2233 | |
|
2225 | 2234 | Now we call it again with the previous output (stored in _): |
|
2226 | 2235 | |
|
2227 | 2236 | In [6]: ed _ |
|
2228 | 2237 | Editing... done. Executing edited code... |
|
2229 | 2238 | hello world |
|
2230 | 2239 | Out[6]: "print 'hello world'n" |
|
2231 | 2240 | |
|
2232 | 2241 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2233 | 2242 | |
|
2234 | 2243 | In [7]: ed _8 |
|
2235 | 2244 | Editing... done. Executing edited code... |
|
2236 | 2245 | hello again |
|
2237 | 2246 | Out[7]: "print 'hello again'n" |
|
2238 | 2247 | |
|
2239 | 2248 | |
|
2240 | 2249 | Changing the default editor hook: |
|
2241 | 2250 | |
|
2242 | 2251 | If you wish to write your own editor hook, you can put it in a |
|
2243 | 2252 | configuration file which you load at startup time. The default hook |
|
2244 | 2253 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2245 | 2254 | starting example for further modifications. That file also has |
|
2246 | 2255 | general instructions on how to set a new hook for use once you've |
|
2247 | 2256 | defined it.""" |
|
2248 | 2257 | |
|
2249 | 2258 | # FIXME: This function has become a convoluted mess. It needs a |
|
2250 | 2259 | # ground-up rewrite with clean, simple logic. |
|
2251 | 2260 | |
|
2252 | 2261 | def make_filename(arg): |
|
2253 | 2262 | "Make a filename from the given args" |
|
2254 | 2263 | try: |
|
2255 | 2264 | filename = get_py_filename(arg) |
|
2256 | 2265 | except IOError: |
|
2257 | 2266 | if args.endswith('.py'): |
|
2258 | 2267 | filename = arg |
|
2259 | 2268 | else: |
|
2260 | 2269 | filename = None |
|
2261 | 2270 | return filename |
|
2262 | 2271 | |
|
2263 | 2272 | # custom exceptions |
|
2264 | 2273 | class DataIsObject(Exception): pass |
|
2265 | 2274 | |
|
2266 | 2275 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2267 | 2276 | # Set a few locals from the options for convenience: |
|
2268 | 2277 | opts_p = opts.has_key('p') |
|
2269 | 2278 | opts_r = opts.has_key('r') |
|
2270 | 2279 | |
|
2271 | 2280 | # Default line number value |
|
2272 | 2281 | lineno = opts.get('n',None) |
|
2273 | 2282 | |
|
2274 | 2283 | if opts_p: |
|
2275 | 2284 | args = '_%s' % last_call[0] |
|
2276 | 2285 | if not self.shell.user_ns.has_key(args): |
|
2277 | 2286 | args = last_call[1] |
|
2278 | 2287 | |
|
2279 | 2288 | # use last_call to remember the state of the previous call, but don't |
|
2280 | 2289 | # let it be clobbered by successive '-p' calls. |
|
2281 | 2290 | try: |
|
2282 | 2291 | last_call[0] = self.shell.outputcache.prompt_count |
|
2283 | 2292 | if not opts_p: |
|
2284 | 2293 | last_call[1] = parameter_s |
|
2285 | 2294 | except: |
|
2286 | 2295 | pass |
|
2287 | 2296 | |
|
2288 | 2297 | # by default this is done with temp files, except when the given |
|
2289 | 2298 | # arg is a filename |
|
2290 | 2299 | use_temp = 1 |
|
2291 | 2300 | |
|
2292 | 2301 | if re.match(r'\d',args): |
|
2293 | 2302 | # Mode where user specifies ranges of lines, like in %macro. |
|
2294 | 2303 | # This means that you can't edit files whose names begin with |
|
2295 | 2304 | # numbers this way. Tough. |
|
2296 | 2305 | ranges = args.split() |
|
2297 | 2306 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2298 | 2307 | elif args.endswith('.py'): |
|
2299 | 2308 | filename = make_filename(args) |
|
2300 | 2309 | data = '' |
|
2301 | 2310 | use_temp = 0 |
|
2302 | 2311 | elif args: |
|
2303 | 2312 | try: |
|
2304 | 2313 | # Load the parameter given as a variable. If not a string, |
|
2305 | 2314 | # process it as an object instead (below) |
|
2306 | 2315 | |
|
2307 | 2316 | #print '*** args',args,'type',type(args) # dbg |
|
2308 | 2317 | data = eval(args,self.shell.user_ns) |
|
2309 | 2318 | if not type(data) in StringTypes: |
|
2310 | 2319 | raise DataIsObject |
|
2311 | 2320 | |
|
2312 | 2321 | except (NameError,SyntaxError): |
|
2313 | 2322 | # given argument is not a variable, try as a filename |
|
2314 | 2323 | filename = make_filename(args) |
|
2315 | 2324 | if filename is None: |
|
2316 | 2325 | warn("Argument given (%s) can't be found as a variable " |
|
2317 | 2326 | "or as a filename." % args) |
|
2318 | 2327 | return |
|
2319 | 2328 | |
|
2320 | 2329 | data = '' |
|
2321 | 2330 | use_temp = 0 |
|
2322 | 2331 | except DataIsObject: |
|
2323 | 2332 | |
|
2324 | 2333 | # macros have a special edit function |
|
2325 | 2334 | if isinstance(data,Macro): |
|
2326 | 2335 | self._edit_macro(args,data) |
|
2327 | 2336 | return |
|
2328 | 2337 | |
|
2329 | 2338 | # For objects, try to edit the file where they are defined |
|
2330 | 2339 | try: |
|
2331 | 2340 | filename = inspect.getabsfile(data) |
|
2332 | 2341 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2333 | 2342 | # class created by %edit? Try to find source |
|
2334 | 2343 | # by looking for method definitions instead, the |
|
2335 | 2344 | # __module__ in those classes is FakeModule. |
|
2336 | 2345 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2337 | 2346 | for attr in attrs: |
|
2338 | 2347 | if not inspect.ismethod(attr): |
|
2339 | 2348 | continue |
|
2340 | 2349 | filename = inspect.getabsfile(attr) |
|
2341 | 2350 | if filename and 'fakemodule' not in filename.lower(): |
|
2342 | 2351 | # change the attribute to be the edit target instead |
|
2343 | 2352 | data = attr |
|
2344 | 2353 | break |
|
2345 | 2354 | |
|
2346 | 2355 | datafile = 1 |
|
2347 | 2356 | except TypeError: |
|
2348 | 2357 | filename = make_filename(args) |
|
2349 | 2358 | datafile = 1 |
|
2350 | 2359 | warn('Could not find file where `%s` is defined.\n' |
|
2351 | 2360 | 'Opening a file named `%s`' % (args,filename)) |
|
2352 | 2361 | # Now, make sure we can actually read the source (if it was in |
|
2353 | 2362 | # a temp file it's gone by now). |
|
2354 | 2363 | if datafile: |
|
2355 | 2364 | try: |
|
2356 | 2365 | if lineno is None: |
|
2357 | 2366 | lineno = inspect.getsourcelines(data)[1] |
|
2358 | 2367 | except IOError: |
|
2359 | 2368 | filename = make_filename(args) |
|
2360 | 2369 | if filename is None: |
|
2361 | 2370 | warn('The file `%s` where `%s` was defined cannot ' |
|
2362 | 2371 | 'be read.' % (filename,data)) |
|
2363 | 2372 | return |
|
2364 | 2373 | use_temp = 0 |
|
2365 | 2374 | else: |
|
2366 | 2375 | data = '' |
|
2367 | 2376 | |
|
2368 | 2377 | if use_temp: |
|
2369 | 2378 | filename = self.shell.mktempfile(data) |
|
2370 | 2379 | print 'IPython will make a temporary file named:',filename |
|
2371 | 2380 | |
|
2372 | 2381 | # do actual editing here |
|
2373 | 2382 | print 'Editing...', |
|
2374 | 2383 | sys.stdout.flush() |
|
2375 | 2384 | try: |
|
2376 | 2385 | self.shell.hooks.editor(filename,lineno) |
|
2377 | 2386 | except TryNext: |
|
2378 | 2387 | warn('Could not open editor') |
|
2379 | 2388 | return |
|
2380 | 2389 | |
|
2381 | 2390 | # XXX TODO: should this be generalized for all string vars? |
|
2382 | 2391 | # For now, this is special-cased to blocks created by cpaste |
|
2383 | 2392 | if args.strip() == 'pasted_block': |
|
2384 | 2393 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2385 | 2394 | |
|
2386 | 2395 | if opts.has_key('x'): # -x prevents actual execution |
|
2387 | 2396 | |
|
2388 | 2397 | else: |
|
2389 | 2398 | print 'done. Executing edited code...' |
|
2390 | 2399 | if opts_r: |
|
2391 | 2400 | self.shell.runlines(file_read(filename)) |
|
2392 | 2401 | else: |
|
2393 | 2402 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2394 | 2403 | self.shell.user_ns) |
|
2395 | 2404 | |
|
2396 | 2405 | |
|
2397 | 2406 | if use_temp: |
|
2398 | 2407 | try: |
|
2399 | 2408 | return open(filename).read() |
|
2400 | 2409 | except IOError,msg: |
|
2401 | 2410 | if msg.filename == filename: |
|
2402 | 2411 | warn('File not found. Did you forget to save?') |
|
2403 | 2412 | return |
|
2404 | 2413 | else: |
|
2405 | 2414 | self.shell.showtraceback() |
|
2406 | 2415 | |
|
2407 | 2416 | def magic_xmode(self,parameter_s = ''): |
|
2408 | 2417 | """Switch modes for the exception handlers. |
|
2409 | 2418 | |
|
2410 | 2419 | Valid modes: Plain, Context and Verbose. |
|
2411 | 2420 | |
|
2412 | 2421 | If called without arguments, acts as a toggle.""" |
|
2413 | 2422 | |
|
2414 | 2423 | def xmode_switch_err(name): |
|
2415 | 2424 | warn('Error changing %s exception modes.\n%s' % |
|
2416 | 2425 | (name,sys.exc_info()[1])) |
|
2417 | 2426 | |
|
2418 | 2427 | shell = self.shell |
|
2419 | 2428 | new_mode = parameter_s.strip().capitalize() |
|
2420 | 2429 | try: |
|
2421 | 2430 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2422 | 2431 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2423 | 2432 | except: |
|
2424 | 2433 | xmode_switch_err('user') |
|
2425 | 2434 | |
|
2426 | 2435 | # threaded shells use a special handler in sys.excepthook |
|
2427 | 2436 | if shell.isthreaded: |
|
2428 | 2437 | try: |
|
2429 | 2438 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2430 | 2439 | except: |
|
2431 | 2440 | xmode_switch_err('threaded') |
|
2432 | 2441 | |
|
2433 | 2442 | def magic_colors(self,parameter_s = ''): |
|
2434 | 2443 | """Switch color scheme for prompts, info system and exception handlers. |
|
2435 | 2444 | |
|
2436 | 2445 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2437 | 2446 | |
|
2438 | 2447 | Color scheme names are not case-sensitive.""" |
|
2439 | 2448 | |
|
2440 | 2449 | def color_switch_err(name): |
|
2441 | 2450 | warn('Error changing %s color schemes.\n%s' % |
|
2442 | 2451 | (name,sys.exc_info()[1])) |
|
2443 | 2452 | |
|
2444 | 2453 | |
|
2445 | 2454 | new_scheme = parameter_s.strip() |
|
2446 | 2455 | if not new_scheme: |
|
2447 | 2456 | raise UsageError( |
|
2448 | 2457 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2449 | 2458 | return |
|
2450 | 2459 | # local shortcut |
|
2451 | 2460 | shell = self.shell |
|
2452 | 2461 | |
|
2453 | 2462 | import IPython.utils.rlineimpl as readline |
|
2454 | 2463 | |
|
2455 | 2464 | if not readline.have_readline and sys.platform == "win32": |
|
2456 | 2465 | msg = """\ |
|
2457 | 2466 | Proper color support under MS Windows requires the pyreadline library. |
|
2458 | 2467 | You can find it at: |
|
2459 | 2468 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2460 | 2469 | Gary's readline needs the ctypes module, from: |
|
2461 | 2470 | http://starship.python.net/crew/theller/ctypes |
|
2462 | 2471 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2463 | 2472 | |
|
2464 | 2473 | Defaulting color scheme to 'NoColor'""" |
|
2465 | 2474 | new_scheme = 'NoColor' |
|
2466 | 2475 | warn(msg) |
|
2467 | 2476 | |
|
2468 | 2477 | # readline option is 0 |
|
2469 | 2478 | if not shell.has_readline: |
|
2470 | 2479 | new_scheme = 'NoColor' |
|
2471 | 2480 | |
|
2472 | 2481 | # Set prompt colors |
|
2473 | 2482 | try: |
|
2474 | 2483 | shell.outputcache.set_colors(new_scheme) |
|
2475 | 2484 | except: |
|
2476 | 2485 | color_switch_err('prompt') |
|
2477 | 2486 | else: |
|
2478 | 2487 | shell.colors = \ |
|
2479 | 2488 | shell.outputcache.color_table.active_scheme_name |
|
2480 | 2489 | # Set exception colors |
|
2481 | 2490 | try: |
|
2482 | 2491 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2483 | 2492 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2484 | 2493 | except: |
|
2485 | 2494 | color_switch_err('exception') |
|
2486 | 2495 | |
|
2487 | 2496 | # threaded shells use a verbose traceback in sys.excepthook |
|
2488 | 2497 | if shell.isthreaded: |
|
2489 | 2498 | try: |
|
2490 | 2499 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2491 | 2500 | except: |
|
2492 | 2501 | color_switch_err('system exception handler') |
|
2493 | 2502 | |
|
2494 | 2503 | # Set info (for 'object?') colors |
|
2495 | 2504 | if shell.color_info: |
|
2496 | 2505 | try: |
|
2497 | 2506 | shell.inspector.set_active_scheme(new_scheme) |
|
2498 | 2507 | except: |
|
2499 | 2508 | color_switch_err('object inspector') |
|
2500 | 2509 | else: |
|
2501 | 2510 | shell.inspector.set_active_scheme('NoColor') |
|
2502 | 2511 | |
|
2503 | 2512 | def magic_color_info(self,parameter_s = ''): |
|
2504 | 2513 | """Toggle color_info. |
|
2505 | 2514 | |
|
2506 | 2515 | The color_info configuration parameter controls whether colors are |
|
2507 | 2516 | used for displaying object details (by things like %psource, %pfile or |
|
2508 | 2517 | the '?' system). This function toggles this value with each call. |
|
2509 | 2518 | |
|
2510 | 2519 | Note that unless you have a fairly recent pager (less works better |
|
2511 | 2520 | than more) in your system, using colored object information displays |
|
2512 | 2521 | will not work properly. Test it and see.""" |
|
2513 | 2522 | |
|
2514 | 2523 | self.shell.color_info = not self.shell.color_info |
|
2515 | 2524 | self.magic_colors(self.shell.colors) |
|
2516 | 2525 | print 'Object introspection functions have now coloring:', |
|
2517 | 2526 | print ['OFF','ON'][int(self.shell.color_info)] |
|
2518 | 2527 | |
|
2519 | 2528 | def magic_Pprint(self, parameter_s=''): |
|
2520 | 2529 | """Toggle pretty printing on/off.""" |
|
2521 | 2530 | |
|
2522 | 2531 | self.shell.pprint = 1 - self.shell.pprint |
|
2523 | 2532 | print 'Pretty printing has been turned', \ |
|
2524 | 2533 | ['OFF','ON'][self.shell.pprint] |
|
2525 | 2534 | |
|
2526 | def magic_exit(self, parameter_s=''): | |
|
2527 | """Exit IPython, confirming if configured to do so. | |
|
2528 | ||
|
2529 | You can configure whether IPython asks for confirmation upon exit by | |
|
2530 | setting the confirm_exit flag in the ipythonrc file.""" | |
|
2531 | ||
|
2532 | self.shell.exit() | |
|
2533 | ||
|
2534 | def magic_quit(self, parameter_s=''): | |
|
2535 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
|
2536 | ||
|
2537 | self.shell.exit() | |
|
2538 | ||
|
2539 | 2535 | def magic_Exit(self, parameter_s=''): |
|
2540 | 2536 | """Exit IPython without confirmation.""" |
|
2541 | 2537 | |
|
2542 | 2538 | self.shell.ask_exit() |
|
2543 | 2539 | |
|
2544 | 2540 | #...................................................................... |
|
2545 | 2541 | # Functions to implement unix shell-type things |
|
2546 | 2542 | |
|
2547 | 2543 | @testdec.skip_doctest |
|
2548 | 2544 | def magic_alias(self, parameter_s = ''): |
|
2549 | 2545 | """Define an alias for a system command. |
|
2550 | 2546 | |
|
2551 | 2547 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2552 | 2548 | |
|
2553 | 2549 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2554 | 2550 | params' (from your underlying operating system). |
|
2555 | 2551 | |
|
2556 | 2552 | Aliases have lower precedence than magic functions and Python normal |
|
2557 | 2553 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2558 | 2554 | alias can not be executed until 'del foo' removes the Python variable. |
|
2559 | 2555 | |
|
2560 | 2556 | You can use the %l specifier in an alias definition to represent the |
|
2561 | 2557 | whole line when the alias is called. For example: |
|
2562 | 2558 | |
|
2563 | 2559 | In [2]: alias all echo "Input in brackets: <%l>" |
|
2564 | 2560 | In [3]: all hello world |
|
2565 | 2561 | Input in brackets: <hello world> |
|
2566 | 2562 | |
|
2567 | 2563 | You can also define aliases with parameters using %s specifiers (one |
|
2568 | 2564 | per parameter): |
|
2569 | 2565 | |
|
2570 | 2566 | In [1]: alias parts echo first %s second %s |
|
2571 | 2567 | In [2]: %parts A B |
|
2572 | 2568 | first A second B |
|
2573 | 2569 | In [3]: %parts A |
|
2574 | 2570 | Incorrect number of arguments: 2 expected. |
|
2575 | 2571 | parts is an alias to: 'echo first %s second %s' |
|
2576 | 2572 | |
|
2577 | 2573 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2578 | 2574 | the other in your aliases. |
|
2579 | 2575 | |
|
2580 | 2576 | Aliases expand Python variables just like system calls using ! or !! |
|
2581 | 2577 | do: all expressions prefixed with '$' get expanded. For details of |
|
2582 | 2578 | the semantic rules, see PEP-215: |
|
2583 | 2579 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2584 | 2580 | IPython for variable expansion. If you want to access a true shell |
|
2585 | 2581 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2586 | 2582 | |
|
2587 | 2583 | In [6]: alias show echo |
|
2588 | 2584 | In [7]: PATH='A Python string' |
|
2589 | 2585 | In [8]: show $PATH |
|
2590 | 2586 | A Python string |
|
2591 | 2587 | In [9]: show $$PATH |
|
2592 | 2588 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2593 | 2589 | |
|
2594 | 2590 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2595 | 2591 | and %rehashx functions, which automatically create aliases for the |
|
2596 | 2592 | contents of your $PATH. |
|
2597 | 2593 | |
|
2598 | 2594 | If called with no parameters, %alias prints the current alias table.""" |
|
2599 | 2595 | |
|
2600 | 2596 | par = parameter_s.strip() |
|
2601 | 2597 | if not par: |
|
2602 | 2598 | stored = self.db.get('stored_aliases', {} ) |
|
2603 | 2599 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2604 | 2600 | # for k, v in stored: |
|
2605 | 2601 | # atab.append(k, v[0]) |
|
2606 | 2602 | |
|
2607 | 2603 | print "Total number of aliases:", len(aliases) |
|
2608 | 2604 | return aliases |
|
2609 | 2605 | |
|
2610 | 2606 | # Now try to define a new one |
|
2611 | 2607 | try: |
|
2612 | 2608 | alias,cmd = par.split(None, 1) |
|
2613 | 2609 | except: |
|
2614 | 2610 | print oinspect.getdoc(self.magic_alias) |
|
2615 | 2611 | else: |
|
2616 | 2612 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2617 | 2613 | # end magic_alias |
|
2618 | 2614 | |
|
2619 | 2615 | def magic_unalias(self, parameter_s = ''): |
|
2620 | 2616 | """Remove an alias""" |
|
2621 | 2617 | |
|
2622 | 2618 | aname = parameter_s.strip() |
|
2623 | 2619 | self.shell.alias_manager.undefine_alias(aname) |
|
2624 | 2620 | stored = self.db.get('stored_aliases', {} ) |
|
2625 | 2621 | if aname in stored: |
|
2626 | 2622 | print "Removing %stored alias",aname |
|
2627 | 2623 | del stored[aname] |
|
2628 | 2624 | self.db['stored_aliases'] = stored |
|
2629 | 2625 | |
|
2630 | 2626 | |
|
2631 | 2627 | def magic_rehashx(self, parameter_s = ''): |
|
2632 | 2628 | """Update the alias table with all executable files in $PATH. |
|
2633 | 2629 | |
|
2634 | 2630 | This version explicitly checks that every entry in $PATH is a file |
|
2635 | 2631 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2636 | 2632 | |
|
2637 | 2633 | Under Windows, it checks executability as a match agains a |
|
2638 | 2634 | '|'-separated string of extensions, stored in the IPython config |
|
2639 | 2635 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2640 | 2636 | |
|
2641 | 2637 | This function also resets the root module cache of module completer, |
|
2642 | 2638 | used on slow filesystems. |
|
2643 | 2639 | """ |
|
2644 | 2640 | from IPython.core.alias import InvalidAliasError |
|
2645 | 2641 | |
|
2646 | 2642 | # for the benefit of module completer in ipy_completers.py |
|
2647 | 2643 | del self.db['rootmodules'] |
|
2648 | 2644 | |
|
2649 | 2645 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2650 | 2646 | os.environ.get('PATH','').split(os.pathsep)] |
|
2651 | 2647 | path = filter(os.path.isdir,path) |
|
2652 | 2648 | |
|
2653 | 2649 | syscmdlist = [] |
|
2654 | 2650 | # Now define isexec in a cross platform manner. |
|
2655 | 2651 | if os.name == 'posix': |
|
2656 | 2652 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2657 | 2653 | os.access(fname,os.X_OK) |
|
2658 | 2654 | else: |
|
2659 | 2655 | try: |
|
2660 | 2656 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2661 | 2657 | except KeyError: |
|
2662 | 2658 | winext = 'exe|com|bat|py' |
|
2663 | 2659 | if 'py' not in winext: |
|
2664 | 2660 | winext += '|py' |
|
2665 | 2661 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2666 | 2662 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2667 | 2663 | savedir = os.getcwd() |
|
2668 | 2664 | |
|
2669 | 2665 | # Now walk the paths looking for executables to alias. |
|
2670 | 2666 | try: |
|
2671 | 2667 | # write the whole loop for posix/Windows so we don't have an if in |
|
2672 | 2668 | # the innermost part |
|
2673 | 2669 | if os.name == 'posix': |
|
2674 | 2670 | for pdir in path: |
|
2675 | 2671 | os.chdir(pdir) |
|
2676 | 2672 | for ff in os.listdir(pdir): |
|
2677 | 2673 | if isexec(ff): |
|
2678 | 2674 | try: |
|
2679 | 2675 | # Removes dots from the name since ipython |
|
2680 | 2676 | # will assume names with dots to be python. |
|
2681 | 2677 | self.shell.alias_manager.define_alias( |
|
2682 | 2678 | ff.replace('.',''), ff) |
|
2683 | 2679 | except InvalidAliasError: |
|
2684 | 2680 | pass |
|
2685 | 2681 | else: |
|
2686 | 2682 | syscmdlist.append(ff) |
|
2687 | 2683 | else: |
|
2684 | no_alias = self.shell.alias_manager.no_alias | |
|
2688 | 2685 | for pdir in path: |
|
2689 | 2686 | os.chdir(pdir) |
|
2690 | 2687 | for ff in os.listdir(pdir): |
|
2691 | 2688 | base, ext = os.path.splitext(ff) |
|
2692 |
if isexec(ff) and base.lower() not in |
|
|
2689 | if isexec(ff) and base.lower() not in no_alias: | |
|
2693 | 2690 | if ext.lower() == '.exe': |
|
2694 | 2691 | ff = base |
|
2695 | 2692 | try: |
|
2696 | 2693 | # Removes dots from the name since ipython |
|
2697 | 2694 | # will assume names with dots to be python. |
|
2698 | 2695 | self.shell.alias_manager.define_alias( |
|
2699 | 2696 | base.lower().replace('.',''), ff) |
|
2700 | 2697 | except InvalidAliasError: |
|
2701 | 2698 | pass |
|
2702 | 2699 | syscmdlist.append(ff) |
|
2703 | 2700 | db = self.db |
|
2704 | 2701 | db['syscmdlist'] = syscmdlist |
|
2705 | 2702 | finally: |
|
2706 | 2703 | os.chdir(savedir) |
|
2707 | 2704 | |
|
2708 | 2705 | def magic_pwd(self, parameter_s = ''): |
|
2709 | 2706 | """Return the current working directory path.""" |
|
2710 | 2707 | return os.getcwd() |
|
2711 | 2708 | |
|
2712 | 2709 | def magic_cd(self, parameter_s=''): |
|
2713 | 2710 | """Change the current working directory. |
|
2714 | 2711 | |
|
2715 | 2712 | This command automatically maintains an internal list of directories |
|
2716 | 2713 | you visit during your IPython session, in the variable _dh. The |
|
2717 | 2714 | command %dhist shows this history nicely formatted. You can also |
|
2718 | 2715 | do 'cd -<tab>' to see directory history conveniently. |
|
2719 | 2716 | |
|
2720 | 2717 | Usage: |
|
2721 | 2718 | |
|
2722 | 2719 | cd 'dir': changes to directory 'dir'. |
|
2723 | 2720 | |
|
2724 | 2721 | cd -: changes to the last visited directory. |
|
2725 | 2722 | |
|
2726 | 2723 | cd -<n>: changes to the n-th directory in the directory history. |
|
2727 | 2724 | |
|
2728 | 2725 | cd --foo: change to directory that matches 'foo' in history |
|
2729 | 2726 | |
|
2730 | 2727 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2731 | 2728 | (note: cd <bookmark_name> is enough if there is no |
|
2732 | 2729 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2733 | 2730 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2734 | 2731 | |
|
2735 | 2732 | Options: |
|
2736 | 2733 | |
|
2737 | 2734 | -q: quiet. Do not print the working directory after the cd command is |
|
2738 | 2735 | executed. By default IPython's cd command does print this directory, |
|
2739 | 2736 | since the default prompts do not display path information. |
|
2740 | 2737 | |
|
2741 | 2738 | Note that !cd doesn't work for this purpose because the shell where |
|
2742 | 2739 | !command runs is immediately discarded after executing 'command'.""" |
|
2743 | 2740 | |
|
2744 | 2741 | parameter_s = parameter_s.strip() |
|
2745 | 2742 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2746 | 2743 | |
|
2747 | 2744 | oldcwd = os.getcwd() |
|
2748 | 2745 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2749 | 2746 | # jump in directory history by number |
|
2750 | 2747 | if numcd: |
|
2751 | 2748 | nn = int(numcd.group(2)) |
|
2752 | 2749 | try: |
|
2753 | 2750 | ps = self.shell.user_ns['_dh'][nn] |
|
2754 | 2751 | except IndexError: |
|
2755 | 2752 | print 'The requested directory does not exist in history.' |
|
2756 | 2753 | return |
|
2757 | 2754 | else: |
|
2758 | 2755 | opts = {} |
|
2759 | 2756 | elif parameter_s.startswith('--'): |
|
2760 | 2757 | ps = None |
|
2761 | 2758 | fallback = None |
|
2762 | 2759 | pat = parameter_s[2:] |
|
2763 | 2760 | dh = self.shell.user_ns['_dh'] |
|
2764 | 2761 | # first search only by basename (last component) |
|
2765 | 2762 | for ent in reversed(dh): |
|
2766 | 2763 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2767 | 2764 | ps = ent |
|
2768 | 2765 | break |
|
2769 | 2766 | |
|
2770 | 2767 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2771 | 2768 | fallback = ent |
|
2772 | 2769 | |
|
2773 | 2770 | # if we have no last part match, pick the first full path match |
|
2774 | 2771 | if ps is None: |
|
2775 | 2772 | ps = fallback |
|
2776 | 2773 | |
|
2777 | 2774 | if ps is None: |
|
2778 | 2775 | print "No matching entry in directory history" |
|
2779 | 2776 | return |
|
2780 | 2777 | else: |
|
2781 | 2778 | opts = {} |
|
2782 | 2779 | |
|
2783 | 2780 | |
|
2784 | 2781 | else: |
|
2785 | 2782 | #turn all non-space-escaping backslashes to slashes, |
|
2786 | 2783 | # for c:\windows\directory\names\ |
|
2787 | 2784 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2788 | 2785 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2789 | 2786 | # jump to previous |
|
2790 | 2787 | if ps == '-': |
|
2791 | 2788 | try: |
|
2792 | 2789 | ps = self.shell.user_ns['_dh'][-2] |
|
2793 | 2790 | except IndexError: |
|
2794 | 2791 | raise UsageError('%cd -: No previous directory to change to.') |
|
2795 | 2792 | # jump to bookmark if needed |
|
2796 | 2793 | else: |
|
2797 | 2794 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2798 | 2795 | bkms = self.db.get('bookmarks', {}) |
|
2799 | 2796 | |
|
2800 | 2797 | if bkms.has_key(ps): |
|
2801 | 2798 | target = bkms[ps] |
|
2802 | 2799 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2803 | 2800 | ps = target |
|
2804 | 2801 | else: |
|
2805 | 2802 | if opts.has_key('b'): |
|
2806 | 2803 | raise UsageError("Bookmark '%s' not found. " |
|
2807 | 2804 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2808 | 2805 | |
|
2809 | 2806 | # at this point ps should point to the target dir |
|
2810 | 2807 | if ps: |
|
2811 | 2808 | try: |
|
2812 | 2809 | os.chdir(os.path.expanduser(ps)) |
|
2813 | 2810 | if self.shell.term_title: |
|
2814 | 2811 | platutils.set_term_title('IPython: ' + abbrev_cwd()) |
|
2815 | 2812 | except OSError: |
|
2816 | 2813 | print sys.exc_info()[1] |
|
2817 | 2814 | else: |
|
2818 | 2815 | cwd = os.getcwd() |
|
2819 | 2816 | dhist = self.shell.user_ns['_dh'] |
|
2820 | 2817 | if oldcwd != cwd: |
|
2821 | 2818 | dhist.append(cwd) |
|
2822 | 2819 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2823 | 2820 | |
|
2824 | 2821 | else: |
|
2825 | 2822 | os.chdir(self.shell.home_dir) |
|
2826 | 2823 | if self.shell.term_title: |
|
2827 | 2824 | platutils.set_term_title('IPython: ' + '~') |
|
2828 | 2825 | cwd = os.getcwd() |
|
2829 | 2826 | dhist = self.shell.user_ns['_dh'] |
|
2830 | 2827 | |
|
2831 | 2828 | if oldcwd != cwd: |
|
2832 | 2829 | dhist.append(cwd) |
|
2833 | 2830 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2834 | 2831 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2835 | 2832 | print self.shell.user_ns['_dh'][-1] |
|
2836 | 2833 | |
|
2837 | 2834 | |
|
2838 | 2835 | def magic_env(self, parameter_s=''): |
|
2839 | 2836 | """List environment variables.""" |
|
2840 | 2837 | |
|
2841 | 2838 | return os.environ.data |
|
2842 | 2839 | |
|
2843 | 2840 | def magic_pushd(self, parameter_s=''): |
|
2844 | 2841 | """Place the current dir on stack and change directory. |
|
2845 | 2842 | |
|
2846 | 2843 | Usage:\\ |
|
2847 | 2844 | %pushd ['dirname'] |
|
2848 | 2845 | """ |
|
2849 | 2846 | |
|
2850 | 2847 | dir_s = self.shell.dir_stack |
|
2851 | 2848 | tgt = os.path.expanduser(parameter_s) |
|
2852 | 2849 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2853 | 2850 | if tgt: |
|
2854 | 2851 | self.magic_cd(parameter_s) |
|
2855 | 2852 | dir_s.insert(0,cwd) |
|
2856 | 2853 | return self.magic_dirs() |
|
2857 | 2854 | |
|
2858 | 2855 | def magic_popd(self, parameter_s=''): |
|
2859 | 2856 | """Change to directory popped off the top of the stack. |
|
2860 | 2857 | """ |
|
2861 | 2858 | if not self.shell.dir_stack: |
|
2862 | 2859 | raise UsageError("%popd on empty stack") |
|
2863 | 2860 | top = self.shell.dir_stack.pop(0) |
|
2864 | 2861 | self.magic_cd(top) |
|
2865 | 2862 | print "popd ->",top |
|
2866 | 2863 | |
|
2867 | 2864 | def magic_dirs(self, parameter_s=''): |
|
2868 | 2865 | """Return the current directory stack.""" |
|
2869 | 2866 | |
|
2870 | 2867 | return self.shell.dir_stack |
|
2871 | 2868 | |
|
2872 | 2869 | def magic_dhist(self, parameter_s=''): |
|
2873 | 2870 | """Print your history of visited directories. |
|
2874 | 2871 | |
|
2875 | 2872 | %dhist -> print full history\\ |
|
2876 | 2873 | %dhist n -> print last n entries only\\ |
|
2877 | 2874 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2878 | 2875 | |
|
2879 | 2876 | This history is automatically maintained by the %cd command, and |
|
2880 | 2877 | always available as the global list variable _dh. You can use %cd -<n> |
|
2881 | 2878 | to go to directory number <n>. |
|
2882 | 2879 | |
|
2883 | 2880 | Note that most of time, you should view directory history by entering |
|
2884 | 2881 | cd -<TAB>. |
|
2885 | 2882 | |
|
2886 | 2883 | """ |
|
2887 | 2884 | |
|
2888 | 2885 | dh = self.shell.user_ns['_dh'] |
|
2889 | 2886 | if parameter_s: |
|
2890 | 2887 | try: |
|
2891 | 2888 | args = map(int,parameter_s.split()) |
|
2892 | 2889 | except: |
|
2893 | 2890 | self.arg_err(Magic.magic_dhist) |
|
2894 | 2891 | return |
|
2895 | 2892 | if len(args) == 1: |
|
2896 | 2893 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2897 | 2894 | elif len(args) == 2: |
|
2898 | 2895 | ini,fin = args |
|
2899 | 2896 | else: |
|
2900 | 2897 | self.arg_err(Magic.magic_dhist) |
|
2901 | 2898 | return |
|
2902 | 2899 | else: |
|
2903 | 2900 | ini,fin = 0,len(dh) |
|
2904 | 2901 | nlprint(dh, |
|
2905 | 2902 | header = 'Directory history (kept in _dh)', |
|
2906 | 2903 | start=ini,stop=fin) |
|
2907 | 2904 | |
|
2908 | 2905 | @testdec.skip_doctest |
|
2909 | 2906 | def magic_sc(self, parameter_s=''): |
|
2910 | 2907 | """Shell capture - execute a shell command and capture its output. |
|
2911 | 2908 | |
|
2912 | 2909 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2913 | 2910 | |
|
2914 | 2911 | You should use the form 'var = !command' instead. Example: |
|
2915 | 2912 | |
|
2916 | 2913 | "%sc -l myfiles = ls ~" should now be written as |
|
2917 | 2914 | |
|
2918 | 2915 | "myfiles = !ls ~" |
|
2919 | 2916 | |
|
2920 | 2917 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2921 | 2918 | below. |
|
2922 | 2919 | |
|
2923 | 2920 | -- |
|
2924 | 2921 | %sc [options] varname=command |
|
2925 | 2922 | |
|
2926 | 2923 | IPython will run the given command using commands.getoutput(), and |
|
2927 | 2924 | will then update the user's interactive namespace with a variable |
|
2928 | 2925 | called varname, containing the value of the call. Your command can |
|
2929 | 2926 | contain shell wildcards, pipes, etc. |
|
2930 | 2927 | |
|
2931 | 2928 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2932 | 2929 | supply must follow Python's standard conventions for valid names. |
|
2933 | 2930 | |
|
2934 | 2931 | (A special format without variable name exists for internal use) |
|
2935 | 2932 | |
|
2936 | 2933 | Options: |
|
2937 | 2934 | |
|
2938 | 2935 | -l: list output. Split the output on newlines into a list before |
|
2939 | 2936 | assigning it to the given variable. By default the output is stored |
|
2940 | 2937 | as a single string. |
|
2941 | 2938 | |
|
2942 | 2939 | -v: verbose. Print the contents of the variable. |
|
2943 | 2940 | |
|
2944 | 2941 | In most cases you should not need to split as a list, because the |
|
2945 | 2942 | returned value is a special type of string which can automatically |
|
2946 | 2943 | provide its contents either as a list (split on newlines) or as a |
|
2947 | 2944 | space-separated string. These are convenient, respectively, either |
|
2948 | 2945 | for sequential processing or to be passed to a shell command. |
|
2949 | 2946 | |
|
2950 | 2947 | For example: |
|
2951 | 2948 | |
|
2952 | 2949 | # all-random |
|
2953 | 2950 | |
|
2954 | 2951 | # Capture into variable a |
|
2955 | 2952 | In [1]: sc a=ls *py |
|
2956 | 2953 | |
|
2957 | 2954 | # a is a string with embedded newlines |
|
2958 | 2955 | In [2]: a |
|
2959 | 2956 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2960 | 2957 | |
|
2961 | 2958 | # which can be seen as a list: |
|
2962 | 2959 | In [3]: a.l |
|
2963 | 2960 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2964 | 2961 | |
|
2965 | 2962 | # or as a whitespace-separated string: |
|
2966 | 2963 | In [4]: a.s |
|
2967 | 2964 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2968 | 2965 | |
|
2969 | 2966 | # a.s is useful to pass as a single command line: |
|
2970 | 2967 | In [5]: !wc -l $a.s |
|
2971 | 2968 | 146 setup.py |
|
2972 | 2969 | 130 win32_manual_post_install.py |
|
2973 | 2970 | 276 total |
|
2974 | 2971 | |
|
2975 | 2972 | # while the list form is useful to loop over: |
|
2976 | 2973 | In [6]: for f in a.l: |
|
2977 | 2974 | ...: !wc -l $f |
|
2978 | 2975 | ...: |
|
2979 | 2976 | 146 setup.py |
|
2980 | 2977 | 130 win32_manual_post_install.py |
|
2981 | 2978 | |
|
2982 | 2979 | Similiarly, the lists returned by the -l option are also special, in |
|
2983 | 2980 | the sense that you can equally invoke the .s attribute on them to |
|
2984 | 2981 | automatically get a whitespace-separated string from their contents: |
|
2985 | 2982 | |
|
2986 | 2983 | In [7]: sc -l b=ls *py |
|
2987 | 2984 | |
|
2988 | 2985 | In [8]: b |
|
2989 | 2986 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2990 | 2987 | |
|
2991 | 2988 | In [9]: b.s |
|
2992 | 2989 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2993 | 2990 | |
|
2994 | 2991 | In summary, both the lists and strings used for ouptut capture have |
|
2995 | 2992 | the following special attributes: |
|
2996 | 2993 | |
|
2997 | 2994 | .l (or .list) : value as list. |
|
2998 | 2995 | .n (or .nlstr): value as newline-separated string. |
|
2999 | 2996 | .s (or .spstr): value as space-separated string. |
|
3000 | 2997 | """ |
|
3001 | 2998 | |
|
3002 | 2999 | opts,args = self.parse_options(parameter_s,'lv') |
|
3003 | 3000 | # Try to get a variable name and command to run |
|
3004 | 3001 | try: |
|
3005 | 3002 | # the variable name must be obtained from the parse_options |
|
3006 | 3003 | # output, which uses shlex.split to strip options out. |
|
3007 | 3004 | var,_ = args.split('=',1) |
|
3008 | 3005 | var = var.strip() |
|
3009 | 3006 | # But the the command has to be extracted from the original input |
|
3010 | 3007 | # parameter_s, not on what parse_options returns, to avoid the |
|
3011 | 3008 | # quote stripping which shlex.split performs on it. |
|
3012 | 3009 | _,cmd = parameter_s.split('=',1) |
|
3013 | 3010 | except ValueError: |
|
3014 | 3011 | var,cmd = '','' |
|
3015 | 3012 | # If all looks ok, proceed |
|
3016 | 3013 | out,err = self.shell.getoutputerror(cmd) |
|
3017 | 3014 | if err: |
|
3018 | 3015 | print >> Term.cerr,err |
|
3019 | 3016 | if opts.has_key('l'): |
|
3020 | 3017 | out = SList(out.split('\n')) |
|
3021 | 3018 | else: |
|
3022 | 3019 | out = LSString(out) |
|
3023 | 3020 | if opts.has_key('v'): |
|
3024 | 3021 | print '%s ==\n%s' % (var,pformat(out)) |
|
3025 | 3022 | if var: |
|
3026 | 3023 | self.shell.user_ns.update({var:out}) |
|
3027 | 3024 | else: |
|
3028 | 3025 | return out |
|
3029 | 3026 | |
|
3030 | 3027 | def magic_sx(self, parameter_s=''): |
|
3031 | 3028 | """Shell execute - run a shell command and capture its output. |
|
3032 | 3029 | |
|
3033 | 3030 | %sx command |
|
3034 | 3031 | |
|
3035 | 3032 | IPython will run the given command using commands.getoutput(), and |
|
3036 | 3033 | return the result formatted as a list (split on '\\n'). Since the |
|
3037 | 3034 | output is _returned_, it will be stored in ipython's regular output |
|
3038 | 3035 | cache Out[N] and in the '_N' automatic variables. |
|
3039 | 3036 | |
|
3040 | 3037 | Notes: |
|
3041 | 3038 | |
|
3042 | 3039 | 1) If an input line begins with '!!', then %sx is automatically |
|
3043 | 3040 | invoked. That is, while: |
|
3044 | 3041 | !ls |
|
3045 | 3042 | causes ipython to simply issue system('ls'), typing |
|
3046 | 3043 | !!ls |
|
3047 | 3044 | is a shorthand equivalent to: |
|
3048 | 3045 | %sx ls |
|
3049 | 3046 | |
|
3050 | 3047 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3051 | 3048 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3052 | 3049 | to process line-oriented shell output via further python commands. |
|
3053 | 3050 | %sc is meant to provide much finer control, but requires more |
|
3054 | 3051 | typing. |
|
3055 | 3052 | |
|
3056 | 3053 | 3) Just like %sc -l, this is a list with special attributes: |
|
3057 | 3054 | |
|
3058 | 3055 | .l (or .list) : value as list. |
|
3059 | 3056 | .n (or .nlstr): value as newline-separated string. |
|
3060 | 3057 | .s (or .spstr): value as whitespace-separated string. |
|
3061 | 3058 | |
|
3062 | 3059 | This is very useful when trying to use such lists as arguments to |
|
3063 | 3060 | system commands.""" |
|
3064 | 3061 | |
|
3065 | 3062 | if parameter_s: |
|
3066 | 3063 | out,err = self.shell.getoutputerror(parameter_s) |
|
3067 | 3064 | if err: |
|
3068 | 3065 | print >> Term.cerr,err |
|
3069 | 3066 | return SList(out.split('\n')) |
|
3070 | 3067 | |
|
3071 | 3068 | def magic_bg(self, parameter_s=''): |
|
3072 | 3069 | """Run a job in the background, in a separate thread. |
|
3073 | 3070 | |
|
3074 | 3071 | For example, |
|
3075 | 3072 | |
|
3076 | 3073 | %bg myfunc(x,y,z=1) |
|
3077 | 3074 | |
|
3078 | 3075 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
3079 | 3076 | execution starts, a message will be printed indicating the job |
|
3080 | 3077 | number. If your job number is 5, you can use |
|
3081 | 3078 | |
|
3082 | 3079 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
3083 | 3080 | |
|
3084 | 3081 | to assign this result to variable 'myvar'. |
|
3085 | 3082 | |
|
3086 | 3083 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
3087 | 3084 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
3088 | 3085 | its attributes. All attributes not starting with an underscore are |
|
3089 | 3086 | meant for public use. |
|
3090 | 3087 | |
|
3091 | 3088 | In particular, look at the jobs.new() method, which is used to create |
|
3092 | 3089 | new jobs. This magic %bg function is just a convenience wrapper |
|
3093 | 3090 | around jobs.new(), for expression-based jobs. If you want to create a |
|
3094 | 3091 | new job with an explicit function object and arguments, you must call |
|
3095 | 3092 | jobs.new() directly. |
|
3096 | 3093 | |
|
3097 | 3094 | The jobs.new docstring also describes in detail several important |
|
3098 | 3095 | caveats associated with a thread-based model for background job |
|
3099 | 3096 | execution. Type jobs.new? for details. |
|
3100 | 3097 | |
|
3101 | 3098 | You can check the status of all jobs with jobs.status(). |
|
3102 | 3099 | |
|
3103 | 3100 | The jobs variable is set by IPython into the Python builtin namespace. |
|
3104 | 3101 | If you ever declare a variable named 'jobs', you will shadow this |
|
3105 | 3102 | name. You can either delete your global jobs variable to regain |
|
3106 | 3103 | access to the job manager, or make a new name and assign it manually |
|
3107 | 3104 | to the manager (stored in IPython's namespace). For example, to |
|
3108 | 3105 | assign the job manager to the Jobs name, use: |
|
3109 | 3106 | |
|
3110 | 3107 | Jobs = __builtins__.jobs""" |
|
3111 | 3108 | |
|
3112 | 3109 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
3113 | 3110 | |
|
3114 | 3111 | def magic_r(self, parameter_s=''): |
|
3115 | 3112 | """Repeat previous input. |
|
3116 | 3113 | |
|
3117 | 3114 | Note: Consider using the more powerfull %rep instead! |
|
3118 | 3115 | |
|
3119 | 3116 | If given an argument, repeats the previous command which starts with |
|
3120 | 3117 | the same string, otherwise it just repeats the previous input. |
|
3121 | 3118 | |
|
3122 | 3119 | Shell escaped commands (with ! as first character) are not recognized |
|
3123 | 3120 | by this system, only pure python code and magic commands. |
|
3124 | 3121 | """ |
|
3125 | 3122 | |
|
3126 | 3123 | start = parameter_s.strip() |
|
3127 | 3124 | esc_magic = ESC_MAGIC |
|
3128 | 3125 | # Identify magic commands even if automagic is on (which means |
|
3129 | 3126 | # the in-memory version is different from that typed by the user). |
|
3130 | 3127 | if self.shell.automagic: |
|
3131 | 3128 | start_magic = esc_magic+start |
|
3132 | 3129 | else: |
|
3133 | 3130 | start_magic = start |
|
3134 | 3131 | # Look through the input history in reverse |
|
3135 | 3132 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
3136 | 3133 | input = self.shell.input_hist[n] |
|
3137 | 3134 | # skip plain 'r' lines so we don't recurse to infinity |
|
3138 | 3135 | if input != '_ip.magic("r")\n' and \ |
|
3139 | 3136 | (input.startswith(start) or input.startswith(start_magic)): |
|
3140 | 3137 | #print 'match',`input` # dbg |
|
3141 | 3138 | print 'Executing:',input, |
|
3142 | 3139 | self.shell.runlines(input) |
|
3143 | 3140 | return |
|
3144 | 3141 | print 'No previous input matching `%s` found.' % start |
|
3145 | 3142 | |
|
3146 | 3143 | |
|
3147 | 3144 | def magic_bookmark(self, parameter_s=''): |
|
3148 | 3145 | """Manage IPython's bookmark system. |
|
3149 | 3146 | |
|
3150 | 3147 | %bookmark <name> - set bookmark to current dir |
|
3151 | 3148 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3152 | 3149 | %bookmark -l - list all bookmarks |
|
3153 | 3150 | %bookmark -d <name> - remove bookmark |
|
3154 | 3151 | %bookmark -r - remove all bookmarks |
|
3155 | 3152 | |
|
3156 | 3153 | You can later on access a bookmarked folder with: |
|
3157 | 3154 | %cd -b <name> |
|
3158 | 3155 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3159 | 3156 | there is such a bookmark defined. |
|
3160 | 3157 | |
|
3161 | 3158 | Your bookmarks persist through IPython sessions, but they are |
|
3162 | 3159 | associated with each profile.""" |
|
3163 | 3160 | |
|
3164 | 3161 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3165 | 3162 | if len(args) > 2: |
|
3166 | 3163 | raise UsageError("%bookmark: too many arguments") |
|
3167 | 3164 | |
|
3168 | 3165 | bkms = self.db.get('bookmarks',{}) |
|
3169 | 3166 | |
|
3170 | 3167 | if opts.has_key('d'): |
|
3171 | 3168 | try: |
|
3172 | 3169 | todel = args[0] |
|
3173 | 3170 | except IndexError: |
|
3174 | 3171 | raise UsageError( |
|
3175 | 3172 | "%bookmark -d: must provide a bookmark to delete") |
|
3176 | 3173 | else: |
|
3177 | 3174 | try: |
|
3178 | 3175 | del bkms[todel] |
|
3179 | 3176 | except KeyError: |
|
3180 | 3177 | raise UsageError( |
|
3181 | 3178 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3182 | 3179 | |
|
3183 | 3180 | elif opts.has_key('r'): |
|
3184 | 3181 | bkms = {} |
|
3185 | 3182 | elif opts.has_key('l'): |
|
3186 | 3183 | bks = bkms.keys() |
|
3187 | 3184 | bks.sort() |
|
3188 | 3185 | if bks: |
|
3189 | 3186 | size = max(map(len,bks)) |
|
3190 | 3187 | else: |
|
3191 | 3188 | size = 0 |
|
3192 | 3189 | fmt = '%-'+str(size)+'s -> %s' |
|
3193 | 3190 | print 'Current bookmarks:' |
|
3194 | 3191 | for bk in bks: |
|
3195 | 3192 | print fmt % (bk,bkms[bk]) |
|
3196 | 3193 | else: |
|
3197 | 3194 | if not args: |
|
3198 | 3195 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3199 | 3196 | elif len(args)==1: |
|
3200 | 3197 | bkms[args[0]] = os.getcwd() |
|
3201 | 3198 | elif len(args)==2: |
|
3202 | 3199 | bkms[args[0]] = args[1] |
|
3203 | 3200 | self.db['bookmarks'] = bkms |
|
3204 | 3201 | |
|
3205 | 3202 | def magic_pycat(self, parameter_s=''): |
|
3206 | 3203 | """Show a syntax-highlighted file through a pager. |
|
3207 | 3204 | |
|
3208 | 3205 | This magic is similar to the cat utility, but it will assume the file |
|
3209 | 3206 | to be Python source and will show it with syntax highlighting. """ |
|
3210 | 3207 | |
|
3211 | 3208 | try: |
|
3212 | 3209 | filename = get_py_filename(parameter_s) |
|
3213 | 3210 | cont = file_read(filename) |
|
3214 | 3211 | except IOError: |
|
3215 | 3212 | try: |
|
3216 | 3213 | cont = eval(parameter_s,self.user_ns) |
|
3217 | 3214 | except NameError: |
|
3218 | 3215 | cont = None |
|
3219 | 3216 | if cont is None: |
|
3220 | 3217 | print "Error: no such file or variable" |
|
3221 | 3218 | return |
|
3222 | 3219 | |
|
3223 | 3220 | page(self.shell.pycolorize(cont), |
|
3224 | 3221 | screen_lines=self.shell.usable_screen_length) |
|
3225 | 3222 | |
|
3226 | 3223 | def _rerun_pasted(self): |
|
3227 | 3224 | """ Rerun a previously pasted command. |
|
3228 | 3225 | """ |
|
3229 | 3226 | b = self.user_ns.get('pasted_block', None) |
|
3230 | 3227 | if b is None: |
|
3231 | 3228 | raise UsageError('No previous pasted block available') |
|
3232 | 3229 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3233 | 3230 | exec b in self.user_ns |
|
3234 | 3231 | |
|
3235 | 3232 | def _get_pasted_lines(self, sentinel): |
|
3236 | 3233 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3237 | 3234 | """ |
|
3238 | 3235 | from IPython.core import iplib |
|
3239 | 3236 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3240 | 3237 | while True: |
|
3241 | 3238 | l = iplib.raw_input_original(':') |
|
3242 | 3239 | if l == sentinel: |
|
3243 | 3240 | return |
|
3244 | 3241 | else: |
|
3245 | 3242 | yield l |
|
3246 | 3243 | |
|
3247 | 3244 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3248 | 3245 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3249 | 3246 | code. |
|
3250 | 3247 | """ |
|
3251 | 3248 | # Regular expressions that declare text we strip from the input: |
|
3252 | 3249 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3253 | 3250 | r'^\s*(\s?>)+', # Python input prompt |
|
3254 | 3251 | r'^\s*\.{3,}', # Continuation prompts |
|
3255 | 3252 | r'^\++', |
|
3256 | 3253 | ] |
|
3257 | 3254 | |
|
3258 | 3255 | strip_from_start = map(re.compile,strip_re) |
|
3259 | 3256 | |
|
3260 | 3257 | lines = [] |
|
3261 | 3258 | for l in raw_lines: |
|
3262 | 3259 | for pat in strip_from_start: |
|
3263 | 3260 | l = pat.sub('',l) |
|
3264 | 3261 | lines.append(l) |
|
3265 | 3262 | |
|
3266 | 3263 | block = "\n".join(lines) + '\n' |
|
3267 | 3264 | #print "block:\n",block |
|
3268 | 3265 | return block |
|
3269 | 3266 | |
|
3270 | 3267 | def _execute_block(self, block, par): |
|
3271 | 3268 | """ Execute a block, or store it in a variable, per the user's request. |
|
3272 | 3269 | """ |
|
3273 | 3270 | if not par: |
|
3274 | 3271 | b = textwrap.dedent(block) |
|
3275 | 3272 | self.user_ns['pasted_block'] = b |
|
3276 | 3273 | exec b in self.user_ns |
|
3277 | 3274 | else: |
|
3278 | 3275 | self.user_ns[par] = SList(block.splitlines()) |
|
3279 | 3276 | print "Block assigned to '%s'" % par |
|
3280 | 3277 | |
|
3281 | 3278 | def magic_cpaste(self, parameter_s=''): |
|
3282 | 3279 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3283 | 3280 | |
|
3284 | 3281 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3285 | 3282 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3286 | 3283 | is the new sentinel for this operation) |
|
3287 | 3284 | |
|
3288 | 3285 | The block is dedented prior to execution to enable execution of method |
|
3289 | 3286 | definitions. '>' and '+' characters at the beginning of a line are |
|
3290 | 3287 | ignored, to allow pasting directly from e-mails, diff files and |
|
3291 | 3288 | doctests (the '...' continuation prompt is also stripped). The |
|
3292 | 3289 | executed block is also assigned to variable named 'pasted_block' for |
|
3293 | 3290 | later editing with '%edit pasted_block'. |
|
3294 | 3291 | |
|
3295 | 3292 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3296 | 3293 | This assigns the pasted block to variable 'foo' as string, without |
|
3297 | 3294 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3298 | 3295 | |
|
3299 | 3296 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
3300 | 3297 | |
|
3301 | 3298 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3302 | 3299 | Just press enter and type -- (and press enter again) and the block |
|
3303 | 3300 | will be what was just pasted. |
|
3304 | 3301 | |
|
3305 | 3302 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3306 | 3303 | |
|
3307 | 3304 | See also |
|
3308 | 3305 | -------- |
|
3309 | 3306 | paste: automatically pull code from clipboard. |
|
3310 | 3307 | """ |
|
3311 | 3308 | |
|
3312 | 3309 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
3313 | 3310 | par = args.strip() |
|
3314 | 3311 | if opts.has_key('r'): |
|
3315 | 3312 | self._rerun_pasted() |
|
3316 | 3313 | return |
|
3317 | 3314 | |
|
3318 | 3315 | sentinel = opts.get('s','--') |
|
3319 | 3316 | |
|
3320 | 3317 | block = self._strip_pasted_lines_for_code( |
|
3321 | 3318 | self._get_pasted_lines(sentinel)) |
|
3322 | 3319 | |
|
3323 | 3320 | self._execute_block(block, par) |
|
3324 | 3321 | |
|
3325 | 3322 | def magic_paste(self, parameter_s=''): |
|
3326 | 3323 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
3327 | 3324 | |
|
3328 | 3325 | The text is pulled directly from the clipboard without user |
|
3329 | 3326 | intervention and printed back on the screen before execution (unless |
|
3330 | 3327 | the -q flag is given to force quiet mode). |
|
3331 | 3328 | |
|
3332 | 3329 | The block is dedented prior to execution to enable execution of method |
|
3333 | 3330 | definitions. '>' and '+' characters at the beginning of a line are |
|
3334 | 3331 | ignored, to allow pasting directly from e-mails, diff files and |
|
3335 | 3332 | doctests (the '...' continuation prompt is also stripped). The |
|
3336 | 3333 | executed block is also assigned to variable named 'pasted_block' for |
|
3337 | 3334 | later editing with '%edit pasted_block'. |
|
3338 | 3335 | |
|
3339 | 3336 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
3340 | 3337 | This assigns the pasted block to variable 'foo' as string, without |
|
3341 | 3338 | dedenting or executing it (preceding >>> and + is still stripped) |
|
3342 | 3339 | |
|
3343 | 3340 | Options |
|
3344 | 3341 | ------- |
|
3345 | 3342 | |
|
3346 | 3343 | -r: re-executes the block previously entered by cpaste. |
|
3347 | 3344 | |
|
3348 | 3345 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
3349 | 3346 | |
|
3350 | 3347 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3351 | 3348 | |
|
3352 | 3349 | See also |
|
3353 | 3350 | -------- |
|
3354 | 3351 | cpaste: manually paste code into terminal until you mark its end. |
|
3355 | 3352 | """ |
|
3356 | 3353 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
3357 | 3354 | par = args.strip() |
|
3358 | 3355 | if opts.has_key('r'): |
|
3359 | 3356 | self._rerun_pasted() |
|
3360 | 3357 | return |
|
3361 | 3358 | |
|
3362 | 3359 | text = self.shell.hooks.clipboard_get() |
|
3363 | 3360 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
3364 | 3361 | |
|
3365 | 3362 | # By default, echo back to terminal unless quiet mode is requested |
|
3366 | 3363 | if not opts.has_key('q'): |
|
3367 | 3364 | write = self.shell.write |
|
3368 | write(block) | |
|
3365 | write(self.shell.pycolorize(block)) | |
|
3369 | 3366 | if not block.endswith('\n'): |
|
3370 | 3367 | write('\n') |
|
3371 | 3368 | write("## -- End pasted text --\n") |
|
3372 | 3369 | |
|
3373 | 3370 | self._execute_block(block, par) |
|
3374 | 3371 | |
|
3375 | 3372 | def magic_quickref(self,arg): |
|
3376 | 3373 | """ Show a quick reference sheet """ |
|
3377 | 3374 | import IPython.core.usage |
|
3378 | 3375 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3379 | 3376 | |
|
3380 | 3377 | page(qr) |
|
3381 | 3378 | |
|
3382 | def magic_upgrade(self,arg): | |
|
3383 | """ Upgrade your IPython installation | |
|
3384 | ||
|
3385 | This will copy the config files that don't yet exist in your | |
|
3386 | ipython dir from the system config dir. Use this after upgrading | |
|
3387 | IPython if you don't wish to delete your .ipython dir. | |
|
3388 | ||
|
3389 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
|
3390 | new users) | |
|
3391 | ||
|
3392 | """ | |
|
3393 | ip = self.getapi() | |
|
3394 | ipinstallation = path(IPython.__file__).dirname() | |
|
3395 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py') | |
|
3396 | src_config = ipinstallation / 'config' / 'userconfig' | |
|
3397 | userdir = path(ip.config.IPYTHONDIR) | |
|
3398 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
|
3399 | print ">",cmd | |
|
3400 | shell(cmd) | |
|
3401 | if arg == '-nolegacy': | |
|
3402 | legacy = userdir.files('ipythonrc*') | |
|
3403 | print "Nuking legacy files:",legacy | |
|
3404 | ||
|
3405 | [p.remove() for p in legacy] | |
|
3406 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
|
3407 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
|
3408 | ||
|
3409 | ||
|
3410 | 3379 | def magic_doctest_mode(self,parameter_s=''): |
|
3411 | 3380 | """Toggle doctest mode on and off. |
|
3412 | 3381 | |
|
3413 | 3382 | This mode allows you to toggle the prompt behavior between normal |
|
3414 | 3383 | IPython prompts and ones that are as similar to the default IPython |
|
3415 | 3384 | interpreter as possible. |
|
3416 | 3385 | |
|
3417 | 3386 | It also supports the pasting of code snippets that have leading '>>>' |
|
3418 | 3387 | and '...' prompts in them. This means that you can paste doctests from |
|
3419 | 3388 | files or docstrings (even if they have leading whitespace), and the |
|
3420 | 3389 | code will execute correctly. You can then use '%history -tn' to see |
|
3421 | 3390 | the translated history without line numbers; this will give you the |
|
3422 | 3391 | input after removal of all the leading prompts and whitespace, which |
|
3423 | 3392 | can be pasted back into an editor. |
|
3424 | 3393 | |
|
3425 | 3394 | With these features, you can switch into this mode easily whenever you |
|
3426 | 3395 | need to do testing and changes to doctests, without having to leave |
|
3427 | 3396 | your existing IPython session. |
|
3428 | 3397 | """ |
|
3429 | 3398 | |
|
3430 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
|
3431 | from IPython.extensions import InterpreterPasteInput as ipaste | |
|
3432 | 3399 | from IPython.utils.ipstruct import Struct |
|
3433 | 3400 | |
|
3434 | 3401 | # Shorthands |
|
3435 | 3402 | shell = self.shell |
|
3436 | 3403 | oc = shell.outputcache |
|
3437 | 3404 | meta = shell.meta |
|
3438 | 3405 | # dstore is a data store kept in the instance metadata bag to track any |
|
3439 | 3406 | # changes we make, so we can undo them later. |
|
3440 | 3407 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3441 | 3408 | save_dstore = dstore.setdefault |
|
3442 | 3409 | |
|
3443 | 3410 | # save a few values we'll need to recover later |
|
3444 | 3411 | mode = save_dstore('mode',False) |
|
3445 | 3412 | save_dstore('rc_pprint',shell.pprint) |
|
3446 | 3413 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3447 | 3414 | save_dstore('rc_separate_out',shell.separate_out) |
|
3448 | 3415 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3449 | 3416 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3450 | 3417 | save_dstore('rc_separate_in',shell.separate_in) |
|
3451 | 3418 | |
|
3452 | 3419 | if mode == False: |
|
3453 | 3420 | # turn on |
|
3454 | ipaste.activate_prefilter() | |
|
3455 | ||
|
3456 | 3421 | oc.prompt1.p_template = '>>> ' |
|
3457 | 3422 | oc.prompt2.p_template = '... ' |
|
3458 | 3423 | oc.prompt_out.p_template = '' |
|
3459 | 3424 | |
|
3460 | 3425 | # Prompt separators like plain python |
|
3461 | 3426 | oc.input_sep = oc.prompt1.sep = '' |
|
3462 | 3427 | oc.output_sep = '' |
|
3463 | 3428 | oc.output_sep2 = '' |
|
3464 | 3429 | |
|
3465 | 3430 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3466 | 3431 | oc.prompt_out.pad_left = False |
|
3467 | 3432 | |
|
3468 | 3433 | shell.pprint = False |
|
3469 | 3434 | |
|
3470 | 3435 | shell.magic_xmode('Plain') |
|
3471 | 3436 | |
|
3472 | 3437 | else: |
|
3473 | 3438 | # turn off |
|
3474 | ipaste.deactivate_prefilter() | |
|
3475 | ||
|
3476 | 3439 | oc.prompt1.p_template = shell.prompt_in1 |
|
3477 | 3440 | oc.prompt2.p_template = shell.prompt_in2 |
|
3478 | 3441 | oc.prompt_out.p_template = shell.prompt_out |
|
3479 | 3442 | |
|
3480 | 3443 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3481 | 3444 | |
|
3482 | 3445 | oc.output_sep = dstore.rc_separate_out |
|
3483 | 3446 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3484 | 3447 | |
|
3485 | 3448 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3486 | 3449 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3487 | 3450 | |
|
3488 |
|
|
|
3451 | shell.pprint = dstore.rc_pprint | |
|
3489 | 3452 | |
|
3490 | 3453 | shell.magic_xmode(dstore.xmode) |
|
3491 | 3454 | |
|
3492 | 3455 | # Store new mode and inform |
|
3493 | 3456 | dstore.mode = bool(1-int(mode)) |
|
3494 | 3457 | print 'Doctest mode is:', |
|
3495 | 3458 | print ['OFF','ON'][dstore.mode] |
|
3496 | 3459 | |
|
3497 | 3460 | def magic_gui(self, parameter_s=''): |
|
3498 | 3461 | """Enable or disable IPython GUI event loop integration. |
|
3499 | 3462 | |
|
3500 | 3463 | %gui [-a] [GUINAME] |
|
3501 | 3464 | |
|
3502 | 3465 | This magic replaces IPython's threaded shells that were activated |
|
3503 | 3466 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3504 | 3467 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3505 | 3468 | interrupts should work without any problems. The following toolkits |
|
3506 |
are support |
|
|
3469 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
|
3507 | 3470 | |
|
3508 | 3471 | %gui wx # enable wxPython event loop integration |
|
3509 | 3472 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3510 | 3473 | %gui gtk # enable PyGTK event loop integration |
|
3511 | 3474 | %gui tk # enable Tk event loop integration |
|
3512 | 3475 | %gui # disable all event loop integration |
|
3513 | 3476 | |
|
3514 | 3477 | WARNING: after any of these has been called you can simply create |
|
3515 | 3478 | an application object, but DO NOT start the event loop yourself, as |
|
3516 | 3479 | we have already handled that. |
|
3517 | 3480 | |
|
3518 | 3481 | If you want us to create an appropriate application object add the |
|
3519 | 3482 | "-a" flag to your command:: |
|
3520 | 3483 | |
|
3521 | 3484 | %gui -a wx |
|
3522 | 3485 | |
|
3523 | 3486 | This is highly recommended for most users. |
|
3524 | 3487 | """ |
|
3525 | from IPython.lib import inputhook | |
|
3526 | if "-a" in parameter_s: | |
|
3527 | app = True | |
|
3528 | else: | |
|
3529 | app = False | |
|
3530 | if not parameter_s: | |
|
3531 | inputhook.clear_inputhook() | |
|
3532 | elif 'wx' in parameter_s: | |
|
3533 | return inputhook.enable_wx(app) | |
|
3534 | elif ('qt4' in parameter_s) or ('qt' in parameter_s): | |
|
3535 | return inputhook.enable_qt4(app) | |
|
3536 | elif 'gtk' in parameter_s: | |
|
3537 | return inputhook.enable_gtk(app) | |
|
3538 | elif 'tk' in parameter_s: | |
|
3539 | return inputhook.enable_tk(app) | |
|
3488 | opts, arg = self.parse_options(parameter_s,'a') | |
|
3489 | if arg=='': arg = None | |
|
3490 | return enable_gui(arg, 'a' in opts) | |
|
3540 | 3491 | |
|
3541 | 3492 | def magic_load_ext(self, module_str): |
|
3542 | 3493 | """Load an IPython extension by its module name.""" |
|
3543 | self.load_extension(module_str) | |
|
3494 | return self.load_extension(module_str) | |
|
3544 | 3495 | |
|
3545 | 3496 | def magic_unload_ext(self, module_str): |
|
3546 | 3497 | """Unload an IPython extension by its module name.""" |
|
3547 | 3498 | self.unload_extension(module_str) |
|
3548 | 3499 | |
|
3549 | 3500 | def magic_reload_ext(self, module_str): |
|
3550 | 3501 | """Reload an IPython extension by its module name.""" |
|
3551 | 3502 | self.reload_extension(module_str) |
|
3552 | 3503 | |
|
3504 | @testdec.skip_doctest | |
|
3505 | def magic_install_profiles(self, s): | |
|
3506 | """Install the default IPython profiles into the .ipython dir. | |
|
3507 | ||
|
3508 | If the default profiles have already been installed, they will not | |
|
3509 | be overwritten. You can force overwriting them by using the ``-o`` | |
|
3510 | option:: | |
|
3511 | ||
|
3512 | In [1]: %install_profiles -o | |
|
3513 | """ | |
|
3514 | if '-o' in s: | |
|
3515 | overwrite = True | |
|
3516 | else: | |
|
3517 | overwrite = False | |
|
3518 | from IPython.config import profile | |
|
3519 | profile_dir = os.path.split(profile.__file__)[0] | |
|
3520 | ipython_dir = self.ipython_dir | |
|
3521 | files = os.listdir(profile_dir) | |
|
3522 | ||
|
3523 | to_install = [] | |
|
3524 | for f in files: | |
|
3525 | if f.startswith('ipython_config'): | |
|
3526 | src = os.path.join(profile_dir, f) | |
|
3527 | dst = os.path.join(ipython_dir, f) | |
|
3528 | if (not os.path.isfile(dst)) or overwrite: | |
|
3529 | to_install.append((f, src, dst)) | |
|
3530 | if len(to_install)>0: | |
|
3531 | print "Installing profiles to: ", ipython_dir | |
|
3532 | for (f, src, dst) in to_install: | |
|
3533 | shutil.copy(src, dst) | |
|
3534 | print " %s" % f | |
|
3535 | ||
|
3536 | def magic_install_default_config(self, s): | |
|
3537 | """Install IPython's default config file into the .ipython dir. | |
|
3538 | ||
|
3539 | If the default config file (:file:`ipython_config.py`) is already | |
|
3540 | installed, it will not be overwritten. You can force overwriting | |
|
3541 | by using the ``-o`` option:: | |
|
3542 | ||
|
3543 | In [1]: %install_default_config | |
|
3544 | """ | |
|
3545 | if '-o' in s: | |
|
3546 | overwrite = True | |
|
3547 | else: | |
|
3548 | overwrite = False | |
|
3549 | from IPython.config import default | |
|
3550 | config_dir = os.path.split(default.__file__)[0] | |
|
3551 | ipython_dir = self.ipython_dir | |
|
3552 | default_config_file_name = 'ipython_config.py' | |
|
3553 | src = os.path.join(config_dir, default_config_file_name) | |
|
3554 | dst = os.path.join(ipython_dir, default_config_file_name) | |
|
3555 | if (not os.path.isfile(dst)) or overwrite: | |
|
3556 | shutil.copy(src, dst) | |
|
3557 | print "Installing default config file: %s" % dst | |
|
3558 | ||
|
3559 | # Pylab support: simple wrappers that activate pylab, load gui input | |
|
3560 | # handling and modify slightly %run | |
|
3561 | ||
|
3562 | @testdec.skip_doctest | |
|
3563 | def _pylab_magic_run(self, parameter_s=''): | |
|
3564 | Magic.magic_run(self, parameter_s, | |
|
3565 | runner=mpl_runner(self.shell.safe_execfile)) | |
|
3566 | ||
|
3567 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
|
3568 | ||
|
3569 | @testdec.skip_doctest | |
|
3570 | def magic_pylab(self, s): | |
|
3571 | """Load numpy and matplotlib to work interactively. | |
|
3572 | ||
|
3573 | %pylab [GUINAME] | |
|
3574 | ||
|
3575 | This function lets you activate pylab (matplotlib, numpy and | |
|
3576 | interactive support) at any point during an IPython session. | |
|
3577 | ||
|
3578 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
|
3579 | pylab and mlab, as well as all names from numpy and pylab. | |
|
3580 | ||
|
3581 | Parameters | |
|
3582 | ---------- | |
|
3583 | guiname : optional | |
|
3584 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
|
3585 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
|
3586 | otherwise matplotlib's default (which you can override in your | |
|
3587 | matplotlib config file) is used. | |
|
3588 | ||
|
3589 | Examples | |
|
3590 | -------- | |
|
3591 | In this case, where the MPL default is TkAgg: | |
|
3592 | In [2]: %pylab | |
|
3593 | ||
|
3594 | Welcome to pylab, a matplotlib-based Python environment. | |
|
3595 | Backend in use: TkAgg | |
|
3596 | For more information, type 'help(pylab)'. | |
|
3597 | ||
|
3598 | But you can explicitly request a different backend: | |
|
3599 | In [3]: %pylab qt | |
|
3600 | ||
|
3601 | Welcome to pylab, a matplotlib-based Python environment. | |
|
3602 | Backend in use: Qt4Agg | |
|
3603 | For more information, type 'help(pylab)'. | |
|
3604 | """ | |
|
3605 | self.shell.enable_pylab(s) | |
|
3606 | ||
|
3607 | def magic_tb(self, s): | |
|
3608 | """Print the last traceback with the currently active exception mode. | |
|
3609 | ||
|
3610 | See %xmode for changing exception reporting modes.""" | |
|
3611 | self.shell.showtraceback() | |
|
3612 | ||
|
3553 | 3613 | # end Magic |
|
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