Show More
The requested changes are too big and content was truncated. Show full diff
@@ -0,0 +1,155 b'' | |||
|
1 | # encoding: utf-8 | |
|
2 | ||
|
3 | """This file contains unittests for the frontendbase module.""" | |
|
4 | ||
|
5 | __docformat__ = "restructuredtext en" | |
|
6 | ||
|
7 | #--------------------------------------------------------------------------- | |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
|
9 | # | |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
|
11 | # the file COPYING, distributed as part of this software. | |
|
12 | #--------------------------------------------------------------------------- | |
|
13 | ||
|
14 | #--------------------------------------------------------------------------- | |
|
15 | # Imports | |
|
16 | #--------------------------------------------------------------------------- | |
|
17 | ||
|
18 | import unittest | |
|
19 | ||
|
20 | try: | |
|
21 | from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase | |
|
22 | from IPython.frontend import frontendbase | |
|
23 | from IPython.kernel.engineservice import EngineService | |
|
24 | except ImportError: | |
|
25 | import nose | |
|
26 | raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap") | |
|
27 | ||
|
28 | from IPython.testing.decorators import skip | |
|
29 | ||
|
30 | class FrontEndCallbackChecker(AsyncFrontEndBase): | |
|
31 | """FrontEndBase subclass for checking callbacks""" | |
|
32 | def __init__(self, engine=None, history=None): | |
|
33 | super(FrontEndCallbackChecker, self).__init__(engine=engine, | |
|
34 | history=history) | |
|
35 | self.updateCalled = False | |
|
36 | self.renderResultCalled = False | |
|
37 | self.renderErrorCalled = False | |
|
38 | ||
|
39 | def update_cell_prompt(self, result, blockID=None): | |
|
40 | self.updateCalled = True | |
|
41 | return result | |
|
42 | ||
|
43 | def render_result(self, result): | |
|
44 | self.renderResultCalled = True | |
|
45 | return result | |
|
46 | ||
|
47 | ||
|
48 | def render_error(self, failure): | |
|
49 | self.renderErrorCalled = True | |
|
50 | return failure | |
|
51 | ||
|
52 | ||
|
53 | ||
|
54 | ||
|
55 | class TestAsyncFrontendBase(unittest.TestCase): | |
|
56 | def setUp(self): | |
|
57 | """Setup the EngineService and FrontEndBase""" | |
|
58 | ||
|
59 | self.fb = FrontEndCallbackChecker(engine=EngineService()) | |
|
60 | ||
|
61 | def test_implements_IFrontEnd(self): | |
|
62 | assert(frontendbase.IFrontEnd.implementedBy( | |
|
63 | AsyncFrontEndBase)) | |
|
64 | ||
|
65 | def test_is_complete_returns_False_for_incomplete_block(self): | |
|
66 | """""" | |
|
67 | ||
|
68 | block = """def test(a):""" | |
|
69 | ||
|
70 | assert(self.fb.is_complete(block) == False) | |
|
71 | ||
|
72 | def test_is_complete_returns_True_for_complete_block(self): | |
|
73 | """""" | |
|
74 | ||
|
75 | block = """def test(a): pass""" | |
|
76 | ||
|
77 | assert(self.fb.is_complete(block)) | |
|
78 | ||
|
79 | block = """a=3""" | |
|
80 | ||
|
81 | assert(self.fb.is_complete(block)) | |
|
82 | ||
|
83 | def test_blockID_added_to_result(self): | |
|
84 | block = """3+3""" | |
|
85 | ||
|
86 | d = self.fb.execute(block, blockID='TEST_ID') | |
|
87 | ||
|
88 | d.addCallback(self.checkBlockID, expected='TEST_ID') | |
|
89 | ||
|
90 | def test_blockID_added_to_failure(self): | |
|
91 | block = "raise Exception()" | |
|
92 | ||
|
93 | d = self.fb.execute(block,blockID='TEST_ID') | |
|
94 | d.addErrback(self.checkFailureID, expected='TEST_ID') | |
|
95 | ||
|
96 | def checkBlockID(self, result, expected=""): | |
|
97 | assert(result['blockID'] == expected) | |
|
98 | ||
|
99 | ||
|
100 | def checkFailureID(self, failure, expected=""): | |
|
101 | assert(failure.blockID == expected) | |
|
102 | ||
|
103 | ||
|
104 | def test_callbacks_added_to_execute(self): | |
|
105 | """test that | |
|
106 | update_cell_prompt | |
|
107 | render_result | |
|
108 | ||
|
109 | are added to execute request | |
|
110 | """ | |
|
111 | ||
|
112 | d = self.fb.execute("10+10") | |
|
113 | d.addCallback(self.checkCallbacks) | |
|
114 | ||
|
115 | def checkCallbacks(self, result): | |
|
116 | assert(self.fb.updateCalled) | |
|
117 | assert(self.fb.renderResultCalled) | |
|
118 | ||
|
119 | @skip("This test fails and lead to an unhandled error in a Deferred.") | |
|
120 | def test_error_callback_added_to_execute(self): | |
|
121 | """test that render_error called on execution error""" | |
|
122 | ||
|
123 | d = self.fb.execute("raise Exception()") | |
|
124 | d.addCallback(self.checkRenderError) | |
|
125 | ||
|
126 | def checkRenderError(self, result): | |
|
127 | assert(self.fb.renderErrorCalled) | |
|
128 | ||
|
129 | def test_history_returns_expected_block(self): | |
|
130 | """Make sure history browsing doesn't fail""" | |
|
131 | ||
|
132 | blocks = ["a=1","a=2","a=3"] | |
|
133 | for b in blocks: | |
|
134 | d = self.fb.execute(b) | |
|
135 | ||
|
136 | # d is now the deferred for the last executed block | |
|
137 | d.addCallback(self.historyTests, blocks) | |
|
138 | ||
|
139 | ||
|
140 | def historyTests(self, result, blocks): | |
|
141 | """historyTests""" | |
|
142 | ||
|
143 | assert(len(blocks) >= 3) | |
|
144 | assert(self.fb.get_history_previous("") == blocks[-2]) | |
|
145 | assert(self.fb.get_history_previous("") == blocks[-3]) | |
|
146 | assert(self.fb.get_history_next() == blocks[-2]) | |
|
147 | ||
|
148 | ||
|
149 | def test_history_returns_none_at_startup(self): | |
|
150 | """test_history_returns_none_at_startup""" | |
|
151 | ||
|
152 | assert(self.fb.get_history_previous("")==None) | |
|
153 | assert(self.fb.get_history_next()==None) | |
|
154 | ||
|
155 |
@@ -0,0 +1,240 b'' | |||
|
1 | .. _paralleltask: | |
|
2 | ||
|
3 | ========================== | |
|
4 | The IPython task interface | |
|
5 | ========================== | |
|
6 | ||
|
7 | .. contents:: | |
|
8 | ||
|
9 | The ``Task`` interface to the controller presents the engines as a fault tolerant, dynamic load-balanced system or workers. Unlike the ``MultiEngine`` interface, in the ``Task`` interface, the user have no direct access to individual engines. In some ways, this interface is simpler, but in other ways it is more powerful. Best of all the user can use both of these interfaces at the same time to take advantage or both of their strengths. When the user can break up the user's work into segments that do not depend on previous execution, the ``Task`` interface is ideal. But it also has more power and flexibility, allowing the user to guide the distribution of jobs, without having to assign Tasks to engines explicitly. | |
|
10 | ||
|
11 | Starting the IPython controller and engines | |
|
12 | =========================================== | |
|
13 | ||
|
14 | To follow along with this tutorial, the user will need to start the IPython | |
|
15 | controller and four IPython engines. The simplest way of doing this is to | |
|
16 | use the ``ipcluster`` command:: | |
|
17 | ||
|
18 | $ ipcluster -n 4 | |
|
19 | ||
|
20 | For more detailed information about starting the controller and engines, see our :ref:`introduction <ip1par>` to using IPython for parallel computing. | |
|
21 | ||
|
22 | The magic here is that this single controller and set of engines is running both the MultiEngine and ``Task`` interfaces simultaneously. | |
|
23 | ||
|
24 | QuickStart Task Farming | |
|
25 | ======================= | |
|
26 | ||
|
27 | First, a quick example of how to start running the most basic Tasks. | |
|
28 | The first step is to import the IPython ``client`` module and then create a ``TaskClient`` instance:: | |
|
29 | ||
|
30 | In [1]: from IPython.kernel import client | |
|
31 | ||
|
32 | In [2]: tc = client.TaskClient() | |
|
33 | ||
|
34 | Then the user wrap the commands the user want to run in Tasks:: | |
|
35 | ||
|
36 | In [3]: tasklist = [] | |
|
37 | In [4]: for n in range(1000): | |
|
38 | ... tasklist.append(client.Task("a = %i"%n, pull="a")) | |
|
39 | ||
|
40 | The first argument of the ``Task`` constructor is a string, the command to be executed. The most important optional keyword argument is ``pull``, which can be a string or list of strings, and it specifies the variable names to be saved as results of the ``Task``. | |
|
41 | ||
|
42 | Next, the user need to submit the Tasks to the ``TaskController`` with the ``TaskClient``:: | |
|
43 | ||
|
44 | In [5]: taskids = [ tc.run(t) for t in tasklist ] | |
|
45 | ||
|
46 | This will give the user a list of the TaskIDs used by the controller to keep track of the Tasks and their results. Now at some point the user are going to want to get those results back. The ``barrier`` method allows the user to wait for the Tasks to finish running:: | |
|
47 | ||
|
48 | In [6]: tc.barrier(taskids) | |
|
49 | ||
|
50 | This command will block until all the Tasks in ``taskids`` have finished. Now, the user probably want to look at the user's results:: | |
|
51 | ||
|
52 | In [7]: task_results = [ tc.get_task_result(taskid) for taskid in taskids ] | |
|
53 | ||
|
54 | Now the user have a list of ``TaskResult`` objects, which have the actual result as a dictionary, but also keep track of some useful metadata about the ``Task``:: | |
|
55 | ||
|
56 | In [8]: tr = ``Task``_results[73] | |
|
57 | ||
|
58 | In [9]: tr | |
|
59 | Out[9]: ``TaskResult``[ID:73]:{'a':73} | |
|
60 | ||
|
61 | In [10]: tr.engineid | |
|
62 | Out[10]: 1 | |
|
63 | ||
|
64 | In [11]: tr.submitted, tr.completed, tr.duration | |
|
65 | Out[11]: ("2008/03/08 03:41:42", "2008/03/08 03:41:44", 2.12345) | |
|
66 | ||
|
67 | The actual results are stored in a dictionary, ``tr.results``, and a namespace object ``tr.ns`` which accesses the result keys by attribute:: | |
|
68 | ||
|
69 | In [12]: tr.results['a'] | |
|
70 | Out[12]: 73 | |
|
71 | ||
|
72 | In [13]: tr.ns.a | |
|
73 | Out[13]: 73 | |
|
74 | ||
|
75 | That should cover the basics of running simple Tasks. There are several more powerful things the user can do with Tasks covered later. The most useful probably being using a ``MutiEngineClient`` interface to initialize all the engines with the import dependencies necessary to run the user's Tasks. | |
|
76 | ||
|
77 | There are many options for running and managing Tasks. The best way to learn further about the ``Task`` interface is to study the examples in ``docs/examples``. If the user do so and learn a lots about this interface, we encourage the user to expand this documentation about the ``Task`` system. | |
|
78 | ||
|
79 | Overview of the Task System | |
|
80 | =========================== | |
|
81 | ||
|
82 | The user's view of the ``Task`` system has three basic objects: The ``TaskClient``, the ``Task``, and the ``TaskResult``. The names of these three objects well indicate their role. | |
|
83 | ||
|
84 | The ``TaskClient`` is the user's ``Task`` farming connection to the IPython cluster. Unlike the ``MultiEngineClient``, the ``TaskControler`` handles all the scheduling and distribution of work, so the ``TaskClient`` has no notion of engines, it just submits Tasks and requests their results. The Tasks are described as ``Task`` objects, and their results are wrapped in ``TaskResult`` objects. Thus, there are very few necessary methods for the user to manage. | |
|
85 | ||
|
86 | Inside the task system is a Scheduler object, which assigns tasks to workers. The default scheduler is a simple FIFO queue. Subclassing the Scheduler should be easy, just implementing your own priority system. | |
|
87 | ||
|
88 | The TaskClient | |
|
89 | ============== | |
|
90 | ||
|
91 | The ``TaskClient`` is the object the user use to connect to the ``Controller`` that is managing the user's Tasks. It is the analog of the ``MultiEngineClient`` for the standard IPython multiplexing interface. As with all client interfaces, the first step is to import the IPython Client Module:: | |
|
92 | ||
|
93 | In [1]: from IPython.kernel import client | |
|
94 | ||
|
95 | Just as with the ``MultiEngineClient``, the user create the ``TaskClient`` with a tuple, containing the ip-address and port of the ``Controller``. the ``client`` module conveniently has the default address of the ``Task`` interface of the controller. Creating a default ``TaskClient`` object would be done with this:: | |
|
96 | ||
|
97 | In [2]: tc = client.TaskClient(client.default_task_address) | |
|
98 | ||
|
99 | or, if the user want to specify a non default location of the ``Controller``, the user can specify explicitly:: | |
|
100 | ||
|
101 | In [3]: tc = client.TaskClient(("192.168.1.1", 10113)) | |
|
102 | ||
|
103 | As discussed earlier, the ``TaskClient`` only has a few basic methods. | |
|
104 | ||
|
105 | * ``tc.run(task)`` | |
|
106 | ``run`` is the method by which the user submits Tasks. It takes exactly one argument, a ``Task`` object. All the advanced control of ``Task`` behavior is handled by properties of the ``Task`` object, rather than the submission command, so they will be discussed later in the `Task`_ section. ``run`` returns an integer, the ``Task``ID by which the ``Task`` and its results can be tracked and retrieved:: | |
|
107 | ||
|
108 | In [4]: ``Task``ID = tc.run(``Task``) | |
|
109 | ||
|
110 | * ``tc.get_task_result(taskid, block=``False``)`` | |
|
111 | ``get_task_result`` is the method by which results are retrieved. It takes a single integer argument, the ``Task``ID`` of the result the user wish to retrieve. ``get_task_result`` also takes a keyword argument ``block``. ``block`` specifies whether the user actually want to wait for the result. If ``block`` is false, as it is by default, ``get_task_result`` will return immediately. If the ``Task`` has completed, it will return the ``TaskResult`` object for that ``Task``. But if the ``Task`` has not completed, it will return ``None``. If the user specify ``block=``True``, then ``get_task_result`` will wait for the ``Task`` to complete, and always return the ``TaskResult`` for the requested ``Task``. | |
|
112 | * ``tc.barrier(taskid(s))`` | |
|
113 | ``barrier`` is a synchronization method. It takes exactly one argument, a ``Task``ID or list of taskIDs. ``barrier`` will block until all the specified Tasks have completed. In practice, a barrier is often called between the ``Task`` submission section of the code and the result gathering section:: | |
|
114 | ||
|
115 | In [5]: taskIDs = [ tc.run(``Task``) for ``Task`` in myTasks ] | |
|
116 | ||
|
117 | In [6]: tc.get_task_result(taskIDs[-1]) is None | |
|
118 | Out[6]: ``True`` | |
|
119 | ||
|
120 | In [7]: tc.barrier(``Task``ID) | |
|
121 | ||
|
122 | In [8]: results = [ tc.get_task_result(tid) for tid in taskIDs ] | |
|
123 | ||
|
124 | * ``tc.queue_status(verbose=``False``)`` | |
|
125 | ``queue_status`` is a method for querying the state of the ``TaskControler``. ``queue_status`` returns a dict of the form:: | |
|
126 | ||
|
127 | {'scheduled': Tasks that have been submitted but yet run | |
|
128 | 'pending' : Tasks that are currently running | |
|
129 | 'succeeded': Tasks that have completed successfully | |
|
130 | 'failed' : Tasks that have finished with a failure | |
|
131 | } | |
|
132 | ||
|
133 | if @verbose is not specified (or is ``False``), then the values of the dict are integers - the number of Tasks in each state. if @verbose is ``True``, then each element in the dict is a list of the taskIDs in that state:: | |
|
134 | ||
|
135 | In [8]: tc.queue_status() | |
|
136 | Out[8]: {'scheduled': 4, | |
|
137 | 'pending' : 2, | |
|
138 | 'succeeded': 5, | |
|
139 | 'failed' : 1 | |
|
140 | } | |
|
141 | ||
|
142 | In [9]: tc.queue_status(verbose=True) | |
|
143 | Out[9]: {'scheduled': [8,9,10,11], | |
|
144 | 'pending' : [6,7], | |
|
145 | 'succeeded': [0,1,2,4,5], | |
|
146 | 'failed' : [3] | |
|
147 | } | |
|
148 | ||
|
149 | * ``tc.abort(taskid)`` | |
|
150 | ``abort`` allows the user to abort Tasks that have already been submitted. ``abort`` will always return immediately. If the ``Task`` has completed, ``abort`` will raise an ``IndexError ``Task`` Already Completed``. An obvious case for ``abort`` would be where the user submits a long-running ``Task`` with a number of retries (see ``Task``_ section for how to specify retries) in an interactive session, but realizes there has been a typo. The user can then abort the ``Task``, preventing certain failures from cluttering up the queue. It can also be used for parallel search-type problems, where only one ``Task`` will give the solution, so once the user find the solution, the user would want to abort all remaining Tasks to prevent wasted work. | |
|
151 | * ``tc.spin()`` | |
|
152 | ``spin`` simply triggers the scheduler in the ``TaskControler``. Under most normal circumstances, this will do nothing. The primary known usage case involves the ``Task`` dependency (see `Dependencies`_). The dependency is a function of an Engine's ``properties``, but changing the ``properties`` via the ``MutliEngineClient`` does not trigger a reschedule event. The main example case for this requires the following event sequence: | |
|
153 | * ``engine`` is available, ``Task`` is submitted, but ``engine`` does not have ``Task``'s dependencies. | |
|
154 | * ``engine`` gets necessary dependencies while no new Tasks are submitted or completed. | |
|
155 | * now ``engine`` can run ``Task``, but a ``Task`` event is required for the ``TaskControler`` to try scheduling ``Task`` again. | |
|
156 | ||
|
157 | ``spin`` is just an empty ping method to ensure that the Controller has scheduled all available Tasks, and should not be needed under most normal circumstances. | |
|
158 | ||
|
159 | That covers the ``TaskClient``, a simple interface to the cluster. With this, the user can submit jobs (and abort if necessary), request their results, synchronize on arbitrary subsets of jobs. | |
|
160 | ||
|
161 | .. _task: The Task Object | |
|
162 | ||
|
163 | The Task Object | |
|
164 | =============== | |
|
165 | ||
|
166 | The ``Task`` is the basic object for describing a job. It can be used in a very simple manner, where the user just specifies a command string to be executed as the ``Task``. The usage of this first argument is exactly the same as the ``execute`` method of the ``MultiEngine`` (in fact, ``execute`` is called to run the code):: | |
|
167 | ||
|
168 | In [1]: t = client.Task("a = str(id)") | |
|
169 | ||
|
170 | This ``Task`` would run, and store the string representation of the ``id`` element in ``a`` in each worker's namespace, but it is fairly useless because the user does not know anything about the state of the ``worker`` on which it ran at the time of retrieving results. It is important that each ``Task`` not expect the state of the ``worker`` to persist after the ``Task`` is completed. | |
|
171 | There are many different situations for using ``Task`` Farming, and the ``Task`` object has many attributes for use in customizing the ``Task`` behavior. All of a ``Task``'s attributes may be specified in the constructor, through keyword arguments, or after ``Task`` construction through attribute assignment. | |
|
172 | ||
|
173 | Data Attributes | |
|
174 | *************** | |
|
175 | It is likely that the user may want to move data around before or after executing the ``Task``. We provide methods of sending data to initialize the worker's namespace, and specifying what data to bring back as the ``Task``'s results. | |
|
176 | ||
|
177 | * pull = [] | |
|
178 | The obvious case is as above, where ``t`` would execute and store the result of ``myfunc`` in ``a``, it is likely that the user would want to bring ``a`` back to their namespace. This is done through the ``pull`` attribute. ``pull`` can be a string or list of strings, and it specifies the names of variables to be retrieved. The ``TaskResult`` object retrieved by ``get_task_result`` will have a dictionary of keys and values, and the ``Task``'s ``pull`` attribute determines what goes into it:: | |
|
179 | ||
|
180 | In [2]: t = client.Task("a = str(id)", pull = "a") | |
|
181 | ||
|
182 | In [3]: t = client.Task("a = str(id)", pull = ["a", "id"]) | |
|
183 | ||
|
184 | * push = {} | |
|
185 | A user might also want to initialize some data into the namespace before the code part of the ``Task`` is run. Enter ``push``. ``push`` is a dictionary of key/value pairs to be loaded from the user's namespace into the worker's immediately before execution:: | |
|
186 | ||
|
187 | In [4]: t = client.Task("a = f(submitted)", push=dict(submitted=time.time()), pull="a") | |
|
188 | ||
|
189 | push and pull result directly in calling an ``engine``'s ``push`` and ``pull`` methods before and after ``Task`` execution respectively, and thus their api is the same. | |
|
190 | ||
|
191 | Namespace Cleaning | |
|
192 | ****************** | |
|
193 | When a user is running a large number of Tasks, it is likely that the namespace of the worker's could become cluttered. Some Tasks might be sensitive to clutter, while others might be known to cause namespace pollution. For these reasons, Tasks have two boolean attributes for cleaning up the namespace. | |
|
194 | ||
|
195 | * ``clear_after`` | |
|
196 | if clear_after is specified ``True``, the worker on which the ``Task`` was run will be reset (via ``engine.reset``) upon completion of the ``Task``. This can be useful for both Tasks that produce clutter or Tasks whose intermediate data one might wish to be kept private:: | |
|
197 | ||
|
198 | In [5]: t = client.Task("a = range(1e10)", pull = "a",clear_after=True) | |
|
199 | ||
|
200 | ||
|
201 | * ``clear_before`` | |
|
202 | as one might guess, clear_before is identical to ``clear_after``, but it takes place before the ``Task`` is run. This ensures that the ``Task`` runs on a fresh worker:: | |
|
203 | ||
|
204 | In [6]: t = client.Task("a = globals()", pull = "a",clear_before=True) | |
|
205 | ||
|
206 | Of course, a user can both at the same time, ensuring that all workers are clear except when they are currently running a job. Both of these default to ``False``. | |
|
207 | ||
|
208 | Fault Tolerance | |
|
209 | *************** | |
|
210 | It is possible that Tasks might fail, and there are a variety of reasons this could happen. One might be that the worker it was running on disconnected, and there was nothing wrong with the ``Task`` itself. With the fault tolerance attributes of the ``Task``, the user can specify how many times to resubmit the ``Task``, and what to do if it never succeeds. | |
|
211 | ||
|
212 | * ``retries`` | |
|
213 | ``retries`` is an integer, specifying the number of times a ``Task`` is to be retried. It defaults to zero. It is often a good idea for this number to be 1 or 2, to protect the ``Task`` from disconnecting engines, but not a large number. If a ``Task`` is failing 100 times, there is probably something wrong with the ``Task``. The canonical bad example: | |
|
214 | ||
|
215 | In [7]: t = client.Task("os.kill(os.getpid(), 9)", retries=99) | |
|
216 | ||
|
217 | This would actually take down 100 workers. | |
|
218 | ||
|
219 | * ``recovery_task`` | |
|
220 | ``recovery_task`` is another ``Task`` object, to be run in the event of the original ``Task`` still failing after running out of retries. Since ``recovery_task`` is another ``Task`` object, it can have its own ``recovery_task``. The chain of Tasks is limitless, except loops are not allowed (that would be bad!). | |
|
221 | ||
|
222 | Dependencies | |
|
223 | ************ | |
|
224 | Dependencies are the most powerful part of the ``Task`` farming system, because it allows the user to do some classification of the workers, and guide the ``Task`` distribution without meddling with the controller directly. It makes use of two objects - the ``Task``'s ``depend`` attribute, and the engine's ``properties``. See the `MultiEngine`_ reference for how to use engine properties. The engine properties api exists for extending IPython, allowing conditional execution and new controllers that make decisions based on properties of its engines. Currently the ``Task`` dependency is the only internal use of the properties api. | |
|
225 | ||
|
226 | .. _MultiEngine: ./parallel_multiengine | |
|
227 | ||
|
228 | The ``depend`` attribute of a ``Task`` must be a function of exactly one argument, the worker's properties dictionary, and it should return ``True`` if the ``Task`` should be allowed to run on the worker and ``False`` if not. The usage in the controller is fault tolerant, so exceptions raised by ``Task.depend`` will be ignored and functionally equivalent to always returning ``False``. Tasks`` with invalid ``depend`` functions will never be assigned to a worker:: | |
|
229 | ||
|
230 | In [8]: def dep(properties): | |
|
231 | ... return properties["RAM"] > 2**32 # have at least 4GB | |
|
232 | In [9]: t = client.Task("a = bigfunc()", depend=dep) | |
|
233 | ||
|
234 | It is important to note that assignment of values to the properties dict is done entirely by the user, either locally (in the engine) using the EngineAPI, or remotely, through the ``MultiEngineClient``'s get/set_properties methods. | |
|
235 | ||
|
236 | ||
|
237 | ||
|
238 | ||
|
239 | ||
|
240 |
@@ -0,0 +1,191 b'' | |||
|
1 | Overview | |
|
2 | ======== | |
|
3 | ||
|
4 | This document describes the steps required to install IPython. IPython is organized into a number of subpackages, each of which has its own dependencies. All of the subpackages come with IPython, so you don't need to download and install them separately. However, to use a given subpackage, you will need to install all of its dependencies. | |
|
5 | ||
|
6 | ||
|
7 | Please let us know if you have problems installing IPython or any of its | |
|
8 | dependencies. IPython requires Python version 2.4 or greater. We have not tested | |
|
9 | IPython with the upcoming 2.6 or 3.0 versions. | |
|
10 | ||
|
11 | .. warning:: | |
|
12 | ||
|
13 | IPython will not work with Python 2.3 or below. | |
|
14 | ||
|
15 | Some of the installation approaches use the :mod:`setuptools` package and its :command:`easy_install` command line program. In many scenarios, this provides the most simple method of installing IPython and its dependencies. It is not required though. More information about :mod:`setuptools` can be found on its website. | |
|
16 | ||
|
17 | More general information about installing Python packages can be found in Python's documentation at http://www.python.org/doc/. | |
|
18 | ||
|
19 | Installing IPython itself | |
|
20 | ========================= | |
|
21 | ||
|
22 | Given a properly built Python, the basic interactive IPython shell will work with no external dependencies. However, some Python distributions (particularly on Windows and OS X), don't come with a working :mod:`readline` module. The IPython shell will work without :mod:`readline`, but will lack many features that users depend on, such as tab completion and command line editing. See below for details of how to make sure you have a working :mod:`readline`. | |
|
23 | ||
|
24 | Installation using easy_install | |
|
25 | ------------------------------- | |
|
26 | ||
|
27 | If you have :mod:`setuptools` installed, the easiest way of getting IPython is to simple use :command:`easy_install`:: | |
|
28 | ||
|
29 | $ easy_install IPython | |
|
30 | ||
|
31 | That's it. | |
|
32 | ||
|
33 | Installation from source | |
|
34 | ------------------------ | |
|
35 | ||
|
36 | If you don't want to use :command:`easy_install`, or don't have it installed, just grab the latest stable build of IPython from `here <http://ipython.scipy.org/dist/>`_. Then do the following:: | |
|
37 | ||
|
38 | $ tar -xzf ipython.tar.gz | |
|
39 | $ cd ipython | |
|
40 | $ python setup.py install | |
|
41 | ||
|
42 | If you are installing to a location (like ``/usr/local``) that requires higher permissions, you may need to run the last command with :command:`sudo`. | |
|
43 | ||
|
44 | Windows | |
|
45 | ------- | |
|
46 | ||
|
47 | There are a few caveats for Windows users. The main issue is that a basic ``python setup.py install`` approach won't create ``.bat`` file or Start Menu shortcuts, which most users want. To get an installation with these, there are two choices: | |
|
48 | ||
|
49 | 1. Install using :command:`easy_install`. | |
|
50 | ||
|
51 | 2. Install using our binary ``.exe`` Windows installer, which can be found at `here <http://ipython.scipy.org/dist/>`_ | |
|
52 | ||
|
53 | 3. Install from source, but using :mod:`setuptools` (``python setupegg.py install``). | |
|
54 | ||
|
55 | Installing the development version | |
|
56 | ---------------------------------- | |
|
57 | ||
|
58 | It is also possible to install the development version of IPython from our `Bazaar <http://bazaar-vcs.org/>`_ source code | |
|
59 | repository. To do this you will need to have Bazaar installed on your system. Then just do:: | |
|
60 | ||
|
61 | $ bzr branch lp:ipython | |
|
62 | $ cd ipython | |
|
63 | $ python setup.py install | |
|
64 | ||
|
65 | Again, this last step on Windows won't create ``.bat`` files or Start Menu shortcuts, so you will have to use one of the other approaches listed above. | |
|
66 | ||
|
67 | Some users want to be able to follow the development branch as it changes. If you have :mod:`setuptools` installed, this is easy. Simply replace the last step by:: | |
|
68 | ||
|
69 | $ python setupegg.py develop | |
|
70 | ||
|
71 | This creates links in the right places and installs the command line script to the appropriate places. Then, if you want to update your IPython at any time, just do:: | |
|
72 | ||
|
73 | $ bzr pull | |
|
74 | ||
|
75 | Basic optional dependencies | |
|
76 | =========================== | |
|
77 | ||
|
78 | There are a number of basic optional dependencies that most users will want to get. These are: | |
|
79 | ||
|
80 | * readline (for command line editing, tab completion, etc.) | |
|
81 | * nose (to run the IPython test suite) | |
|
82 | * pexpect (to use things like irunner) | |
|
83 | ||
|
84 | If you are comfortable installing these things yourself, have at it, otherwise read on for more details. | |
|
85 | ||
|
86 | readline | |
|
87 | -------- | |
|
88 | ||
|
89 | In principle, all Python distributions should come with a working :mod:`readline` module. But, reality is not quite that simple. There are two common situations where you won't have a working :mod:`readline` module: | |
|
90 | ||
|
91 | * If you are using the built-in Python on Mac OS X. | |
|
92 | ||
|
93 | * If you are running Windows, which doesn't have a :mod:`readline` module. | |
|
94 | ||
|
95 | On OS X, the built-in Python doesn't not have :mod:`readline` because of license issues. Starting with OS X 10.5 (Leopard), Apple's built-in Python has a BSD-licensed not-quite-compatible readline replacement. As of IPython 0.9, many of the issues related to the differences between readline and libedit have been resolved. For many users, libedit may be sufficient. | |
|
96 | ||
|
97 | Most users on OS X will want to get the full :mod:`readline` module. To get a working :mod:`readline` module, just do (with :mod:`setuptools` installed):: | |
|
98 | ||
|
99 | $ easy_install readline | |
|
100 | ||
|
101 | .. note: | |
|
102 | ||
|
103 | Other Python distributions on OS X (such as fink, MacPorts and the | |
|
104 | official python.org binaries) already have readline installed so | |
|
105 | you don't have to do this step. | |
|
106 | ||
|
107 | If needed, the readline egg can be build and installed from source (see the wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard). | |
|
108 | ||
|
109 | On Windows, you will need the PyReadline module. PyReadline is a separate, Windows only implementation of readline that uses native Windows calls through :mod:`ctypes`. The easiest way of installing PyReadline is you use the binary installer available `here <http://ipython.scipy.org/dist/>`_. The :mod:`ctypes` module, which comes with Python 2.5 and greater, is required by PyReadline. It is available for Python 2.4 at http://python.net/crew/theller/ctypes. | |
|
110 | ||
|
111 | nose | |
|
112 | ---- | |
|
113 | ||
|
114 | To run the IPython test suite you will need the :mod:`nose` package. Nose provides a great way of sniffing out and running all of the IPython tests. The simplest way of getting nose, is to use :command:`easy_install`:: | |
|
115 | ||
|
116 | $ easy_install nose | |
|
117 | ||
|
118 | Another way of getting this is to do:: | |
|
119 | ||
|
120 | $ easy_install IPython[test] | |
|
121 | ||
|
122 | For more installation options, see the `nose website <http://somethingaboutorange.com/mrl/projects/nose/>`_. Once you have nose installed, you can run IPython's test suite using the iptest command:: | |
|
123 | ||
|
124 | $ iptest | |
|
125 | ||
|
126 | ||
|
127 | pexpect | |
|
128 | ------- | |
|
129 | ||
|
130 | The `pexpect <http://www.noah.org/wiki/Pexpect>`_ package is used in IPython's :command:`irunner` script. On Unix platforms (including OS X), just do:: | |
|
131 | ||
|
132 | $ easy_install pexpect | |
|
133 | ||
|
134 | Windows users are out of luck as pexpect does not run there. | |
|
135 | ||
|
136 | Dependencies for IPython.kernel (parallel computing) | |
|
137 | ==================================================== | |
|
138 | ||
|
139 | The IPython kernel provides a nice architecture for parallel computing. The main focus of this architecture is on interactive parallel computing. These features require a number of additional packages: | |
|
140 | ||
|
141 | * zope.interface (yep, we use interfaces) | |
|
142 | * Twisted (asynchronous networking framework) | |
|
143 | * Foolscap (a nice, secure network protocol) | |
|
144 | * pyOpenSSL (security for network connections) | |
|
145 | ||
|
146 | On a Unix style platform (including OS X), if you want to use :mod:`setuptools`, you can just do:: | |
|
147 | ||
|
148 | $ easy_install IPython[kernel] # the first three | |
|
149 | $ easy_install IPython[security] # pyOpenSSL | |
|
150 | ||
|
151 | zope.interface and Twisted | |
|
152 | -------------------------- | |
|
153 | ||
|
154 | On Unix style platforms (including OS X), the simplest way of getting the these is to use :command:`easy_install`:: | |
|
155 | ||
|
156 | $ easy_install zope.interface | |
|
157 | $ easy_install Twisted | |
|
158 | ||
|
159 | Of course, you can also download the source tarballs from the `Twisted website <twistedmatrix.org>`_ and the `zope.interface page at PyPI <http://pypi.python.org/pypi/zope.interface>`_ and do the usual ``python setup.py install`` if you prefer. | |
|
160 | ||
|
161 | Windows is a bit different. For zope.interface and Twisted, simply get the latest binary ``.exe`` installer from the Twisted website. This installer includes both zope.interface and Twisted and should just work. | |
|
162 | ||
|
163 | Foolscap | |
|
164 | -------- | |
|
165 | ||
|
166 | Foolscap uses Twisted to provide a very nice secure RPC protocol that we use to implement our parallel computing features. | |
|
167 | ||
|
168 | On all platforms a simple:: | |
|
169 | ||
|
170 | $ easy_install foolscap | |
|
171 | ||
|
172 | should work. You can also download the source tarballs from the `Foolscap website <http://foolscap.lothar.com/trac>`_ and do ``python setup.py install`` if you prefer. | |
|
173 | ||
|
174 | pyOpenSSL | |
|
175 | --------- | |
|
176 | ||
|
177 | IPython requires an older version of pyOpenSSL (0.6 rather than the current 0.7). There are a couple of options for getting this: | |
|
178 | ||
|
179 | 1. Most Linux distributions have packages for pyOpenSSL. | |
|
180 | 2. The built-in Python 2.5 on OS X 10.5 already has it installed. | |
|
181 | 3. There are source tarballs on the pyOpenSSL website. On Unix-like | |
|
182 | platforms, these can be built using ``python seutp.py install``. | |
|
183 | 4. There is also a binary ``.exe`` Windows installer on the `pyOpenSSL website <http://pyopenssl.sourceforge.net/>`_. | |
|
184 | ||
|
185 | Dependencies for IPython.frontend (the IPython GUI) | |
|
186 | =================================================== | |
|
187 | ||
|
188 | wxPython | |
|
189 | -------- | |
|
190 | ||
|
191 | Starting with IPython 0.9, IPython has a new IPython.frontend package that has a nice wxPython based IPython GUI. As you would expect, this GUI requires wxPython. Most Linux distributions have wxPython packages available and the built-in Python on OS X comes with wxPython preinstalled. For Windows, a binary installer is available on the `wxPython website <http://www.wxpython.org/>`_. No newline at end of file |
|
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,99 +1,97 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | """Release data for the IPython project. | |
|
3 | ||
|
4 | $Id: Release.py 3002 2008-02-01 07:17:00Z fperez $""" | |
|
2 | """Release data for the IPython project.""" | |
|
5 | 3 | |
|
6 | 4 | #***************************************************************************** |
|
7 | 5 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | 6 | # |
|
9 | 7 | # Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and Nathaniel Gray |
|
10 | 8 | # <n8gray@caltech.edu> |
|
11 | 9 | # |
|
12 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 11 | # the file COPYING, distributed as part of this software. |
|
14 | 12 | #***************************************************************************** |
|
15 | 13 | |
|
16 | 14 | # Name of the package for release purposes. This is the name which labels |
|
17 | 15 | # the tarballs and RPMs made by distutils, so it's best to lowercase it. |
|
18 | 16 | name = 'ipython' |
|
19 | 17 | |
|
20 | 18 | # For versions with substrings (like 0.6.16.svn), use an extra . to separate |
|
21 | 19 | # the new substring. We have to avoid using either dashes or underscores, |
|
22 | 20 | # because bdist_rpm does not accept dashes (an RPM) convention, and |
|
23 | 21 | # bdist_deb does not accept underscores (a Debian convention). |
|
24 | 22 | |
|
25 | 23 | development = False # change this to False to do a release |
|
26 |
version_base = '0.9. |
|
|
24 | version_base = '0.9.1' | |
|
27 | 25 | branch = 'ipython' |
|
28 |
revision = '11 |
|
|
26 | revision = '1143' | |
|
29 | 27 | |
|
30 | 28 | if development: |
|
31 | 29 | if branch == 'ipython': |
|
32 | 30 | version = '%s.bzr.r%s' % (version_base, revision) |
|
33 | 31 | else: |
|
34 | 32 | version = '%s.bzr.r%s.%s' % (version_base, revision, branch) |
|
35 | 33 | else: |
|
36 | 34 | version = version_base |
|
37 | 35 | |
|
38 | 36 | |
|
39 | 37 | description = "Tools for interactive development in Python." |
|
40 | 38 | |
|
41 | 39 | long_description = \ |
|
42 | 40 | """ |
|
43 | 41 | IPython provides a replacement for the interactive Python interpreter with |
|
44 | 42 | extra functionality. |
|
45 | 43 | |
|
46 | 44 | Main features: |
|
47 | 45 | |
|
48 | 46 | * Comprehensive object introspection. |
|
49 | 47 | |
|
50 | 48 | * Input history, persistent across sessions. |
|
51 | 49 | |
|
52 | 50 | * Caching of output results during a session with automatically generated |
|
53 | 51 | references. |
|
54 | 52 | |
|
55 | 53 | * Readline based name completion. |
|
56 | 54 | |
|
57 | 55 | * Extensible system of 'magic' commands for controlling the environment and |
|
58 | 56 | performing many tasks related either to IPython or the operating system. |
|
59 | 57 | |
|
60 | 58 | * Configuration system with easy switching between different setups (simpler |
|
61 | 59 | than changing $PYTHONSTARTUP environment variables every time). |
|
62 | 60 | |
|
63 | 61 | * Session logging and reloading. |
|
64 | 62 | |
|
65 | 63 | * Extensible syntax processing for special purpose situations. |
|
66 | 64 | |
|
67 | 65 | * Access to the system shell with user-extensible alias system. |
|
68 | 66 | |
|
69 | 67 | * Easily embeddable in other Python programs. |
|
70 | 68 | |
|
71 | 69 | * Integrated access to the pdb debugger and the Python profiler. |
|
72 | 70 | |
|
73 | 71 | The latest development version is always available at the IPython subversion |
|
74 | 72 | repository_. |
|
75 | 73 | |
|
76 | 74 | .. _repository: http://ipython.scipy.org/svn/ipython/ipython/trunk#egg=ipython-dev |
|
77 | 75 | """ |
|
78 | 76 | |
|
79 | 77 | license = 'BSD' |
|
80 | 78 | |
|
81 | 79 | authors = {'Fernando' : ('Fernando Perez','fperez@colorado.edu'), |
|
82 | 80 | 'Janko' : ('Janko Hauser','jhauser@zscout.de'), |
|
83 | 81 | 'Nathan' : ('Nathaniel Gray','n8gray@caltech.edu'), |
|
84 | 82 | 'Ville' : ('Ville Vainio','vivainio@gmail.com'), |
|
85 | 83 | 'Brian' : ('Brian E Granger', 'ellisonbg@gmail.com'), |
|
86 | 84 | 'Min' : ('Min Ragan-Kelley', 'benjaminrk@gmail.com') |
|
87 | 85 | } |
|
88 | 86 | |
|
89 | 87 | author = 'The IPython Development Team' |
|
90 | 88 | |
|
91 | 89 | author_email = 'ipython-dev@scipy.org' |
|
92 | 90 | |
|
93 | 91 | url = 'http://ipython.scipy.org' |
|
94 | 92 | |
|
95 | 93 | download_url = 'http://ipython.scipy.org/dist' |
|
96 | 94 | |
|
97 | 95 | platforms = ['Linux','Mac OSX','Windows XP/2000/NT','Windows 95/98/ME'] |
|
98 | 96 | |
|
99 | 97 | keywords = ['Interactive','Interpreter','Shell','Parallel','Distributed'] |
@@ -1,76 +1,76 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | Base front end class for all async frontends. |
|
3 | 3 | """ |
|
4 | 4 | __docformat__ = "restructuredtext en" |
|
5 | 5 | |
|
6 | 6 | #------------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008 The IPython Development Team |
|
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 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #------------------------------------------------------------------------------- |
|
17 | import uuid | |
|
17 | from IPython.external import guid | |
|
18 | 18 | |
|
19 | 19 | |
|
20 | 20 | from zope.interface import Interface, Attribute, implements, classProvides |
|
21 | 21 | from twisted.python.failure import Failure |
|
22 | 22 | from IPython.frontend.frontendbase import FrontEndBase, IFrontEnd, IFrontEndFactory |
|
23 | 23 | from IPython.kernel.core.history import FrontEndHistory |
|
24 | 24 | from IPython.kernel.engineservice import IEngineCore |
|
25 | 25 | |
|
26 | 26 | |
|
27 | 27 | class AsyncFrontEndBase(FrontEndBase): |
|
28 | 28 | """ |
|
29 | 29 | Overrides FrontEndBase to wrap execute in a deferred result. |
|
30 | 30 | All callbacks are made as callbacks on the deferred result. |
|
31 | 31 | """ |
|
32 | 32 | |
|
33 | 33 | implements(IFrontEnd) |
|
34 | 34 | classProvides(IFrontEndFactory) |
|
35 | 35 | |
|
36 | 36 | def __init__(self, engine=None, history=None): |
|
37 | 37 | assert(engine==None or IEngineCore.providedBy(engine)) |
|
38 | 38 | self.engine = IEngineCore(engine) |
|
39 | 39 | if history is None: |
|
40 | 40 | self.history = FrontEndHistory(input_cache=['']) |
|
41 | 41 | else: |
|
42 | 42 | self.history = history |
|
43 | 43 | |
|
44 | 44 | |
|
45 | 45 | def execute(self, block, blockID=None): |
|
46 | 46 | """Execute the block and return the deferred result. |
|
47 | 47 | |
|
48 | 48 | Parameters: |
|
49 | 49 | block : {str, AST} |
|
50 | 50 | blockID : any |
|
51 | 51 | Caller may provide an ID to identify this block. |
|
52 | 52 | result['blockID'] := blockID |
|
53 | 53 | |
|
54 | 54 | Result: |
|
55 | 55 | Deferred result of self.interpreter.execute |
|
56 | 56 | """ |
|
57 | 57 | |
|
58 | 58 | if(not self.is_complete(block)): |
|
59 | 59 | return Failure(Exception("Block is not compilable")) |
|
60 | 60 | |
|
61 | 61 | if(blockID == None): |
|
62 |
blockID = |
|
|
62 | blockID = guid.generate() | |
|
63 | 63 | |
|
64 | 64 | d = self.engine.execute(block) |
|
65 | 65 | d.addCallback(self._add_history, block=block) |
|
66 | 66 | d.addCallbacks(self._add_block_id_for_result, |
|
67 | 67 | errback=self._add_block_id_for_failure, |
|
68 | 68 | callbackArgs=(blockID,), |
|
69 | 69 | errbackArgs=(blockID,)) |
|
70 | 70 | d.addBoth(self.update_cell_prompt, blockID=blockID) |
|
71 | 71 | d.addCallbacks(self.render_result, |
|
72 | 72 | errback=self.render_error) |
|
73 | 73 | |
|
74 | 74 | return d |
|
75 | 75 | |
|
76 | 76 |
@@ -1,560 +1,560 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.frontend.cocoa.tests.test_cocoa_frontend -*- |
|
3 | 3 | |
|
4 | 4 | """PyObjC classes to provide a Cocoa frontend to the |
|
5 | 5 | IPython.kernel.engineservice.IEngineBase. |
|
6 | 6 | |
|
7 | 7 | To add an IPython interpreter to a cocoa app, instantiate an |
|
8 | 8 | IPythonCocoaController in a XIB and connect its textView outlet to an |
|
9 | 9 | NSTextView instance in your UI. That's it. |
|
10 | 10 | |
|
11 | 11 | Author: Barry Wark |
|
12 | 12 | """ |
|
13 | 13 | |
|
14 | 14 | __docformat__ = "restructuredtext en" |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Copyright (C) 2008 The IPython Development Team |
|
18 | 18 | # |
|
19 | 19 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | 20 | # the file COPYING, distributed as part of this software. |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Imports |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | import sys |
|
28 | 28 | import objc |
|
29 | import uuid | |
|
29 | from IPython.external import guid | |
|
30 | 30 | |
|
31 | 31 | from Foundation import NSObject, NSMutableArray, NSMutableDictionary,\ |
|
32 | 32 | NSLog, NSNotificationCenter, NSMakeRange,\ |
|
33 | 33 | NSLocalizedString, NSIntersectionRange,\ |
|
34 | 34 | NSString, NSAutoreleasePool |
|
35 | 35 | |
|
36 | 36 | from AppKit import NSApplicationWillTerminateNotification, NSBeep,\ |
|
37 | 37 | NSTextView, NSRulerView, NSVerticalRuler |
|
38 | 38 | |
|
39 | 39 | from pprint import saferepr |
|
40 | 40 | |
|
41 | 41 | import IPython |
|
42 | 42 | from IPython.kernel.engineservice import ThreadedEngineService |
|
43 | 43 | from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase |
|
44 | 44 | |
|
45 | 45 | from twisted.internet.threads import blockingCallFromThread |
|
46 | 46 | from twisted.python.failure import Failure |
|
47 | 47 | |
|
48 | 48 | #----------------------------------------------------------------------------- |
|
49 | 49 | # Classes to implement the Cocoa frontend |
|
50 | 50 | #----------------------------------------------------------------------------- |
|
51 | 51 | |
|
52 | 52 | # TODO: |
|
53 | 53 | # 1. use MultiEngineClient and out-of-process engine rather than |
|
54 | 54 | # ThreadedEngineService? |
|
55 | 55 | # 2. integrate Xgrid launching of engines |
|
56 | 56 | |
|
57 | 57 | class AutoreleasePoolWrappedThreadedEngineService(ThreadedEngineService): |
|
58 | 58 | """Wrap all blocks in an NSAutoreleasePool""" |
|
59 | 59 | |
|
60 | 60 | def wrapped_execute(self, msg, lines): |
|
61 | 61 | """wrapped_execute""" |
|
62 | 62 | try: |
|
63 | 63 | p = NSAutoreleasePool.alloc().init() |
|
64 | 64 | result = super(AutoreleasePoolWrappedThreadedEngineService, |
|
65 | 65 | self).wrapped_execute(msg, lines) |
|
66 | 66 | finally: |
|
67 | 67 | p.drain() |
|
68 | 68 | |
|
69 | 69 | return result |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | class Cell(NSObject): |
|
74 | 74 | """ |
|
75 | 75 | Representation of the prompts, input and output of a cell in the |
|
76 | 76 | frontend |
|
77 | 77 | """ |
|
78 | 78 | |
|
79 | 79 | blockNumber = objc.ivar().unsigned_long() |
|
80 | 80 | blockID = objc.ivar() |
|
81 | 81 | inputBlock = objc.ivar() |
|
82 | 82 | output = objc.ivar() |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | |
|
86 | 86 | class CellBlock(object): |
|
87 | 87 | """ |
|
88 | 88 | Storage for information about text ranges relating to a single cell |
|
89 | 89 | """ |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | def __init__(self, inputPromptRange, inputRange=None, outputPromptRange=None, |
|
93 | 93 | outputRange=None): |
|
94 | 94 | super(CellBlock, self).__init__() |
|
95 | 95 | self.inputPromptRange = inputPromptRange |
|
96 | 96 | self.inputRange = inputRange |
|
97 | 97 | self.outputPromptRange = outputPromptRange |
|
98 | 98 | self.outputRange = outputRange |
|
99 | 99 | |
|
100 | 100 | def update_ranges_for_insertion(self, text, textRange): |
|
101 | 101 | """Update ranges for text insertion at textRange""" |
|
102 | 102 | |
|
103 | 103 | for r in [self.inputPromptRange,self.inputRange, |
|
104 | 104 | self.outputPromptRange, self.outputRange]: |
|
105 | 105 | if(r == None): |
|
106 | 106 | continue |
|
107 | 107 | intersection = NSIntersectionRange(r,textRange) |
|
108 | 108 | if(intersection.length == 0): #ranges don't intersect |
|
109 | 109 | if r.location >= textRange.location: |
|
110 | 110 | r.location += len(text) |
|
111 | 111 | else: #ranges intersect |
|
112 | 112 | if(r.location > textRange.location): |
|
113 | 113 | offset = len(text) - intersection.length |
|
114 | 114 | r.length -= offset |
|
115 | 115 | r.location += offset |
|
116 | 116 | elif(r.location == textRange.location): |
|
117 | 117 | r.length += len(text) - intersection.length |
|
118 | 118 | else: |
|
119 | 119 | r.length -= intersection.length |
|
120 | 120 | |
|
121 | 121 | |
|
122 | 122 | def update_ranges_for_deletion(self, textRange): |
|
123 | 123 | """Update ranges for text deletion at textRange""" |
|
124 | 124 | |
|
125 | 125 | for r in [self.inputPromptRange,self.inputRange, |
|
126 | 126 | self.outputPromptRange, self.outputRange]: |
|
127 | 127 | if(r==None): |
|
128 | 128 | continue |
|
129 | 129 | intersection = NSIntersectionRange(r, textRange) |
|
130 | 130 | if(intersection.length == 0): #ranges don't intersect |
|
131 | 131 | if r.location >= textRange.location: |
|
132 | 132 | r.location -= textRange.length |
|
133 | 133 | else: #ranges intersect |
|
134 | 134 | if(r.location > textRange.location): |
|
135 | 135 | offset = intersection.length |
|
136 | 136 | r.length -= offset |
|
137 | 137 | r.location += offset |
|
138 | 138 | elif(r.location == textRange.location): |
|
139 | 139 | r.length += intersection.length |
|
140 | 140 | else: |
|
141 | 141 | r.length -= intersection.length |
|
142 | 142 | |
|
143 | 143 | def __repr__(self): |
|
144 | 144 | return 'CellBlock('+ str((self.inputPromptRange, |
|
145 | 145 | self.inputRange, |
|
146 | 146 | self.outputPromptRange, |
|
147 | 147 | self.outputRange)) + ')' |
|
148 | 148 | |
|
149 | 149 | |
|
150 | 150 | |
|
151 | 151 | |
|
152 | 152 | class IPythonCocoaController(NSObject, AsyncFrontEndBase): |
|
153 | 153 | userNS = objc.ivar() #mirror of engine.user_ns (key=>str(value)) |
|
154 | 154 | waitingForEngine = objc.ivar().bool() |
|
155 | 155 | textView = objc.IBOutlet() |
|
156 | 156 | |
|
157 | 157 | def init(self): |
|
158 | 158 | self = super(IPythonCocoaController, self).init() |
|
159 | 159 | AsyncFrontEndBase.__init__(self, |
|
160 | 160 | engine=AutoreleasePoolWrappedThreadedEngineService()) |
|
161 | 161 | if(self != None): |
|
162 | 162 | self._common_init() |
|
163 | 163 | |
|
164 | 164 | return self |
|
165 | 165 | |
|
166 | 166 | def _common_init(self): |
|
167 | 167 | """_common_init""" |
|
168 | 168 | |
|
169 | 169 | self.userNS = NSMutableDictionary.dictionary() |
|
170 | 170 | self.waitingForEngine = False |
|
171 | 171 | |
|
172 | 172 | self.lines = {} |
|
173 | 173 | self.tabSpaces = 4 |
|
174 | 174 | self.tabUsesSpaces = True |
|
175 | 175 | self.currentBlockID = self.next_block_ID() |
|
176 | 176 | self.blockRanges = {} # blockID=>CellBlock |
|
177 | 177 | |
|
178 | 178 | |
|
179 | 179 | def awakeFromNib(self): |
|
180 | 180 | """awakeFromNib""" |
|
181 | 181 | |
|
182 | 182 | self._common_init() |
|
183 | 183 | |
|
184 | 184 | # Start the IPython engine |
|
185 | 185 | self.engine.startService() |
|
186 | 186 | NSLog('IPython engine started') |
|
187 | 187 | |
|
188 | 188 | # Register for app termination |
|
189 | 189 | nc = NSNotificationCenter.defaultCenter() |
|
190 | 190 | nc.addObserver_selector_name_object_( |
|
191 | 191 | self, |
|
192 | 192 | 'appWillTerminate:', |
|
193 | 193 | NSApplicationWillTerminateNotification, |
|
194 | 194 | None) |
|
195 | 195 | |
|
196 | 196 | self.textView.setDelegate_(self) |
|
197 | 197 | self.textView.enclosingScrollView().setHasVerticalRuler_(True) |
|
198 | 198 | r = NSRulerView.alloc().initWithScrollView_orientation_( |
|
199 | 199 | self.textView.enclosingScrollView(), |
|
200 | 200 | NSVerticalRuler) |
|
201 | 201 | self.verticalRulerView = r |
|
202 | 202 | self.verticalRulerView.setClientView_(self.textView) |
|
203 | 203 | self._start_cli_banner() |
|
204 | 204 | self.start_new_block() |
|
205 | 205 | |
|
206 | 206 | |
|
207 | 207 | def appWillTerminate_(self, notification): |
|
208 | 208 | """appWillTerminate""" |
|
209 | 209 | |
|
210 | 210 | self.engine.stopService() |
|
211 | 211 | |
|
212 | 212 | |
|
213 | 213 | def complete(self, token): |
|
214 | 214 | """Complete token in engine's user_ns |
|
215 | 215 | |
|
216 | 216 | Parameters |
|
217 | 217 | ---------- |
|
218 | 218 | token : string |
|
219 | 219 | |
|
220 | 220 | Result |
|
221 | 221 | ------ |
|
222 | 222 | Deferred result of |
|
223 | 223 | IPython.kernel.engineservice.IEngineBase.complete |
|
224 | 224 | """ |
|
225 | 225 | |
|
226 | 226 | return self.engine.complete(token) |
|
227 | 227 | |
|
228 | 228 | |
|
229 | 229 | def execute(self, block, blockID=None): |
|
230 | 230 | self.waitingForEngine = True |
|
231 | 231 | self.willChangeValueForKey_('commandHistory') |
|
232 | 232 | d = super(IPythonCocoaController, self).execute(block, |
|
233 | 233 | blockID) |
|
234 | 234 | d.addBoth(self._engine_done) |
|
235 | 235 | d.addCallback(self._update_user_ns) |
|
236 | 236 | |
|
237 | 237 | return d |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | def push_(self, namespace): |
|
241 | 241 | """Push dictionary of key=>values to python namespace""" |
|
242 | 242 | |
|
243 | 243 | self.waitingForEngine = True |
|
244 | 244 | self.willChangeValueForKey_('commandHistory') |
|
245 | 245 | d = self.engine.push(namespace) |
|
246 | 246 | d.addBoth(self._engine_done) |
|
247 | 247 | d.addCallback(self._update_user_ns) |
|
248 | 248 | |
|
249 | 249 | |
|
250 | 250 | def pull_(self, keys): |
|
251 | 251 | """Pull keys from python namespace""" |
|
252 | 252 | |
|
253 | 253 | self.waitingForEngine = True |
|
254 | 254 | result = blockingCallFromThread(self.engine.pull, keys) |
|
255 | 255 | self.waitingForEngine = False |
|
256 | 256 | |
|
257 | 257 | @objc.signature('v@:@I') |
|
258 | 258 | def executeFileAtPath_encoding_(self, path, encoding): |
|
259 | 259 | """Execute file at path in an empty namespace. Update the engine |
|
260 | 260 | user_ns with the resulting locals.""" |
|
261 | 261 | |
|
262 | 262 | lines,err = NSString.stringWithContentsOfFile_encoding_error_( |
|
263 | 263 | path, |
|
264 | 264 | encoding, |
|
265 | 265 | None) |
|
266 | 266 | self.engine.execute(lines) |
|
267 | 267 | |
|
268 | 268 | |
|
269 | 269 | def _engine_done(self, x): |
|
270 | 270 | self.waitingForEngine = False |
|
271 | 271 | self.didChangeValueForKey_('commandHistory') |
|
272 | 272 | return x |
|
273 | 273 | |
|
274 | 274 | def _update_user_ns(self, result): |
|
275 | 275 | """Update self.userNS from self.engine's namespace""" |
|
276 | 276 | d = self.engine.keys() |
|
277 | 277 | d.addCallback(self._get_engine_namespace_values_for_keys) |
|
278 | 278 | |
|
279 | 279 | return result |
|
280 | 280 | |
|
281 | 281 | |
|
282 | 282 | def _get_engine_namespace_values_for_keys(self, keys): |
|
283 | 283 | d = self.engine.pull(keys) |
|
284 | 284 | d.addCallback(self._store_engine_namespace_values, keys=keys) |
|
285 | 285 | |
|
286 | 286 | |
|
287 | 287 | def _store_engine_namespace_values(self, values, keys=[]): |
|
288 | 288 | assert(len(values) == len(keys)) |
|
289 | 289 | self.willChangeValueForKey_('userNS') |
|
290 | 290 | for (k,v) in zip(keys,values): |
|
291 | 291 | self.userNS[k] = saferepr(v) |
|
292 | 292 | self.didChangeValueForKey_('userNS') |
|
293 | 293 | |
|
294 | 294 | |
|
295 | 295 | def update_cell_prompt(self, result, blockID=None): |
|
296 | 296 | print self.blockRanges |
|
297 | 297 | if(isinstance(result, Failure)): |
|
298 | 298 | prompt = self.input_prompt() |
|
299 | 299 | |
|
300 | 300 | else: |
|
301 | 301 | prompt = self.input_prompt(number=result['number']) |
|
302 | 302 | |
|
303 | 303 | r = self.blockRanges[blockID].inputPromptRange |
|
304 | 304 | self.insert_text(prompt, |
|
305 | 305 | textRange=r, |
|
306 | 306 | scrollToVisible=False |
|
307 | 307 | ) |
|
308 | 308 | |
|
309 | 309 | return result |
|
310 | 310 | |
|
311 | 311 | |
|
312 | 312 | def render_result(self, result): |
|
313 | 313 | blockID = result['blockID'] |
|
314 | 314 | inputRange = self.blockRanges[blockID].inputRange |
|
315 | 315 | del self.blockRanges[blockID] |
|
316 | 316 | |
|
317 | 317 | #print inputRange,self.current_block_range() |
|
318 | 318 | self.insert_text('\n' + |
|
319 | 319 | self.output_prompt(number=result['number']) + |
|
320 | 320 | result.get('display',{}).get('pprint','') + |
|
321 | 321 | '\n\n', |
|
322 | 322 | textRange=NSMakeRange(inputRange.location+inputRange.length, |
|
323 | 323 | 0)) |
|
324 | 324 | return result |
|
325 | 325 | |
|
326 | 326 | |
|
327 | 327 | def render_error(self, failure): |
|
328 | 328 | print failure |
|
329 | 329 | blockID = failure.blockID |
|
330 | 330 | inputRange = self.blockRanges[blockID].inputRange |
|
331 | 331 | self.insert_text('\n' + |
|
332 | 332 | self.output_prompt() + |
|
333 | 333 | '\n' + |
|
334 | 334 | failure.getErrorMessage() + |
|
335 | 335 | '\n\n', |
|
336 | 336 | textRange=NSMakeRange(inputRange.location + |
|
337 | 337 | inputRange.length, |
|
338 | 338 | 0)) |
|
339 | 339 | self.start_new_block() |
|
340 | 340 | return failure |
|
341 | 341 | |
|
342 | 342 | |
|
343 | 343 | def _start_cli_banner(self): |
|
344 | 344 | """Print banner""" |
|
345 | 345 | |
|
346 | 346 | banner = """IPython1 %s -- An enhanced Interactive Python.""" % \ |
|
347 | 347 | IPython.__version__ |
|
348 | 348 | |
|
349 | 349 | self.insert_text(banner + '\n\n') |
|
350 | 350 | |
|
351 | 351 | |
|
352 | 352 | def start_new_block(self): |
|
353 | 353 | """""" |
|
354 | 354 | |
|
355 | 355 | self.currentBlockID = self.next_block_ID() |
|
356 | 356 | self.blockRanges[self.currentBlockID] = self.new_cell_block() |
|
357 | 357 | self.insert_text(self.input_prompt(), |
|
358 | 358 | textRange=self.current_block_range().inputPromptRange) |
|
359 | 359 | |
|
360 | 360 | |
|
361 | 361 | |
|
362 | 362 | def next_block_ID(self): |
|
363 | 363 | |
|
364 |
return |
|
|
364 | return guid.generate() | |
|
365 | 365 | |
|
366 | 366 | def new_cell_block(self): |
|
367 | 367 | """A new CellBlock at the end of self.textView.textStorage()""" |
|
368 | 368 | |
|
369 | 369 | return CellBlock(NSMakeRange(self.textView.textStorage().length(), |
|
370 | 370 | 0), #len(self.input_prompt())), |
|
371 | 371 | NSMakeRange(self.textView.textStorage().length(),# + len(self.input_prompt()), |
|
372 | 372 | 0)) |
|
373 | 373 | |
|
374 | 374 | |
|
375 | 375 | def current_block_range(self): |
|
376 | 376 | return self.blockRanges.get(self.currentBlockID, |
|
377 | 377 | self.new_cell_block()) |
|
378 | 378 | |
|
379 | 379 | def current_block(self): |
|
380 | 380 | """The current block's text""" |
|
381 | 381 | |
|
382 | 382 | return self.text_for_range(self.current_block_range().inputRange) |
|
383 | 383 | |
|
384 | 384 | def text_for_range(self, textRange): |
|
385 | 385 | """text_for_range""" |
|
386 | 386 | |
|
387 | 387 | ts = self.textView.textStorage() |
|
388 | 388 | return ts.string().substringWithRange_(textRange) |
|
389 | 389 | |
|
390 | 390 | def current_line(self): |
|
391 | 391 | block = self.text_for_range(self.current_block_range().inputRange) |
|
392 | 392 | block = block.split('\n') |
|
393 | 393 | return block[-1] |
|
394 | 394 | |
|
395 | 395 | |
|
396 | 396 | def insert_text(self, string=None, textRange=None, scrollToVisible=True): |
|
397 | 397 | """Insert text into textView at textRange, updating blockRanges |
|
398 | 398 | as necessary |
|
399 | 399 | """ |
|
400 | 400 | if(textRange == None): |
|
401 | 401 | #range for end of text |
|
402 | 402 | textRange = NSMakeRange(self.textView.textStorage().length(), 0) |
|
403 | 403 | |
|
404 | 404 | |
|
405 | 405 | self.textView.replaceCharactersInRange_withString_( |
|
406 | 406 | textRange, string) |
|
407 | 407 | |
|
408 | 408 | for r in self.blockRanges.itervalues(): |
|
409 | 409 | r.update_ranges_for_insertion(string, textRange) |
|
410 | 410 | |
|
411 | 411 | self.textView.setSelectedRange_(textRange) |
|
412 | 412 | if(scrollToVisible): |
|
413 | 413 | self.textView.scrollRangeToVisible_(textRange) |
|
414 | 414 | |
|
415 | 415 | |
|
416 | 416 | |
|
417 | 417 | def replace_current_block_with_string(self, textView, string): |
|
418 | 418 | textView.replaceCharactersInRange_withString_( |
|
419 | 419 | self.current_block_range().inputRange, |
|
420 | 420 | string) |
|
421 | 421 | self.current_block_range().inputRange.length = len(string) |
|
422 | 422 | r = NSMakeRange(textView.textStorage().length(), 0) |
|
423 | 423 | textView.scrollRangeToVisible_(r) |
|
424 | 424 | textView.setSelectedRange_(r) |
|
425 | 425 | |
|
426 | 426 | |
|
427 | 427 | def current_indent_string(self): |
|
428 | 428 | """returns string for indent or None if no indent""" |
|
429 | 429 | |
|
430 | 430 | return self._indent_for_block(self.current_block()) |
|
431 | 431 | |
|
432 | 432 | |
|
433 | 433 | def _indent_for_block(self, block): |
|
434 | 434 | lines = block.split('\n') |
|
435 | 435 | if(len(lines) > 1): |
|
436 | 436 | currentIndent = len(lines[-1]) - len(lines[-1].lstrip()) |
|
437 | 437 | if(currentIndent == 0): |
|
438 | 438 | currentIndent = self.tabSpaces |
|
439 | 439 | |
|
440 | 440 | if(self.tabUsesSpaces): |
|
441 | 441 | result = ' ' * currentIndent |
|
442 | 442 | else: |
|
443 | 443 | result = '\t' * (currentIndent/self.tabSpaces) |
|
444 | 444 | else: |
|
445 | 445 | result = None |
|
446 | 446 | |
|
447 | 447 | return result |
|
448 | 448 | |
|
449 | 449 | |
|
450 | 450 | # NSTextView delegate methods... |
|
451 | 451 | def textView_doCommandBySelector_(self, textView, selector): |
|
452 | 452 | assert(textView == self.textView) |
|
453 | 453 | NSLog("textView_doCommandBySelector_: "+selector) |
|
454 | 454 | |
|
455 | 455 | |
|
456 | 456 | if(selector == 'insertNewline:'): |
|
457 | 457 | indent = self.current_indent_string() |
|
458 | 458 | if(indent): |
|
459 | 459 | line = indent + self.current_line() |
|
460 | 460 | else: |
|
461 | 461 | line = self.current_line() |
|
462 | 462 | |
|
463 | 463 | if(self.is_complete(self.current_block())): |
|
464 | 464 | self.execute(self.current_block(), |
|
465 | 465 | blockID=self.currentBlockID) |
|
466 | 466 | self.start_new_block() |
|
467 | 467 | |
|
468 | 468 | return True |
|
469 | 469 | |
|
470 | 470 | return False |
|
471 | 471 | |
|
472 | 472 | elif(selector == 'moveUp:'): |
|
473 | 473 | prevBlock = self.get_history_previous(self.current_block()) |
|
474 | 474 | if(prevBlock != None): |
|
475 | 475 | self.replace_current_block_with_string(textView, prevBlock) |
|
476 | 476 | else: |
|
477 | 477 | NSBeep() |
|
478 | 478 | return True |
|
479 | 479 | |
|
480 | 480 | elif(selector == 'moveDown:'): |
|
481 | 481 | nextBlock = self.get_history_next() |
|
482 | 482 | if(nextBlock != None): |
|
483 | 483 | self.replace_current_block_with_string(textView, nextBlock) |
|
484 | 484 | else: |
|
485 | 485 | NSBeep() |
|
486 | 486 | return True |
|
487 | 487 | |
|
488 | 488 | elif(selector == 'moveToBeginningOfParagraph:'): |
|
489 | 489 | textView.setSelectedRange_(NSMakeRange( |
|
490 | 490 | self.current_block_range().inputRange.location, |
|
491 | 491 | 0)) |
|
492 | 492 | return True |
|
493 | 493 | elif(selector == 'moveToEndOfParagraph:'): |
|
494 | 494 | textView.setSelectedRange_(NSMakeRange( |
|
495 | 495 | self.current_block_range().inputRange.location + \ |
|
496 | 496 | self.current_block_range().inputRange.length, 0)) |
|
497 | 497 | return True |
|
498 | 498 | elif(selector == 'deleteToEndOfParagraph:'): |
|
499 | 499 | if(textView.selectedRange().location <= \ |
|
500 | 500 | self.current_block_range().location): |
|
501 | 501 | raise NotImplemented() |
|
502 | 502 | |
|
503 | 503 | return False # don't actually handle the delete |
|
504 | 504 | |
|
505 | 505 | elif(selector == 'insertTab:'): |
|
506 | 506 | if(len(self.current_line().strip()) == 0): #only white space |
|
507 | 507 | return False |
|
508 | 508 | else: |
|
509 | 509 | self.textView.complete_(self) |
|
510 | 510 | return True |
|
511 | 511 | |
|
512 | 512 | elif(selector == 'deleteBackward:'): |
|
513 | 513 | #if we're at the beginning of the current block, ignore |
|
514 | 514 | if(textView.selectedRange().location == \ |
|
515 | 515 | self.current_block_range().inputRange.location): |
|
516 | 516 | return True |
|
517 | 517 | else: |
|
518 | 518 | for r in self.blockRanges.itervalues(): |
|
519 | 519 | deleteRange = textView.selectedRange |
|
520 | 520 | if(deleteRange.length == 0): |
|
521 | 521 | deleteRange.location -= 1 |
|
522 | 522 | deleteRange.length = 1 |
|
523 | 523 | r.update_ranges_for_deletion(deleteRange) |
|
524 | 524 | return False |
|
525 | 525 | return False |
|
526 | 526 | |
|
527 | 527 | |
|
528 | 528 | def textView_shouldChangeTextInRanges_replacementStrings_(self, |
|
529 | 529 | textView, ranges, replacementStrings): |
|
530 | 530 | """ |
|
531 | 531 | Delegate method for NSTextView. |
|
532 | 532 | |
|
533 | 533 | Refuse change text in ranges not at end, but make those changes at |
|
534 | 534 | end. |
|
535 | 535 | """ |
|
536 | 536 | |
|
537 | 537 | assert(len(ranges) == len(replacementStrings)) |
|
538 | 538 | allow = True |
|
539 | 539 | for r,s in zip(ranges, replacementStrings): |
|
540 | 540 | r = r.rangeValue() |
|
541 | 541 | if(textView.textStorage().length() > 0 and |
|
542 | 542 | r.location < self.current_block_range().inputRange.location): |
|
543 | 543 | self.insert_text(s) |
|
544 | 544 | allow = False |
|
545 | 545 | |
|
546 | 546 | return allow |
|
547 | 547 | |
|
548 | 548 | def textView_completions_forPartialWordRange_indexOfSelectedItem_(self, |
|
549 | 549 | textView, words, charRange, index): |
|
550 | 550 | try: |
|
551 | 551 | ts = textView.textStorage() |
|
552 | 552 | token = ts.string().substringWithRange_(charRange) |
|
553 | 553 | completions = blockingCallFromThread(self.complete, token) |
|
554 | 554 | except: |
|
555 | 555 | completions = objc.nil |
|
556 | 556 | NSBeep() |
|
557 | 557 | |
|
558 | 558 | return (completions,0) |
|
559 | 559 | |
|
560 | 560 |
@@ -1,362 +1,343 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*- |
|
3 | 3 | """ |
|
4 | 4 | frontendbase provides an interface and base class for GUI frontends for |
|
5 | 5 | IPython.kernel/IPython.kernel.core. |
|
6 | 6 | |
|
7 | 7 | Frontend implementations will likely want to subclass FrontEndBase. |
|
8 | 8 | |
|
9 | 9 | Author: Barry Wark |
|
10 | 10 | """ |
|
11 | 11 | __docformat__ = "restructuredtext en" |
|
12 | 12 | |
|
13 | 13 | #------------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008 The IPython Development Team |
|
15 | 15 | # |
|
16 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
17 | 17 | # the file COPYING, distributed as part of this software. |
|
18 | 18 | #------------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | #------------------------------------------------------------------------------- |
|
21 | 21 | # Imports |
|
22 | 22 | #------------------------------------------------------------------------------- |
|
23 | 23 | import string |
|
24 |
import |
|
|
25 | import _ast | |
|
24 | import codeop | |
|
25 | from IPython.external import guid | |
|
26 | ||
|
26 | 27 | |
|
27 | 28 | from IPython.frontend.zopeinterface import ( |
|
28 | 29 | Interface, |
|
29 | 30 | Attribute, |
|
30 | implements, | |
|
31 | classProvides | |
|
32 | 31 | ) |
|
33 | 32 | from IPython.kernel.core.history import FrontEndHistory |
|
34 | 33 | from IPython.kernel.core.util import Bunch |
|
35 | 34 | |
|
36 | 35 | ############################################################################## |
|
37 | 36 | # TEMPORARY!!! fake configuration, while we decide whether to use tconfig or |
|
38 | 37 | # not |
|
39 | 38 | |
|
40 | 39 | rc = Bunch() |
|
41 | 40 | rc.prompt_in1 = r'In [$number]: ' |
|
42 | 41 | rc.prompt_in2 = r'...' |
|
43 | 42 | rc.prompt_out = r'Out [$number]: ' |
|
44 | 43 | |
|
45 | 44 | ############################################################################## |
|
46 | 45 | # Interface definitions |
|
47 | 46 | ############################################################################## |
|
48 | 47 | |
|
49 | 48 | class IFrontEndFactory(Interface): |
|
50 | 49 | """Factory interface for frontends.""" |
|
51 | 50 | |
|
52 | 51 | def __call__(engine=None, history=None): |
|
53 | 52 | """ |
|
54 | 53 | Parameters: |
|
55 | 54 | interpreter : IPython.kernel.engineservice.IEngineCore |
|
56 | 55 | """ |
|
57 | 56 | |
|
58 | 57 | pass |
|
59 | 58 | |
|
60 | 59 | |
|
61 | 60 | class IFrontEnd(Interface): |
|
62 | 61 | """Interface for frontends. All methods return t.i.d.Deferred""" |
|
63 | 62 | |
|
64 | 63 | Attribute("input_prompt_template", "string.Template instance\ |
|
65 | 64 | substituteable with execute result.") |
|
66 | 65 | Attribute("output_prompt_template", "string.Template instance\ |
|
67 | 66 | substituteable with execute result.") |
|
68 | 67 | Attribute("continuation_prompt_template", "string.Template instance\ |
|
69 | 68 | substituteable with execute result.") |
|
70 | 69 | |
|
71 | 70 | def update_cell_prompt(result, blockID=None): |
|
72 | 71 | """Subclass may override to update the input prompt for a block. |
|
73 | 72 | |
|
74 | 73 | In asynchronous frontends, this method will be called as a |
|
75 | 74 | twisted.internet.defer.Deferred's callback/errback. |
|
76 | 75 | Implementations should thus return result when finished. |
|
77 | 76 | |
|
78 | 77 | Result is a result dict in case of success, and a |
|
79 | 78 | twisted.python.util.failure.Failure in case of an error |
|
80 | 79 | """ |
|
81 | 80 | |
|
82 | 81 | pass |
|
83 | 82 | |
|
84 | 83 | def render_result(result): |
|
85 | 84 | """Render the result of an execute call. Implementors may choose the |
|
86 | 85 | method of rendering. |
|
87 | 86 | For example, a notebook-style frontend might render a Chaco plot |
|
88 | 87 | inline. |
|
89 | 88 | |
|
90 | 89 | Parameters: |
|
91 | 90 | result : dict (result of IEngineBase.execute ) |
|
92 | 91 | blockID = result['blockID'] |
|
93 | 92 | |
|
94 | 93 | Result: |
|
95 | 94 | Output of frontend rendering |
|
96 | 95 | """ |
|
97 | 96 | |
|
98 | 97 | pass |
|
99 | 98 | |
|
100 | 99 | def render_error(failure): |
|
101 | 100 | """Subclasses must override to render the failure. |
|
102 | 101 | |
|
103 | 102 | In asynchronous frontend, since this method will be called as a |
|
104 | 103 | twisted.internet.defer.Deferred's callback. Implementations |
|
105 | 104 | should thus return result when finished. |
|
106 | 105 | |
|
107 | 106 | blockID = failure.blockID |
|
108 | 107 | """ |
|
109 | 108 | |
|
110 | 109 | pass |
|
111 | 110 | |
|
112 | 111 | def input_prompt(number=''): |
|
113 | 112 | """Returns the input prompt by subsituting into |
|
114 | 113 | self.input_prompt_template |
|
115 | 114 | """ |
|
116 | 115 | pass |
|
117 | 116 | |
|
118 | 117 | def output_prompt(number=''): |
|
119 | 118 | """Returns the output prompt by subsituting into |
|
120 | 119 | self.output_prompt_template |
|
121 | 120 | """ |
|
122 | 121 | |
|
123 | 122 | pass |
|
124 | 123 | |
|
125 | 124 | def continuation_prompt(): |
|
126 | 125 | """Returns the continuation prompt by subsituting into |
|
127 | 126 | self.continuation_prompt_template |
|
128 | 127 | """ |
|
129 | 128 | |
|
130 | 129 | pass |
|
131 | 130 | |
|
132 | 131 | def is_complete(block): |
|
133 | 132 | """Returns True if block is complete, False otherwise.""" |
|
134 | 133 | |
|
135 | 134 | pass |
|
136 | 135 | |
|
137 | def compile_ast(block): | |
|
138 | """Compiles block to an _ast.AST""" | |
|
139 | ||
|
140 | pass | |
|
141 | ||
|
136 | ||
|
142 | 137 | def get_history_previous(current_block): |
|
143 | 138 | """Returns the block previous in the history. Saves currentBlock if |
|
144 | 139 | the history_cursor is currently at the end of the input history""" |
|
145 | 140 | pass |
|
146 | 141 | |
|
147 | 142 | def get_history_next(): |
|
148 | 143 | """Returns the next block in the history.""" |
|
149 | 144 | |
|
150 | 145 | pass |
|
151 | 146 | |
|
152 | 147 | def complete(self, line): |
|
153 | 148 | """Returns the list of possible completions, and the completed |
|
154 | 149 | line. |
|
155 | 150 | |
|
156 | 151 | The input argument is the full line to be completed. This method |
|
157 | 152 | returns both the line completed as much as possible, and the list |
|
158 | 153 | of further possible completions (full words). |
|
159 | 154 | """ |
|
160 | 155 | pass |
|
161 | 156 | |
|
162 | 157 | |
|
163 | 158 | ############################################################################## |
|
164 | 159 | # Base class for all the frontends. |
|
165 | 160 | ############################################################################## |
|
166 | 161 | |
|
167 | 162 | class FrontEndBase(object): |
|
168 | 163 | """ |
|
169 | 164 | FrontEndBase manages the state tasks for a CLI frontend: |
|
170 | 165 | - Input and output history management |
|
171 | 166 | - Input/continuation and output prompt generation |
|
172 | 167 | |
|
173 | 168 | Some issues (due to possibly unavailable engine): |
|
174 | 169 | - How do we get the current cell number for the engine? |
|
175 | 170 | - How do we handle completions? |
|
176 | 171 | """ |
|
177 | 172 | |
|
178 | 173 | history_cursor = 0 |
|
179 | 174 | |
|
180 | 175 | input_prompt_template = string.Template(rc.prompt_in1) |
|
181 | 176 | output_prompt_template = string.Template(rc.prompt_out) |
|
182 | 177 | continuation_prompt_template = string.Template(rc.prompt_in2) |
|
183 | 178 | |
|
184 | 179 | def __init__(self, shell=None, history=None): |
|
185 | 180 | self.shell = shell |
|
186 | 181 | if history is None: |
|
187 | 182 | self.history = FrontEndHistory(input_cache=['']) |
|
188 | 183 | else: |
|
189 | 184 | self.history = history |
|
190 | 185 | |
|
191 | 186 | |
|
192 | 187 | def input_prompt(self, number=''): |
|
193 | 188 | """Returns the current input prompt |
|
194 | 189 | |
|
195 | 190 | It would be great to use ipython1.core.prompts.Prompt1 here |
|
196 | 191 | """ |
|
197 | 192 | return self.input_prompt_template.safe_substitute({'number':number}) |
|
198 | 193 | |
|
199 | 194 | |
|
200 | 195 | def continuation_prompt(self): |
|
201 | 196 | """Returns the current continuation prompt""" |
|
202 | 197 | |
|
203 | 198 | return self.continuation_prompt_template.safe_substitute() |
|
204 | 199 | |
|
205 | 200 | def output_prompt(self, number=''): |
|
206 | 201 | """Returns the output prompt for result""" |
|
207 | 202 | |
|
208 | 203 | return self.output_prompt_template.safe_substitute({'number':number}) |
|
209 | 204 | |
|
210 | 205 | |
|
211 | 206 | def is_complete(self, block): |
|
212 | 207 | """Determine if block is complete. |
|
213 | 208 | |
|
214 | 209 | Parameters |
|
215 | 210 | block : string |
|
216 | 211 | |
|
217 | 212 | Result |
|
218 | 213 | True if block can be sent to the engine without compile errors. |
|
219 | 214 | False otherwise. |
|
220 | 215 | """ |
|
221 | 216 | |
|
222 | 217 | try: |
|
223 |
|
|
|
218 | is_complete = codeop.compile_command(block.rstrip() + '\n\n', | |
|
219 | "<string>", "exec") | |
|
224 | 220 | except: |
|
225 | 221 | return False |
|
226 | 222 | |
|
227 | 223 | lines = block.split('\n') |
|
228 | return (len(lines)==1 or str(lines[-1])=='') | |
|
229 | ||
|
230 | ||
|
231 | def compile_ast(self, block): | |
|
232 | """Compile block to an AST | |
|
233 | ||
|
234 | Parameters: | |
|
235 | block : str | |
|
236 | ||
|
237 | Result: | |
|
238 | AST | |
|
239 | ||
|
240 | Throws: | |
|
241 | Exception if block cannot be compiled | |
|
242 | """ | |
|
243 | ||
|
244 | return compile(block, "<string>", "exec", _ast.PyCF_ONLY_AST) | |
|
224 | return ((is_complete is not None) | |
|
225 | and (len(lines)==1 or str(lines[-1])=='')) | |
|
245 | 226 | |
|
246 | 227 | |
|
247 | 228 | def execute(self, block, blockID=None): |
|
248 | 229 | """Execute the block and return the result. |
|
249 | 230 | |
|
250 | 231 | Parameters: |
|
251 | 232 | block : {str, AST} |
|
252 | 233 | blockID : any |
|
253 | 234 | Caller may provide an ID to identify this block. |
|
254 | 235 | result['blockID'] := blockID |
|
255 | 236 | |
|
256 | 237 | Result: |
|
257 | 238 | Deferred result of self.interpreter.execute |
|
258 | 239 | """ |
|
259 | 240 | |
|
260 | 241 | if(not self.is_complete(block)): |
|
261 | 242 | raise Exception("Block is not compilable") |
|
262 | 243 | |
|
263 | 244 | if(blockID == None): |
|
264 |
blockID = |
|
|
245 | blockID = guid.generate() | |
|
265 | 246 | |
|
266 | 247 | try: |
|
267 | 248 | result = self.shell.execute(block) |
|
268 | 249 | except Exception,e: |
|
269 | 250 | e = self._add_block_id_for_failure(e, blockID=blockID) |
|
270 | 251 | e = self.update_cell_prompt(e, blockID=blockID) |
|
271 | 252 | e = self.render_error(e) |
|
272 | 253 | else: |
|
273 | 254 | result = self._add_block_id_for_result(result, blockID=blockID) |
|
274 | 255 | result = self.update_cell_prompt(result, blockID=blockID) |
|
275 | 256 | result = self.render_result(result) |
|
276 | 257 | |
|
277 | 258 | return result |
|
278 | 259 | |
|
279 | 260 | |
|
280 | 261 | def _add_block_id_for_result(self, result, blockID): |
|
281 | 262 | """Add the blockID to result or failure. Unfortunatley, we have to |
|
282 | 263 | treat failures differently than result dicts. |
|
283 | 264 | """ |
|
284 | 265 | |
|
285 | 266 | result['blockID'] = blockID |
|
286 | 267 | |
|
287 | 268 | return result |
|
288 | 269 | |
|
289 | 270 | def _add_block_id_for_failure(self, failure, blockID): |
|
290 | 271 | """_add_block_id_for_failure""" |
|
291 | 272 | failure.blockID = blockID |
|
292 | 273 | return failure |
|
293 | 274 | |
|
294 | 275 | |
|
295 | 276 | def _add_history(self, result, block=None): |
|
296 | 277 | """Add block to the history""" |
|
297 | 278 | |
|
298 | 279 | assert(block != None) |
|
299 | 280 | self.history.add_items([block]) |
|
300 | 281 | self.history_cursor += 1 |
|
301 | 282 | |
|
302 | 283 | return result |
|
303 | 284 | |
|
304 | 285 | |
|
305 | 286 | def get_history_previous(self, current_block): |
|
306 | 287 | """ Returns previous history string and decrement history cursor. |
|
307 | 288 | """ |
|
308 | 289 | command = self.history.get_history_item(self.history_cursor - 1) |
|
309 | 290 | |
|
310 | 291 | if command is not None: |
|
311 | 292 | if(self.history_cursor+1 == len(self.history.input_cache)): |
|
312 | 293 | self.history.input_cache[self.history_cursor] = current_block |
|
313 | 294 | self.history_cursor -= 1 |
|
314 | 295 | return command |
|
315 | 296 | |
|
316 | 297 | |
|
317 | 298 | def get_history_next(self): |
|
318 | 299 | """ Returns next history string and increment history cursor. |
|
319 | 300 | """ |
|
320 | 301 | command = self.history.get_history_item(self.history_cursor+1) |
|
321 | 302 | |
|
322 | 303 | if command is not None: |
|
323 | 304 | self.history_cursor += 1 |
|
324 | 305 | return command |
|
325 | 306 | |
|
326 | 307 | ### |
|
327 | 308 | # Subclasses probably want to override these methods... |
|
328 | 309 | ### |
|
329 | 310 | |
|
330 | 311 | def update_cell_prompt(self, result, blockID=None): |
|
331 | 312 | """Subclass may override to update the input prompt for a block. |
|
332 | 313 | |
|
333 | 314 | This method only really makes sens in asyncrhonous frontend. |
|
334 | 315 | Since this method will be called as a |
|
335 | 316 | twisted.internet.defer.Deferred's callback, implementations should |
|
336 | 317 | return result when finished. |
|
337 | 318 | """ |
|
338 | 319 | |
|
339 | 320 | raise NotImplementedError |
|
340 | 321 | |
|
341 | 322 | |
|
342 | 323 | def render_result(self, result): |
|
343 | 324 | """Subclasses must override to render result. |
|
344 | 325 | |
|
345 | 326 | In asynchronous frontends, this method will be called as a |
|
346 | 327 | twisted.internet.defer.Deferred's callback. Implementations |
|
347 | 328 | should thus return result when finished. |
|
348 | 329 | """ |
|
349 | 330 | |
|
350 | 331 | raise NotImplementedError |
|
351 | 332 | |
|
352 | 333 | |
|
353 | 334 | def render_error(self, failure): |
|
354 | 335 | """Subclasses must override to render the failure. |
|
355 | 336 | |
|
356 | 337 | In asynchronous frontends, this method will be called as a |
|
357 | 338 | twisted.internet.defer.Deferred's callback. Implementations |
|
358 | 339 | should thus return result when finished. |
|
359 | 340 | """ |
|
360 | 341 | |
|
361 | 342 | raise NotImplementedError |
|
362 | 343 |
@@ -1,320 +1,337 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | Base front end class for all line-oriented frontends, rather than |
|
3 | 3 | block-oriented. |
|
4 | 4 | |
|
5 | 5 | Currently this focuses on synchronous frontends. |
|
6 | 6 | """ |
|
7 | 7 | __docformat__ = "restructuredtext en" |
|
8 | 8 | |
|
9 | 9 | #------------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2008 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 | 19 | import re |
|
20 | 20 | |
|
21 | import IPython | |
|
22 | 21 | import sys |
|
23 | 22 | import codeop |
|
24 | import traceback | |
|
25 | 23 | |
|
26 | 24 | from frontendbase import FrontEndBase |
|
27 | 25 | from IPython.kernel.core.interpreter import Interpreter |
|
28 | 26 | |
|
29 | 27 | def common_prefix(strings): |
|
30 | 28 | """ Given a list of strings, return the common prefix between all |
|
31 | 29 | these strings. |
|
32 | 30 | """ |
|
33 | 31 | ref = strings[0] |
|
34 | 32 | prefix = '' |
|
35 | 33 | for size in range(len(ref)): |
|
36 | 34 | test_prefix = ref[:size+1] |
|
37 | 35 | for string in strings[1:]: |
|
38 | 36 | if not string.startswith(test_prefix): |
|
39 | 37 | return prefix |
|
40 | 38 | prefix = test_prefix |
|
41 | 39 | |
|
42 | 40 | return prefix |
|
43 | 41 | |
|
44 | 42 | #------------------------------------------------------------------------------- |
|
45 | 43 | # Base class for the line-oriented front ends |
|
46 | 44 | #------------------------------------------------------------------------------- |
|
47 | 45 | class LineFrontEndBase(FrontEndBase): |
|
48 | 46 | """ Concrete implementation of the FrontEndBase class. This is meant |
|
49 | 47 | to be the base class behind all the frontend that are line-oriented, |
|
50 | 48 | rather than block-oriented. |
|
51 | 49 | """ |
|
52 | 50 | |
|
53 | 51 | # We need to keep the prompt number, to be able to increment |
|
54 | 52 | # it when there is an exception. |
|
55 | 53 | prompt_number = 1 |
|
56 | 54 | |
|
57 | 55 | # We keep a reference to the last result: it helps testing and |
|
58 | 56 | # programatic control of the frontend. |
|
59 | 57 | last_result = dict(number=0) |
|
60 | 58 | |
|
61 | 59 | # The input buffer being edited |
|
62 | 60 | input_buffer = '' |
|
63 | 61 | |
|
64 | 62 | # Set to true for debug output |
|
65 | 63 | debug = False |
|
66 | 64 | |
|
67 | 65 | # A banner to print at startup |
|
68 | 66 | banner = None |
|
69 | 67 | |
|
70 | 68 | #-------------------------------------------------------------------------- |
|
71 | 69 | # FrontEndBase interface |
|
72 | 70 | #-------------------------------------------------------------------------- |
|
73 | 71 | |
|
74 | 72 | def __init__(self, shell=None, history=None, banner=None, *args, **kwargs): |
|
75 | 73 | if shell is None: |
|
76 | 74 | shell = Interpreter() |
|
77 | 75 | FrontEndBase.__init__(self, shell=shell, history=history) |
|
78 | 76 | |
|
79 | 77 | if banner is not None: |
|
80 | 78 | self.banner = banner |
|
81 | 79 | |
|
82 | 80 | def start(self): |
|
83 | 81 | """ Put the frontend in a state where it is ready for user |
|
84 | 82 | interaction. |
|
85 | 83 | """ |
|
86 | 84 | if self.banner is not None: |
|
87 | 85 | self.write(self.banner, refresh=False) |
|
88 | 86 | |
|
89 | 87 | self.new_prompt(self.input_prompt_template.substitute(number=1)) |
|
90 | 88 | |
|
91 | 89 | |
|
92 | 90 | def complete(self, line): |
|
93 | 91 | """Complete line in engine's user_ns |
|
94 | 92 | |
|
95 | 93 | Parameters |
|
96 | 94 | ---------- |
|
97 | 95 | line : string |
|
98 | 96 | |
|
99 | 97 | Result |
|
100 | 98 | ------ |
|
101 | 99 | The replacement for the line and the list of possible completions. |
|
102 | 100 | """ |
|
103 | 101 | completions = self.shell.complete(line) |
|
104 | 102 | complete_sep = re.compile('[\s\{\}\[\]\(\)\=]') |
|
105 | 103 | if completions: |
|
106 | 104 | prefix = common_prefix(completions) |
|
107 | 105 | residual = complete_sep.split(line)[:-1] |
|
108 | 106 | line = line[:-len(residual)] + prefix |
|
109 | 107 | return line, completions |
|
110 | 108 | |
|
111 | 109 | |
|
112 | 110 | def render_result(self, result): |
|
113 | 111 | """ Frontend-specific rendering of the result of a calculation |
|
114 | 112 | that has been sent to an engine. |
|
115 | 113 | """ |
|
116 | 114 | if 'stdout' in result and result['stdout']: |
|
117 | 115 | self.write('\n' + result['stdout']) |
|
118 | 116 | if 'display' in result and result['display']: |
|
119 | 117 | self.write("%s%s\n" % ( |
|
120 | 118 | self.output_prompt_template.substitute( |
|
121 | 119 | number=result['number']), |
|
122 | 120 | result['display']['pprint'] |
|
123 | 121 | ) ) |
|
124 | 122 | |
|
125 | 123 | |
|
126 | 124 | def render_error(self, failure): |
|
127 | 125 | """ Frontend-specific rendering of error. |
|
128 | 126 | """ |
|
129 | 127 | self.write('\n\n'+str(failure)+'\n\n') |
|
130 | 128 | return failure |
|
131 | 129 | |
|
132 | 130 | |
|
133 | 131 | def is_complete(self, string): |
|
134 | 132 | """ Check if a string forms a complete, executable set of |
|
135 | 133 | commands. |
|
136 | 134 | |
|
137 | 135 | For the line-oriented frontend, multi-line code is not executed |
|
138 | 136 | as soon as it is complete: the users has to enter two line |
|
139 | 137 | returns. |
|
140 | 138 | """ |
|
141 | 139 | if string in ('', '\n'): |
|
142 | 140 | # Prefiltering, eg through ipython0, may return an empty |
|
143 | 141 | # string although some operations have been accomplished. We |
|
144 | 142 | # thus want to consider an empty string as a complete |
|
145 | 143 | # statement. |
|
146 | 144 | return True |
|
147 | 145 | elif ( len(self.input_buffer.split('\n'))>2 |
|
148 | 146 | and not re.findall(r"\n[\t ]*\n[\t ]*$", string)): |
|
149 | 147 | return False |
|
150 | 148 | else: |
|
151 | 149 | self.capture_output() |
|
152 | 150 | try: |
|
153 | 151 | # Add line returns here, to make sure that the statement is |
|
154 | 152 | # complete. |
|
155 | 153 | is_complete = codeop.compile_command(string.rstrip() + '\n\n', |
|
156 | 154 | "<string>", "exec") |
|
157 | 155 | self.release_output() |
|
158 | 156 | except Exception, e: |
|
159 | 157 | # XXX: Hack: return True so that the |
|
160 | 158 | # code gets executed and the error captured. |
|
161 | 159 | is_complete = True |
|
162 | 160 | return is_complete |
|
163 | 161 | |
|
164 | 162 | |
|
165 | 163 | def write(self, string, refresh=True): |
|
166 | 164 | """ Write some characters to the display. |
|
167 | 165 | |
|
168 | 166 | Subclass should overide this method. |
|
169 | 167 | |
|
170 | 168 | The refresh keyword argument is used in frontends with an |
|
171 | 169 | event loop, to choose whether the write should trigget an UI |
|
172 | 170 | refresh, and thus be syncrhonous, or not. |
|
173 | 171 | """ |
|
174 | 172 | print >>sys.__stderr__, string |
|
175 | 173 | |
|
176 | 174 | |
|
177 | 175 | def execute(self, python_string, raw_string=None): |
|
178 | 176 | """ Stores the raw_string in the history, and sends the |
|
179 | 177 | python string to the interpreter. |
|
180 | 178 | """ |
|
181 | 179 | if raw_string is None: |
|
182 | 180 | raw_string = python_string |
|
183 | 181 | # Create a false result, in case there is an exception |
|
184 | 182 | self.last_result = dict(number=self.prompt_number) |
|
183 | ||
|
184 | ## try: | |
|
185 | ## self.history.input_cache[-1] = raw_string.rstrip() | |
|
186 | ## result = self.shell.execute(python_string) | |
|
187 | ## self.last_result = result | |
|
188 | ## self.render_result(result) | |
|
189 | ## except: | |
|
190 | ## self.show_traceback() | |
|
191 | ## finally: | |
|
192 | ## self.after_execute() | |
|
193 | ||
|
185 | 194 | try: |
|
186 | self.history.input_cache[-1] = raw_string.rstrip() | |
|
187 | result = self.shell.execute(python_string) | |
|
188 | self.last_result = result | |
|
189 |
self. |
|
|
190 | except: | |
|
191 | self.show_traceback() | |
|
195 | try: | |
|
196 | self.history.input_cache[-1] = raw_string.rstrip() | |
|
197 | result = self.shell.execute(python_string) | |
|
198 | self.last_result = result | |
|
199 | self.render_result(result) | |
|
200 | except: | |
|
201 | self.show_traceback() | |
|
192 | 202 | finally: |
|
193 | 203 | self.after_execute() |
|
194 | 204 | |
|
205 | ||
|
195 | 206 | #-------------------------------------------------------------------------- |
|
196 | 207 | # LineFrontEndBase interface |
|
197 | 208 | #-------------------------------------------------------------------------- |
|
198 | 209 | |
|
199 | 210 | def prefilter_input(self, string): |
|
200 | 211 | """ Prefilter the input to turn it in valid python. |
|
201 | 212 | """ |
|
202 | 213 | string = string.replace('\r\n', '\n') |
|
203 | 214 | string = string.replace('\t', 4*' ') |
|
204 | 215 | # Clean the trailing whitespace |
|
205 | 216 | string = '\n'.join(l.rstrip() for l in string.split('\n')) |
|
206 | 217 | return string |
|
207 | 218 | |
|
208 | 219 | |
|
209 | 220 | def after_execute(self): |
|
210 | 221 | """ All the operations required after an execution to put the |
|
211 | 222 | terminal back in a shape where it is usable. |
|
212 | 223 | """ |
|
213 | 224 | self.prompt_number += 1 |
|
214 | 225 | self.new_prompt(self.input_prompt_template.substitute( |
|
215 | 226 | number=(self.last_result['number'] + 1))) |
|
216 | 227 | # Start a new empty history entry |
|
217 | 228 | self._add_history(None, '') |
|
218 | 229 | self.history_cursor = len(self.history.input_cache) - 1 |
|
219 | 230 | |
|
220 | 231 | |
|
221 | 232 | def complete_current_input(self): |
|
222 | 233 | """ Do code completion on current line. |
|
223 | 234 | """ |
|
224 | 235 | if self.debug: |
|
225 | 236 | print >>sys.__stdout__, "complete_current_input", |
|
226 | 237 | line = self.input_buffer |
|
227 | 238 | new_line, completions = self.complete(line) |
|
228 | 239 | if len(completions)>1: |
|
229 | 240 | self.write_completion(completions, new_line=new_line) |
|
230 | 241 | elif not line == new_line: |
|
231 | 242 | self.input_buffer = new_line |
|
232 | 243 | if self.debug: |
|
233 | 244 | print >>sys.__stdout__, 'line', line |
|
234 | 245 | print >>sys.__stdout__, 'new_line', new_line |
|
235 | 246 | print >>sys.__stdout__, completions |
|
236 | 247 | |
|
237 | 248 | |
|
238 | 249 | def get_line_width(self): |
|
239 | 250 | """ Return the width of the line in characters. |
|
240 | 251 | """ |
|
241 | 252 | return 80 |
|
242 | 253 | |
|
243 | 254 | |
|
244 | 255 | def write_completion(self, possibilities, new_line=None): |
|
245 | 256 | """ Write the list of possible completions. |
|
246 | 257 | |
|
247 | 258 | new_line is the completed input line that should be displayed |
|
248 | 259 | after the completion are writen. If None, the input_buffer |
|
249 | 260 | before the completion is used. |
|
250 | 261 | """ |
|
251 | 262 | if new_line is None: |
|
252 | 263 | new_line = self.input_buffer |
|
253 | 264 | |
|
254 | 265 | self.write('\n') |
|
255 | 266 | max_len = len(max(possibilities, key=len)) + 1 |
|
256 | 267 | |
|
257 | 268 | # Now we check how much symbol we can put on a line... |
|
258 | 269 | chars_per_line = self.get_line_width() |
|
259 | 270 | symbols_per_line = max(1, chars_per_line/max_len) |
|
260 | 271 | |
|
261 | 272 | pos = 1 |
|
262 | 273 | buf = [] |
|
263 | 274 | for symbol in possibilities: |
|
264 | 275 | if pos < symbols_per_line: |
|
265 | 276 | buf.append(symbol.ljust(max_len)) |
|
266 | 277 | pos += 1 |
|
267 | 278 | else: |
|
268 | 279 | buf.append(symbol.rstrip() + '\n') |
|
269 | 280 | pos = 1 |
|
270 | 281 | self.write(''.join(buf)) |
|
271 | 282 | self.new_prompt(self.input_prompt_template.substitute( |
|
272 | 283 | number=self.last_result['number'] + 1)) |
|
273 | 284 | self.input_buffer = new_line |
|
274 | 285 | |
|
275 | 286 | |
|
276 | 287 | def new_prompt(self, prompt): |
|
277 | 288 | """ Prints a prompt and starts a new editing buffer. |
|
278 | 289 | |
|
279 | 290 | Subclasses should use this method to make sure that the |
|
280 | 291 | terminal is put in a state favorable for a new line |
|
281 | 292 | input. |
|
282 | 293 | """ |
|
283 | 294 | self.input_buffer = '' |
|
284 | 295 | self.write(prompt) |
|
285 | 296 | |
|
286 | 297 | |
|
298 | def execute_command(self, command, hidden=False): | |
|
299 | """ Execute a command, not only in the model, but also in the | |
|
300 | view, if any. | |
|
301 | """ | |
|
302 | return self.shell.execute(command) | |
|
303 | ||
|
287 | 304 | #-------------------------------------------------------------------------- |
|
288 | 305 | # Private API |
|
289 | 306 | #-------------------------------------------------------------------------- |
|
290 | 307 | |
|
291 | 308 | def _on_enter(self): |
|
292 | 309 | """ Called when the return key is pressed in a line editing |
|
293 | 310 | buffer. |
|
294 | 311 | """ |
|
295 | 312 | current_buffer = self.input_buffer |
|
296 | 313 | cleaned_buffer = self.prefilter_input(current_buffer) |
|
297 | 314 | if self.is_complete(cleaned_buffer): |
|
298 | 315 | self.execute(cleaned_buffer, raw_string=current_buffer) |
|
299 | 316 | else: |
|
300 | 317 | self.input_buffer += self._get_indent_string( |
|
301 | 318 | current_buffer[:-1]) |
|
302 | 319 | if len(current_buffer.split('\n')) == 2: |
|
303 | 320 | self.input_buffer += '\t\t' |
|
304 | 321 | if current_buffer[:-1].split('\n')[-1].rstrip().endswith(':'): |
|
305 | 322 | self.input_buffer += '\t' |
|
306 | 323 | |
|
307 | 324 | |
|
308 | 325 | def _get_indent_string(self, string): |
|
309 | 326 | """ Return the string of whitespace that prefixes a line. Used to |
|
310 | 327 | add the right amount of indendation when creating a new line. |
|
311 | 328 | """ |
|
312 | 329 | string = string.replace('\t', ' '*4) |
|
313 | 330 | string = string.split('\n')[-1] |
|
314 | 331 | indent_chars = len(string) - len(string.lstrip()) |
|
315 | 332 | indent_string = '\t'*(indent_chars // 4) + \ |
|
316 | 333 | ' '*(indent_chars % 4) |
|
317 | 334 | |
|
318 | 335 | return indent_string |
|
319 | 336 | |
|
320 | 337 |
@@ -1,232 +1,248 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | Frontend class that uses IPython0 to prefilter the inputs. |
|
3 | 3 | |
|
4 | 4 | Using the IPython0 mechanism gives us access to the magics. |
|
5 | 5 | |
|
6 | 6 | This is a transitory class, used here to do the transition between |
|
7 | 7 | ipython0 and ipython1. This class is meant to be short-lived as more |
|
8 | 8 | functionnality is abstracted out of ipython0 in reusable functions and |
|
9 | 9 | is added on the interpreter. This class can be a used to guide this |
|
10 | 10 | refactoring. |
|
11 | 11 | """ |
|
12 | 12 | __docformat__ = "restructuredtext en" |
|
13 | 13 | |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Copyright (C) 2008 The IPython Development Team |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #------------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #------------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #------------------------------------------------------------------------------- |
|
24 | 24 | import sys |
|
25 | 25 | |
|
26 | 26 | from linefrontendbase import LineFrontEndBase, common_prefix |
|
27 | 27 | from frontendbase import FrontEndBase |
|
28 | 28 | |
|
29 | 29 | from IPython.ipmaker import make_IPython |
|
30 | 30 | from IPython.ipapi import IPApi |
|
31 | 31 | from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap |
|
32 | 32 | |
|
33 | 33 | from IPython.kernel.core.sync_traceback_trap import SyncTracebackTrap |
|
34 | 34 | |
|
35 | 35 | from IPython.genutils import Term |
|
36 | 36 | import pydoc |
|
37 | 37 | import os |
|
38 | 38 | import sys |
|
39 | 39 | |
|
40 | 40 | |
|
41 | 41 | def mk_system_call(system_call_function, command): |
|
42 | 42 | """ given a os.system replacement, and a leading string command, |
|
43 | 43 | returns a function that will execute the command with the given |
|
44 | 44 | argument string. |
|
45 | 45 | """ |
|
46 | 46 | def my_system_call(args): |
|
47 | 47 | system_call_function("%s %s" % (command, args)) |
|
48 | 48 | |
|
49 | 49 | my_system_call.__doc__ = "Calls %s" % command |
|
50 | 50 | return my_system_call |
|
51 | 51 | |
|
52 | 52 | #------------------------------------------------------------------------------- |
|
53 | 53 | # Frontend class using ipython0 to do the prefiltering. |
|
54 | 54 | #------------------------------------------------------------------------------- |
|
55 | 55 | class PrefilterFrontEnd(LineFrontEndBase): |
|
56 | 56 | """ Class that uses ipython0 to do prefilter the input, do the |
|
57 | 57 | completion and the magics. |
|
58 | 58 | |
|
59 | 59 | The core trick is to use an ipython0 instance to prefilter the |
|
60 | 60 | input, and share the namespace between the interpreter instance used |
|
61 | 61 | to execute the statements and the ipython0 used for code |
|
62 | 62 | completion... |
|
63 | 63 | """ |
|
64 | 64 | |
|
65 | 65 | debug = False |
|
66 | 66 | |
|
67 | 67 | def __init__(self, ipython0=None, *args, **kwargs): |
|
68 | 68 | """ Parameters: |
|
69 | 69 | ----------- |
|
70 | 70 | |
|
71 | 71 | ipython0: an optional ipython0 instance to use for command |
|
72 | 72 | prefiltering and completion. |
|
73 | 73 | """ |
|
74 | 74 | LineFrontEndBase.__init__(self, *args, **kwargs) |
|
75 | 75 | self.shell.output_trap = RedirectorOutputTrap( |
|
76 | 76 | out_callback=self.write, |
|
77 | 77 | err_callback=self.write, |
|
78 | 78 | ) |
|
79 | 79 | self.shell.traceback_trap = SyncTracebackTrap( |
|
80 | 80 | formatters=self.shell.traceback_trap.formatters, |
|
81 | 81 | ) |
|
82 | 82 | |
|
83 | 83 | # Start the ipython0 instance: |
|
84 | 84 | self.save_output_hooks() |
|
85 | 85 | if ipython0 is None: |
|
86 | 86 | # Instanciate an IPython0 interpreter to be able to use the |
|
87 | 87 | # prefiltering. |
|
88 | 88 | # XXX: argv=[] is a bit bold. |
|
89 | 89 | ipython0 = make_IPython(argv=[], |
|
90 | 90 | user_ns=self.shell.user_ns, |
|
91 | 91 | user_global_ns=self.shell.user_global_ns) |
|
92 | 92 | self.ipython0 = ipython0 |
|
93 | 93 | # Set the pager: |
|
94 | 94 | self.ipython0.set_hook('show_in_pager', |
|
95 | 95 | lambda s, string: self.write("\n" + string)) |
|
96 | 96 | self.ipython0.write = self.write |
|
97 | 97 | self._ip = _ip = IPApi(self.ipython0) |
|
98 | 98 | # Make sure the raw system call doesn't get called, as we don't |
|
99 | 99 | # have a stdin accessible. |
|
100 | 100 | self._ip.system = self.system_call |
|
101 | 101 | # XXX: Muck around with magics so that they work better |
|
102 | 102 | # in our environment |
|
103 | 103 | self.ipython0.magic_ls = mk_system_call(self.system_call, |
|
104 | 104 | 'ls -CF') |
|
105 | 105 | # And now clean up the mess created by ipython0 |
|
106 | 106 | self.release_output() |
|
107 | 107 | |
|
108 | 108 | |
|
109 | 109 | if not 'banner' in kwargs and self.banner is None: |
|
110 | 110 | self.banner = self.ipython0.BANNER + """ |
|
111 | 111 | This is the wx frontend, by Gael Varoquaux. This is EXPERIMENTAL code.""" |
|
112 | 112 | |
|
113 | 113 | self.start() |
|
114 | 114 | |
|
115 | 115 | #-------------------------------------------------------------------------- |
|
116 | 116 | # FrontEndBase interface |
|
117 | 117 | #-------------------------------------------------------------------------- |
|
118 | 118 | |
|
119 | 119 | def show_traceback(self): |
|
120 | 120 | """ Use ipython0 to capture the last traceback and display it. |
|
121 | 121 | """ |
|
122 | 122 | self.capture_output() |
|
123 | 123 | self.ipython0.showtraceback(tb_offset=-1) |
|
124 | 124 | self.release_output() |
|
125 | 125 | |
|
126 | 126 | |
|
127 | 127 | def execute(self, python_string, raw_string=None): |
|
128 | 128 | if self.debug: |
|
129 | 129 | print 'Executing Python code:', repr(python_string) |
|
130 | 130 | self.capture_output() |
|
131 | 131 | LineFrontEndBase.execute(self, python_string, |
|
132 | 132 | raw_string=raw_string) |
|
133 | 133 | self.release_output() |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | def save_output_hooks(self): |
|
137 | 137 | """ Store all the output hooks we can think of, to be able to |
|
138 | 138 | restore them. |
|
139 | 139 | |
|
140 | 140 | We need to do this early, as starting the ipython0 instance will |
|
141 | 141 | screw ouput hooks. |
|
142 | 142 | """ |
|
143 | 143 | self.__old_cout_write = Term.cout.write |
|
144 | 144 | self.__old_cerr_write = Term.cerr.write |
|
145 | 145 | self.__old_stdout = sys.stdout |
|
146 | 146 | self.__old_stderr= sys.stderr |
|
147 | 147 | self.__old_help_output = pydoc.help.output |
|
148 | 148 | self.__old_display_hook = sys.displayhook |
|
149 | 149 | |
|
150 | 150 | |
|
151 | 151 | def capture_output(self): |
|
152 | 152 | """ Capture all the output mechanisms we can think of. |
|
153 | 153 | """ |
|
154 | 154 | self.save_output_hooks() |
|
155 | 155 | Term.cout.write = self.write |
|
156 | 156 | Term.cerr.write = self.write |
|
157 | 157 | sys.stdout = Term.cout |
|
158 | 158 | sys.stderr = Term.cerr |
|
159 | 159 | pydoc.help.output = self.shell.output_trap.out |
|
160 | 160 | |
|
161 | 161 | |
|
162 | 162 | def release_output(self): |
|
163 | 163 | """ Release all the different captures we have made. |
|
164 | 164 | """ |
|
165 | 165 | Term.cout.write = self.__old_cout_write |
|
166 | 166 | Term.cerr.write = self.__old_cerr_write |
|
167 | 167 | sys.stdout = self.__old_stdout |
|
168 | 168 | sys.stderr = self.__old_stderr |
|
169 | 169 | pydoc.help.output = self.__old_help_output |
|
170 | 170 | sys.displayhook = self.__old_display_hook |
|
171 | 171 | |
|
172 | 172 | |
|
173 | 173 | def complete(self, line): |
|
174 | 174 | # FIXME: This should be factored out in the linefrontendbase |
|
175 | 175 | # method. |
|
176 | 176 | word = line.split('\n')[-1].split(' ')[-1] |
|
177 | 177 | completions = self.ipython0.complete(word) |
|
178 | 178 | # FIXME: The proper sort should be done in the complete method. |
|
179 | 179 | key = lambda x: x.replace('_', '') |
|
180 | 180 | completions.sort(key=key) |
|
181 | 181 | if completions: |
|
182 | 182 | prefix = common_prefix(completions) |
|
183 | 183 | line = line[:-len(word)] + prefix |
|
184 | 184 | return line, completions |
|
185 | 185 | |
|
186 | 186 | |
|
187 | 187 | #-------------------------------------------------------------------------- |
|
188 | 188 | # LineFrontEndBase interface |
|
189 | 189 | #-------------------------------------------------------------------------- |
|
190 | 190 | |
|
191 | 191 | def prefilter_input(self, input_string): |
|
192 | 192 | """ Using IPython0 to prefilter the commands to turn them |
|
193 | 193 | in executable statements that are valid Python strings. |
|
194 | 194 | """ |
|
195 | 195 | input_string = LineFrontEndBase.prefilter_input(self, input_string) |
|
196 | 196 | filtered_lines = [] |
|
197 | 197 | # The IPython0 prefilters sometime produce output. We need to |
|
198 | 198 | # capture it. |
|
199 | 199 | self.capture_output() |
|
200 | 200 | self.last_result = dict(number=self.prompt_number) |
|
201 | ||
|
202 | ## try: | |
|
203 | ## for line in input_string.split('\n'): | |
|
204 | ## filtered_lines.append( | |
|
205 | ## self.ipython0.prefilter(line, False).rstrip()) | |
|
206 | ## except: | |
|
207 | ## # XXX: probably not the right thing to do. | |
|
208 | ## self.ipython0.showsyntaxerror() | |
|
209 | ## self.after_execute() | |
|
210 | ## finally: | |
|
211 | ## self.release_output() | |
|
212 | ||
|
213 | ||
|
201 | 214 | try: |
|
202 | for line in input_string.split('\n'): | |
|
203 | filtered_lines.append( | |
|
204 | self.ipython0.prefilter(line, False).rstrip()) | |
|
205 | except: | |
|
206 | # XXX: probably not the right thing to do. | |
|
207 | self.ipython0.showsyntaxerror() | |
|
208 | self.after_execute() | |
|
215 | try: | |
|
216 | for line in input_string.split('\n'): | |
|
217 | filtered_lines.append( | |
|
218 | self.ipython0.prefilter(line, False).rstrip()) | |
|
219 | except: | |
|
220 | # XXX: probably not the right thing to do. | |
|
221 | self.ipython0.showsyntaxerror() | |
|
222 | self.after_execute() | |
|
209 | 223 | finally: |
|
210 | 224 | self.release_output() |
|
211 | 225 | |
|
226 | ||
|
227 | ||
|
212 | 228 | # Clean up the trailing whitespace, to avoid indentation errors |
|
213 | 229 | filtered_string = '\n'.join(filtered_lines) |
|
214 | 230 | return filtered_string |
|
215 | 231 | |
|
216 | 232 | |
|
217 | 233 | #-------------------------------------------------------------------------- |
|
218 | 234 | # PrefilterFrontEnd interface |
|
219 | 235 | #-------------------------------------------------------------------------- |
|
220 | 236 | |
|
221 | 237 | def system_call(self, command_string): |
|
222 | 238 | """ Allows for frontend to define their own system call, to be |
|
223 | 239 | able capture output and redirect input. |
|
224 | 240 | """ |
|
225 | 241 | return os.system(command_string) |
|
226 | 242 | |
|
227 | 243 | |
|
228 | 244 | def do_exit(self): |
|
229 | 245 | """ Exit the shell, cleanup and save the history. |
|
230 | 246 | """ |
|
231 | 247 | self.ipython0.atexit_operations() |
|
232 | 248 |
@@ -1,155 +1,32 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | ||
|
3 | """This file contains unittests for the frontendbase module.""" | |
|
2 | """ | |
|
3 | Test the basic functionality of frontendbase. | |
|
4 | """ | |
|
4 | 5 | |
|
5 | 6 | __docformat__ = "restructuredtext en" |
|
6 | 7 | |
|
7 | #--------------------------------------------------------------------------- | |
|
8 |
# Copyright (C) 2008 The IPython Development Team |
|
|
9 | # | |
|
10 |
# Distributed under the terms of the BSD License. The full license is |
|
|
11 |
# the file COPYING, distributed as part of this software. |
|
|
12 | #--------------------------------------------------------------------------- | |
|
13 | ||
|
14 | #--------------------------------------------------------------------------- | |
|
15 | # Imports | |
|
16 | #--------------------------------------------------------------------------- | |
|
17 | ||
|
18 | import unittest | |
|
19 | ||
|
20 | try: | |
|
21 | from IPython.frontend.asyncfrontendbase import AsyncFrontEndBase | |
|
22 | from IPython.frontend import frontendbase | |
|
23 | from IPython.kernel.engineservice import EngineService | |
|
24 | except ImportError: | |
|
25 | import nose | |
|
26 | raise nose.SkipTest("This test requires zope.interface, Twisted and Foolscap") | |
|
27 | ||
|
28 | from IPython.testing.decorators import skip | |
|
29 | ||
|
30 | class FrontEndCallbackChecker(AsyncFrontEndBase): | |
|
31 | """FrontEndBase subclass for checking callbacks""" | |
|
32 | def __init__(self, engine=None, history=None): | |
|
33 | super(FrontEndCallbackChecker, self).__init__(engine=engine, | |
|
34 | history=history) | |
|
35 | self.updateCalled = False | |
|
36 | self.renderResultCalled = False | |
|
37 | self.renderErrorCalled = False | |
|
38 | ||
|
39 | def update_cell_prompt(self, result, blockID=None): | |
|
40 | self.updateCalled = True | |
|
41 | return result | |
|
42 | ||
|
43 | def render_result(self, result): | |
|
44 | self.renderResultCalled = True | |
|
45 | return result | |
|
46 | ||
|
47 | ||
|
48 | def render_error(self, failure): | |
|
49 | self.renderErrorCalled = True | |
|
50 | return failure | |
|
51 | ||
|
52 | ||
|
8 | #------------------------------------------------------------------------------- | |
|
9 | # Copyright (C) 2008 The IPython Development Team | |
|
10 | # | |
|
11 | # Distributed under the terms of the BSD License. The full license is | |
|
12 | # in the file COPYING, distributed as part of this software. | |
|
13 | #------------------------------------------------------------------------------- | |
|
14 | ||
|
15 | from IPython.frontend.frontendbase import FrontEndBase | |
|
16 | ||
|
17 | def test_iscomplete(): | |
|
18 | """ Check that is_complete works. | |
|
19 | """ | |
|
20 | f = FrontEndBase() | |
|
21 | assert f.is_complete('(a + a)') | |
|
22 | assert not f.is_complete('(a + a') | |
|
23 | assert f.is_complete('1') | |
|
24 | assert not f.is_complete('1 + ') | |
|
25 | assert not f.is_complete('1 + \n\n') | |
|
26 | assert f.is_complete('if True:\n print 1\n') | |
|
27 | assert not f.is_complete('if True:\n print 1') | |
|
28 | assert f.is_complete('def f():\n print 1\n') | |
|
29 | ||
|
30 | if __name__ == '__main__': | |
|
31 | test_iscomplete() | |
|
53 | 32 | |
|
54 | ||
|
55 | class TestAsyncFrontendBase(unittest.TestCase): | |
|
56 | def setUp(self): | |
|
57 | """Setup the EngineService and FrontEndBase""" | |
|
58 | ||
|
59 | self.fb = FrontEndCallbackChecker(engine=EngineService()) | |
|
60 | ||
|
61 | def test_implements_IFrontEnd(self): | |
|
62 | assert(frontendbase.IFrontEnd.implementedBy( | |
|
63 | AsyncFrontEndBase)) | |
|
64 | ||
|
65 | def test_is_complete_returns_False_for_incomplete_block(self): | |
|
66 | """""" | |
|
67 | ||
|
68 | block = """def test(a):""" | |
|
69 | ||
|
70 | assert(self.fb.is_complete(block) == False) | |
|
71 | ||
|
72 | def test_is_complete_returns_True_for_complete_block(self): | |
|
73 | """""" | |
|
74 | ||
|
75 | block = """def test(a): pass""" | |
|
76 | ||
|
77 | assert(self.fb.is_complete(block)) | |
|
78 | ||
|
79 | block = """a=3""" | |
|
80 | ||
|
81 | assert(self.fb.is_complete(block)) | |
|
82 | ||
|
83 | def test_blockID_added_to_result(self): | |
|
84 | block = """3+3""" | |
|
85 | ||
|
86 | d = self.fb.execute(block, blockID='TEST_ID') | |
|
87 | ||
|
88 | d.addCallback(self.checkBlockID, expected='TEST_ID') | |
|
89 | ||
|
90 | def test_blockID_added_to_failure(self): | |
|
91 | block = "raise Exception()" | |
|
92 | ||
|
93 | d = self.fb.execute(block,blockID='TEST_ID') | |
|
94 | d.addErrback(self.checkFailureID, expected='TEST_ID') | |
|
95 | ||
|
96 | def checkBlockID(self, result, expected=""): | |
|
97 | assert(result['blockID'] == expected) | |
|
98 | ||
|
99 | ||
|
100 | def checkFailureID(self, failure, expected=""): | |
|
101 | assert(failure.blockID == expected) | |
|
102 | ||
|
103 | ||
|
104 | def test_callbacks_added_to_execute(self): | |
|
105 | """test that | |
|
106 | update_cell_prompt | |
|
107 | render_result | |
|
108 | ||
|
109 | are added to execute request | |
|
110 | """ | |
|
111 | ||
|
112 | d = self.fb.execute("10+10") | |
|
113 | d.addCallback(self.checkCallbacks) | |
|
114 | ||
|
115 | def checkCallbacks(self, result): | |
|
116 | assert(self.fb.updateCalled) | |
|
117 | assert(self.fb.renderResultCalled) | |
|
118 | ||
|
119 | @skip("This test fails and lead to an unhandled error in a Deferred.") | |
|
120 | def test_error_callback_added_to_execute(self): | |
|
121 | """test that render_error called on execution error""" | |
|
122 | ||
|
123 | d = self.fb.execute("raise Exception()") | |
|
124 | d.addCallback(self.checkRenderError) | |
|
125 | ||
|
126 | def checkRenderError(self, result): | |
|
127 | assert(self.fb.renderErrorCalled) | |
|
128 | ||
|
129 | def test_history_returns_expected_block(self): | |
|
130 | """Make sure history browsing doesn't fail""" | |
|
131 | ||
|
132 | blocks = ["a=1","a=2","a=3"] | |
|
133 | for b in blocks: | |
|
134 | d = self.fb.execute(b) | |
|
135 | ||
|
136 | # d is now the deferred for the last executed block | |
|
137 | d.addCallback(self.historyTests, blocks) | |
|
138 | ||
|
139 | ||
|
140 | def historyTests(self, result, blocks): | |
|
141 | """historyTests""" | |
|
142 | ||
|
143 | assert(len(blocks) >= 3) | |
|
144 | assert(self.fb.get_history_previous("") == blocks[-2]) | |
|
145 | assert(self.fb.get_history_previous("") == blocks[-3]) | |
|
146 | assert(self.fb.get_history_next() == blocks[-2]) | |
|
147 | ||
|
148 | ||
|
149 | def test_history_returns_none_at_startup(self): | |
|
150 | """test_history_returns_none_at_startup""" | |
|
151 | ||
|
152 | assert(self.fb.get_history_previous("")==None) | |
|
153 | assert(self.fb.get_history_next()==None) | |
|
154 | ||
|
155 |
@@ -1,436 +1,436 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | A Wx widget to act as a console and input commands. |
|
4 | 4 | |
|
5 | 5 | This widget deals with prompts and provides an edit buffer |
|
6 | 6 | restricted to after the last prompt. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | __docformat__ = "restructuredtext en" |
|
10 | 10 | |
|
11 | 11 | #------------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is |
|
15 | 15 | # in 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 wx |
|
23 | 23 | import wx.stc as stc |
|
24 | 24 | |
|
25 | 25 | from wx.py import editwindow |
|
26 | 26 | import time |
|
27 | 27 | import sys |
|
28 | 28 | LINESEP = '\n' |
|
29 | 29 | if sys.platform == 'win32': |
|
30 | 30 | LINESEP = '\n\r' |
|
31 | 31 | |
|
32 | 32 | import re |
|
33 | 33 | |
|
34 | 34 | # FIXME: Need to provide an API for non user-generated display on the |
|
35 | 35 | # screen: this should not be editable by the user. |
|
36 | 36 | |
|
37 | 37 | _DEFAULT_SIZE = 10 |
|
38 | 38 | if sys.platform == 'darwin': |
|
39 |
_DEFAULT_S |
|
|
39 | _DEFAULT_SIZE = 12 | |
|
40 | 40 | |
|
41 | 41 | _DEFAULT_STYLE = { |
|
42 | 42 | 'stdout' : 'fore:#0000FF', |
|
43 | 43 | 'stderr' : 'fore:#007f00', |
|
44 | 44 | 'trace' : 'fore:#FF0000', |
|
45 | 45 | |
|
46 | 46 | 'default' : 'size:%d' % _DEFAULT_SIZE, |
|
47 | 47 | 'bracegood' : 'fore:#00AA00,back:#000000,bold', |
|
48 | 48 | 'bracebad' : 'fore:#FF0000,back:#000000,bold', |
|
49 | 49 | |
|
50 | 50 | # properties for the various Python lexer styles |
|
51 | 51 | 'comment' : 'fore:#007F00', |
|
52 | 52 | 'number' : 'fore:#007F7F', |
|
53 | 53 | 'string' : 'fore:#7F007F,italic', |
|
54 | 54 | 'char' : 'fore:#7F007F,italic', |
|
55 | 55 | 'keyword' : 'fore:#00007F,bold', |
|
56 | 56 | 'triple' : 'fore:#7F0000', |
|
57 | 57 | 'tripledouble' : 'fore:#7F0000', |
|
58 | 58 | 'class' : 'fore:#0000FF,bold,underline', |
|
59 | 59 | 'def' : 'fore:#007F7F,bold', |
|
60 | 60 | 'operator' : 'bold' |
|
61 | 61 | } |
|
62 | 62 | |
|
63 | 63 | # new style numbers |
|
64 | 64 | _STDOUT_STYLE = 15 |
|
65 | 65 | _STDERR_STYLE = 16 |
|
66 | 66 | _TRACE_STYLE = 17 |
|
67 | 67 | |
|
68 | 68 | |
|
69 | 69 | # system colors |
|
70 | 70 | #SYS_COLOUR_BACKGROUND = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND) |
|
71 | 71 | |
|
72 | 72 | #------------------------------------------------------------------------------- |
|
73 | 73 | # The console widget class |
|
74 | 74 | #------------------------------------------------------------------------------- |
|
75 | 75 | class ConsoleWidget(editwindow.EditWindow): |
|
76 | 76 | """ Specialized styled text control view for console-like workflow. |
|
77 | 77 | |
|
78 | 78 | This widget is mainly interested in dealing with the prompt and |
|
79 | 79 | keeping the cursor inside the editing line. |
|
80 | 80 | """ |
|
81 | 81 | |
|
82 | 82 | # This is where the title captured from the ANSI escape sequences are |
|
83 | 83 | # stored. |
|
84 | 84 | title = 'Console' |
|
85 | 85 | |
|
86 | 86 | # The buffer being edited. |
|
87 | 87 | def _set_input_buffer(self, string): |
|
88 | 88 | self.SetSelection(self.current_prompt_pos, self.GetLength()) |
|
89 | 89 | self.ReplaceSelection(string) |
|
90 | 90 | self.GotoPos(self.GetLength()) |
|
91 | 91 | |
|
92 | 92 | def _get_input_buffer(self): |
|
93 | 93 | """ Returns the text in current edit buffer. |
|
94 | 94 | """ |
|
95 | 95 | input_buffer = self.GetTextRange(self.current_prompt_pos, |
|
96 | 96 | self.GetLength()) |
|
97 | 97 | input_buffer = input_buffer.replace(LINESEP, '\n') |
|
98 | 98 | return input_buffer |
|
99 | 99 | |
|
100 | 100 | input_buffer = property(_get_input_buffer, _set_input_buffer) |
|
101 | 101 | |
|
102 | 102 | style = _DEFAULT_STYLE.copy() |
|
103 | 103 | |
|
104 | 104 | # Translation table from ANSI escape sequences to color. Override |
|
105 | 105 | # this to specify your colors. |
|
106 | 106 | ANSI_STYLES = {'0;30': [0, 'BLACK'], '0;31': [1, 'RED'], |
|
107 | 107 | '0;32': [2, 'GREEN'], '0;33': [3, 'BROWN'], |
|
108 | 108 | '0;34': [4, 'BLUE'], '0;35': [5, 'PURPLE'], |
|
109 | 109 | '0;36': [6, 'CYAN'], '0;37': [7, 'LIGHT GREY'], |
|
110 | 110 | '1;30': [8, 'DARK GREY'], '1;31': [9, 'RED'], |
|
111 | 111 | '1;32': [10, 'SEA GREEN'], '1;33': [11, 'YELLOW'], |
|
112 | 112 | '1;34': [12, 'LIGHT BLUE'], '1;35': |
|
113 | 113 | [13, 'MEDIUM VIOLET RED'], |
|
114 | 114 | '1;36': [14, 'LIGHT STEEL BLUE'], '1;37': [15, 'YELLOW']} |
|
115 | 115 | |
|
116 | 116 | # The color of the carret (call _apply_style() after setting) |
|
117 | 117 | carret_color = 'BLACK' |
|
118 | 118 | |
|
119 | 119 | # Store the last time a refresh was done |
|
120 | 120 | _last_refresh_time = 0 |
|
121 | 121 | |
|
122 | 122 | #-------------------------------------------------------------------------- |
|
123 | 123 | # Public API |
|
124 | 124 | #-------------------------------------------------------------------------- |
|
125 | 125 | |
|
126 | 126 | def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, |
|
127 | 127 | size=wx.DefaultSize, style=wx.WANTS_CHARS, ): |
|
128 | 128 | editwindow.EditWindow.__init__(self, parent, id, pos, size, style) |
|
129 | 129 | self._configure_scintilla() |
|
130 | 130 | |
|
131 | 131 | self.Bind(wx.EVT_KEY_DOWN, self._on_key_down) |
|
132 | 132 | self.Bind(wx.EVT_KEY_UP, self._on_key_up) |
|
133 | 133 | |
|
134 | 134 | |
|
135 | 135 | def write(self, text, refresh=True): |
|
136 | 136 | """ Write given text to buffer, while translating the ansi escape |
|
137 | 137 | sequences. |
|
138 | 138 | """ |
|
139 | 139 | # XXX: do not put print statements to sys.stdout/sys.stderr in |
|
140 | 140 | # this method, the print statements will call this method, as |
|
141 | 141 | # you will end up with an infinit loop |
|
142 | 142 | title = self.title_pat.split(text) |
|
143 | 143 | if len(title)>1: |
|
144 | 144 | self.title = title[-2] |
|
145 | 145 | |
|
146 | 146 | text = self.title_pat.sub('', text) |
|
147 | 147 | segments = self.color_pat.split(text) |
|
148 | 148 | segment = segments.pop(0) |
|
149 | 149 | self.GotoPos(self.GetLength()) |
|
150 | 150 | self.StartStyling(self.GetLength(), 0xFF) |
|
151 | 151 | try: |
|
152 | 152 | self.AppendText(segment) |
|
153 | 153 | except UnicodeDecodeError: |
|
154 | 154 | # XXX: Do I really want to skip the exception? |
|
155 | 155 | pass |
|
156 | 156 | |
|
157 | 157 | if segments: |
|
158 | 158 | for ansi_tag, text in zip(segments[::2], segments[1::2]): |
|
159 | 159 | self.StartStyling(self.GetLength(), 0xFF) |
|
160 | 160 | try: |
|
161 | 161 | self.AppendText(text) |
|
162 | 162 | except UnicodeDecodeError: |
|
163 | 163 | # XXX: Do I really want to skip the exception? |
|
164 | 164 | pass |
|
165 | 165 | |
|
166 | 166 | if ansi_tag not in self.ANSI_STYLES: |
|
167 | 167 | style = 0 |
|
168 | 168 | else: |
|
169 | 169 | style = self.ANSI_STYLES[ansi_tag][0] |
|
170 | 170 | |
|
171 | 171 | self.SetStyling(len(text), style) |
|
172 | 172 | |
|
173 | 173 | self.GotoPos(self.GetLength()) |
|
174 | 174 | if refresh: |
|
175 | 175 | current_time = time.time() |
|
176 | 176 | if current_time - self._last_refresh_time > 0.03: |
|
177 | 177 | if sys.platform == 'win32': |
|
178 | 178 | wx.SafeYield() |
|
179 | 179 | else: |
|
180 | 180 | wx.Yield() |
|
181 | 181 | # self.ProcessEvent(wx.PaintEvent()) |
|
182 | 182 | self._last_refresh_time = current_time |
|
183 | 183 | |
|
184 | 184 | |
|
185 | 185 | def new_prompt(self, prompt): |
|
186 | 186 | """ Prints a prompt at start of line, and move the start of the |
|
187 | 187 | current block there. |
|
188 | 188 | |
|
189 | 189 | The prompt can be given with ascii escape sequences. |
|
190 | 190 | """ |
|
191 | 191 | self.write(prompt, refresh=False) |
|
192 | 192 | # now we update our cursor giving end of prompt |
|
193 | 193 | self.current_prompt_pos = self.GetLength() |
|
194 | 194 | self.current_prompt_line = self.GetCurrentLine() |
|
195 | 195 | self.EnsureCaretVisible() |
|
196 | 196 | |
|
197 | 197 | |
|
198 | 198 | def scroll_to_bottom(self): |
|
199 | 199 | maxrange = self.GetScrollRange(wx.VERTICAL) |
|
200 | 200 | self.ScrollLines(maxrange) |
|
201 | 201 | |
|
202 | 202 | |
|
203 | 203 | def pop_completion(self, possibilities, offset=0): |
|
204 | 204 | """ Pops up an autocompletion menu. Offset is the offset |
|
205 | 205 | in characters of the position at which the menu should |
|
206 | 206 | appear, relativ to the cursor. |
|
207 | 207 | """ |
|
208 | 208 | self.AutoCompSetIgnoreCase(False) |
|
209 | 209 | self.AutoCompSetAutoHide(False) |
|
210 | 210 | self.AutoCompSetMaxHeight(len(possibilities)) |
|
211 | 211 | self.AutoCompShow(offset, " ".join(possibilities)) |
|
212 | 212 | |
|
213 | 213 | |
|
214 | 214 | def get_line_width(self): |
|
215 | 215 | """ Return the width of the line in characters. |
|
216 | 216 | """ |
|
217 | 217 | return self.GetSize()[0]/self.GetCharWidth() |
|
218 | 218 | |
|
219 | 219 | #-------------------------------------------------------------------------- |
|
220 | 220 | # EditWindow API |
|
221 | 221 | #-------------------------------------------------------------------------- |
|
222 | 222 | |
|
223 | 223 | def OnUpdateUI(self, event): |
|
224 | 224 | """ Override the OnUpdateUI of the EditWindow class, to prevent |
|
225 | 225 | syntax highlighting both for faster redraw, and for more |
|
226 | 226 | consistent look and feel. |
|
227 | 227 | """ |
|
228 | 228 | |
|
229 | 229 | #-------------------------------------------------------------------------- |
|
230 | 230 | # Private API |
|
231 | 231 | #-------------------------------------------------------------------------- |
|
232 | 232 | |
|
233 | 233 | def _apply_style(self): |
|
234 | 234 | """ Applies the colors for the different text elements and the |
|
235 | 235 | carret. |
|
236 | 236 | """ |
|
237 | 237 | self.SetCaretForeground(self.carret_color) |
|
238 | 238 | |
|
239 | 239 | #self.StyleClearAll() |
|
240 | 240 | self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, |
|
241 | 241 | "fore:#FF0000,back:#0000FF,bold") |
|
242 | 242 | self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, |
|
243 | 243 | "fore:#000000,back:#FF0000,bold") |
|
244 | 244 | |
|
245 | 245 | for style in self.ANSI_STYLES.values(): |
|
246 | 246 | self.StyleSetSpec(style[0], "bold,fore:%s" % style[1]) |
|
247 | 247 | |
|
248 | 248 | |
|
249 | 249 | def _configure_scintilla(self): |
|
250 | 250 | self.SetEOLMode(stc.STC_EOL_LF) |
|
251 | 251 | |
|
252 | 252 | # Ctrl"+" or Ctrl "-" can be used to zoomin/zoomout the text inside |
|
253 | 253 | # the widget |
|
254 | 254 | self.CmdKeyAssign(ord('+'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMIN) |
|
255 | 255 | self.CmdKeyAssign(ord('-'), stc.STC_SCMOD_CTRL, stc.STC_CMD_ZOOMOUT) |
|
256 | 256 | # Also allow Ctrl Shift "=" for poor non US keyboard users. |
|
257 | 257 | self.CmdKeyAssign(ord('='), stc.STC_SCMOD_CTRL|stc.STC_SCMOD_SHIFT, |
|
258 | 258 | stc.STC_CMD_ZOOMIN) |
|
259 | 259 | |
|
260 | 260 | # Keys: we need to clear some of the keys the that don't play |
|
261 | 261 | # well with a console. |
|
262 | 262 | self.CmdKeyClear(ord('D'), stc.STC_SCMOD_CTRL) |
|
263 | 263 | self.CmdKeyClear(ord('L'), stc.STC_SCMOD_CTRL) |
|
264 | 264 | self.CmdKeyClear(ord('T'), stc.STC_SCMOD_CTRL) |
|
265 | 265 | self.CmdKeyClear(ord('A'), stc.STC_SCMOD_CTRL) |
|
266 | 266 | |
|
267 | 267 | self.SetEOLMode(stc.STC_EOL_CRLF) |
|
268 | 268 | self.SetWrapMode(stc.STC_WRAP_CHAR) |
|
269 | 269 | self.SetWrapMode(stc.STC_WRAP_WORD) |
|
270 | 270 | self.SetBufferedDraw(True) |
|
271 | 271 | self.SetUseAntiAliasing(True) |
|
272 | 272 | self.SetLayoutCache(stc.STC_CACHE_PAGE) |
|
273 | 273 | self.SetUndoCollection(False) |
|
274 | 274 | self.SetUseTabs(True) |
|
275 | 275 | self.SetIndent(4) |
|
276 | 276 | self.SetTabWidth(4) |
|
277 | 277 | |
|
278 | 278 | # we don't want scintilla's autocompletion to choose |
|
279 | 279 | # automaticaly out of a single choice list, as we pop it up |
|
280 | 280 | # automaticaly |
|
281 | 281 | self.AutoCompSetChooseSingle(False) |
|
282 | 282 | self.AutoCompSetMaxHeight(10) |
|
283 | 283 | # XXX: this doesn't seem to have an effect. |
|
284 | 284 | self.AutoCompSetFillUps('\n') |
|
285 | 285 | |
|
286 | 286 | self.SetMargins(3, 3) #text is moved away from border with 3px |
|
287 | 287 | # Suppressing Scintilla margins |
|
288 | 288 | self.SetMarginWidth(0, 0) |
|
289 | 289 | self.SetMarginWidth(1, 0) |
|
290 | 290 | self.SetMarginWidth(2, 0) |
|
291 | 291 | |
|
292 | 292 | self._apply_style() |
|
293 | 293 | |
|
294 | 294 | # Xterm escape sequences |
|
295 | 295 | self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') |
|
296 | 296 | self.title_pat = re.compile('\x1b]0;(.*?)\x07') |
|
297 | 297 | |
|
298 | 298 | #self.SetEdgeMode(stc.STC_EDGE_LINE) |
|
299 | 299 | #self.SetEdgeColumn(80) |
|
300 | 300 | |
|
301 | 301 | # styles |
|
302 | 302 | p = self.style |
|
303 | 303 | self.StyleSetSpec(stc.STC_STYLE_DEFAULT, p['default']) |
|
304 | 304 | self.StyleClearAll() |
|
305 | 305 | self.StyleSetSpec(_STDOUT_STYLE, p['stdout']) |
|
306 | 306 | self.StyleSetSpec(_STDERR_STYLE, p['stderr']) |
|
307 | 307 | self.StyleSetSpec(_TRACE_STYLE, p['trace']) |
|
308 | 308 | |
|
309 | 309 | self.StyleSetSpec(stc.STC_STYLE_BRACELIGHT, p['bracegood']) |
|
310 | 310 | self.StyleSetSpec(stc.STC_STYLE_BRACEBAD, p['bracebad']) |
|
311 | 311 | self.StyleSetSpec(stc.STC_P_COMMENTLINE, p['comment']) |
|
312 | 312 | self.StyleSetSpec(stc.STC_P_NUMBER, p['number']) |
|
313 | 313 | self.StyleSetSpec(stc.STC_P_STRING, p['string']) |
|
314 | 314 | self.StyleSetSpec(stc.STC_P_CHARACTER, p['char']) |
|
315 | 315 | self.StyleSetSpec(stc.STC_P_WORD, p['keyword']) |
|
316 | 316 | self.StyleSetSpec(stc.STC_P_WORD2, p['keyword']) |
|
317 | 317 | self.StyleSetSpec(stc.STC_P_TRIPLE, p['triple']) |
|
318 | 318 | self.StyleSetSpec(stc.STC_P_TRIPLEDOUBLE, p['tripledouble']) |
|
319 | 319 | self.StyleSetSpec(stc.STC_P_CLASSNAME, p['class']) |
|
320 | 320 | self.StyleSetSpec(stc.STC_P_DEFNAME, p['def']) |
|
321 | 321 | self.StyleSetSpec(stc.STC_P_OPERATOR, p['operator']) |
|
322 | 322 | self.StyleSetSpec(stc.STC_P_COMMENTBLOCK, p['comment']) |
|
323 | 323 | |
|
324 | 324 | def _on_key_down(self, event, skip=True): |
|
325 | 325 | """ Key press callback used for correcting behavior for |
|
326 | 326 | console-like interfaces: the cursor is constraint to be after |
|
327 | 327 | the last prompt. |
|
328 | 328 | |
|
329 | 329 | Return True if event as been catched. |
|
330 | 330 | """ |
|
331 | 331 | catched = True |
|
332 | 332 | # Intercept some specific keys. |
|
333 | 333 | if event.KeyCode == ord('L') and event.ControlDown() : |
|
334 | 334 | self.scroll_to_bottom() |
|
335 | 335 | elif event.KeyCode == ord('K') and event.ControlDown() : |
|
336 | 336 | self.input_buffer = '' |
|
337 | 337 | elif event.KeyCode == ord('A') and event.ControlDown() : |
|
338 | 338 | self.GotoPos(self.GetLength()) |
|
339 | 339 | self.SetSelectionStart(self.current_prompt_pos) |
|
340 | 340 | self.SetSelectionEnd(self.GetCurrentPos()) |
|
341 | 341 | catched = True |
|
342 | 342 | elif event.KeyCode == ord('E') and event.ControlDown() : |
|
343 | 343 | self.GotoPos(self.GetLength()) |
|
344 | 344 | catched = True |
|
345 | 345 | elif event.KeyCode == wx.WXK_PAGEUP: |
|
346 | 346 | self.ScrollPages(-1) |
|
347 | 347 | elif event.KeyCode == wx.WXK_PAGEDOWN: |
|
348 | 348 | self.ScrollPages(1) |
|
349 | 349 | elif event.KeyCode == wx.WXK_UP and event.ShiftDown(): |
|
350 | 350 | self.ScrollLines(-1) |
|
351 | 351 | elif event.KeyCode == wx.WXK_DOWN and event.ShiftDown(): |
|
352 | 352 | self.ScrollLines(1) |
|
353 | 353 | else: |
|
354 | 354 | catched = False |
|
355 | 355 | |
|
356 | 356 | if self.AutoCompActive(): |
|
357 | 357 | event.Skip() |
|
358 | 358 | else: |
|
359 | 359 | if event.KeyCode in (13, wx.WXK_NUMPAD_ENTER) and \ |
|
360 | 360 | event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN): |
|
361 | 361 | catched = True |
|
362 | 362 | self.CallTipCancel() |
|
363 | 363 | self.write('\n', refresh=False) |
|
364 | 364 | # Under windows scintilla seems to be doing funny stuff to the |
|
365 | 365 | # line returns here, but the getter for input_buffer filters |
|
366 | 366 | # this out. |
|
367 | 367 | if sys.platform == 'win32': |
|
368 | 368 | self.input_buffer = self.input_buffer |
|
369 | 369 | self._on_enter() |
|
370 | 370 | |
|
371 | 371 | elif event.KeyCode == wx.WXK_HOME: |
|
372 | 372 | if event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN): |
|
373 | 373 | self.GotoPos(self.current_prompt_pos) |
|
374 | 374 | catched = True |
|
375 | 375 | |
|
376 | 376 | elif event.Modifiers == wx.MOD_SHIFT: |
|
377 | 377 | # FIXME: This behavior is not ideal: if the selection |
|
378 | 378 | # is already started, it will jump. |
|
379 | 379 | self.SetSelectionStart(self.current_prompt_pos) |
|
380 | 380 | self.SetSelectionEnd(self.GetCurrentPos()) |
|
381 | 381 | catched = True |
|
382 | 382 | |
|
383 | 383 | elif event.KeyCode == wx.WXK_UP: |
|
384 | 384 | if self.GetCurrentLine() > self.current_prompt_line: |
|
385 | 385 | if self.GetCurrentLine() == self.current_prompt_line + 1 \ |
|
386 | 386 | and self.GetColumn(self.GetCurrentPos()) < \ |
|
387 | 387 | self.GetColumn(self.current_prompt_pos): |
|
388 | 388 | self.GotoPos(self.current_prompt_pos) |
|
389 | 389 | else: |
|
390 | 390 | event.Skip() |
|
391 | 391 | catched = True |
|
392 | 392 | |
|
393 | 393 | elif event.KeyCode in (wx.WXK_LEFT, wx.WXK_BACK): |
|
394 | 394 | if self.GetCurrentPos() > self.current_prompt_pos: |
|
395 | 395 | event.Skip() |
|
396 | 396 | catched = True |
|
397 | 397 | |
|
398 | 398 | if skip and not catched: |
|
399 | 399 | # Put the cursor back in the edit region |
|
400 | 400 | if self.GetCurrentPos() < self.current_prompt_pos: |
|
401 | 401 | self.GotoPos(self.current_prompt_pos) |
|
402 | 402 | else: |
|
403 | 403 | event.Skip() |
|
404 | 404 | |
|
405 | 405 | return catched |
|
406 | 406 | |
|
407 | 407 | |
|
408 | 408 | def _on_key_up(self, event, skip=True): |
|
409 | 409 | """ If cursor is outside the editing region, put it back. |
|
410 | 410 | """ |
|
411 | 411 | event.Skip() |
|
412 | 412 | if self.GetCurrentPos() < self.current_prompt_pos: |
|
413 | 413 | self.GotoPos(self.current_prompt_pos) |
|
414 | 414 | |
|
415 | 415 | |
|
416 | 416 | |
|
417 | 417 | if __name__ == '__main__': |
|
418 | 418 | # Some simple code to test the console widget. |
|
419 | 419 | class MainWindow(wx.Frame): |
|
420 | 420 | def __init__(self, parent, id, title): |
|
421 | 421 | wx.Frame.__init__(self, parent, id, title, size=(300,250)) |
|
422 | 422 | self._sizer = wx.BoxSizer(wx.VERTICAL) |
|
423 | 423 | self.console_widget = ConsoleWidget(self) |
|
424 | 424 | self._sizer.Add(self.console_widget, 1, wx.EXPAND) |
|
425 | 425 | self.SetSizer(self._sizer) |
|
426 | 426 | self.SetAutoLayout(1) |
|
427 | 427 | self.Show(True) |
|
428 | 428 | |
|
429 | 429 | app = wx.PySimpleApp() |
|
430 | 430 | w = MainWindow(None, wx.ID_ANY, 'ConsoleWidget') |
|
431 | 431 | w.SetSize((780, 460)) |
|
432 | 432 | w.Show() |
|
433 | 433 | |
|
434 | 434 | app.MainLoop() |
|
435 | 435 | |
|
436 | 436 |
@@ -1,526 +1,557 b'' | |||
|
1 | 1 | # encoding: utf-8 -*- test-case-name: |
|
2 | 2 | # FIXME: Need to add tests. |
|
3 | 3 | # ipython1.frontend.wx.tests.test_wx_frontend -*- |
|
4 | 4 | |
|
5 | 5 | """Classes to provide a Wx frontend to the |
|
6 | 6 | IPython.kernel.core.interpreter. |
|
7 | 7 | |
|
8 | 8 | This class inherits from ConsoleWidget, that provides a console-like |
|
9 | 9 | widget to provide a text-rendering widget suitable for a terminal. |
|
10 | 10 | """ |
|
11 | 11 | |
|
12 | 12 | __docformat__ = "restructuredtext en" |
|
13 | 13 | |
|
14 | 14 | #------------------------------------------------------------------------------- |
|
15 | 15 | # Copyright (C) 2008 The IPython Development Team |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #------------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #------------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #------------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | # Major library imports |
|
26 | 26 | import re |
|
27 | 27 | import __builtin__ |
|
28 | from time import sleep | |
|
29 | 28 | import sys |
|
30 | 29 | from threading import Lock |
|
31 | 30 | import string |
|
32 | 31 | |
|
33 | 32 | import wx |
|
34 | 33 | from wx import stc |
|
35 | 34 | |
|
36 | 35 | # Ipython-specific imports. |
|
37 | 36 | from IPython.frontend._process import PipedProcess |
|
38 | 37 | from console_widget import ConsoleWidget |
|
39 | 38 | from IPython.frontend.prefilterfrontend import PrefilterFrontEnd |
|
40 | 39 | |
|
41 | 40 | #------------------------------------------------------------------------------- |
|
42 | 41 | # Constants |
|
43 | 42 | #------------------------------------------------------------------------------- |
|
44 | 43 | |
|
45 | 44 | _COMPLETE_BUFFER_BG = '#FAFAF1' # Nice green |
|
46 | 45 | _INPUT_BUFFER_BG = '#FDFFD3' # Nice yellow |
|
47 | 46 | _ERROR_BG = '#FFF1F1' # Nice red |
|
48 | 47 | |
|
49 | 48 | _COMPLETE_BUFFER_MARKER = 31 |
|
50 | 49 | _ERROR_MARKER = 30 |
|
51 | 50 | _INPUT_MARKER = 29 |
|
52 | 51 | |
|
53 | 52 | prompt_in1 = \ |
|
54 | 53 | '\n\x01\x1b[0;34m\x02In [\x01\x1b[1;34m\x02$number\x01\x1b[0;34m\x02]: \x01\x1b[0m\x02' |
|
55 | 54 | |
|
56 | 55 | prompt_out = \ |
|
57 | 56 | '\x01\x1b[0;31m\x02Out[\x01\x1b[1;31m\x02$number\x01\x1b[0;31m\x02]: \x01\x1b[0m\x02' |
|
58 | 57 | |
|
59 | 58 | #------------------------------------------------------------------------------- |
|
60 | 59 | # Classes to implement the Wx frontend |
|
61 | 60 | #------------------------------------------------------------------------------- |
|
62 | 61 | class WxController(ConsoleWidget, PrefilterFrontEnd): |
|
63 | 62 | """Classes to provide a Wx frontend to the |
|
64 | 63 | IPython.kernel.core.interpreter. |
|
65 | 64 | |
|
66 | 65 | This class inherits from ConsoleWidget, that provides a console-like |
|
67 | 66 | widget to provide a text-rendering widget suitable for a terminal. |
|
68 | 67 | """ |
|
69 | 68 | |
|
70 | 69 | output_prompt_template = string.Template(prompt_out) |
|
71 | 70 | |
|
72 | 71 | input_prompt_template = string.Template(prompt_in1) |
|
73 | 72 | |
|
74 | 73 | # Print debug info on what is happening to the console. |
|
75 | 74 | debug = False |
|
76 | 75 | |
|
77 | 76 | # The title of the terminal, as captured through the ANSI escape |
|
78 | 77 | # sequences. |
|
79 | 78 | def _set_title(self, title): |
|
80 | 79 | return self.Parent.SetTitle(title) |
|
81 | 80 | |
|
82 | 81 | def _get_title(self): |
|
83 | 82 | return self.Parent.GetTitle() |
|
84 | 83 | |
|
85 | 84 | title = property(_get_title, _set_title) |
|
86 | 85 | |
|
87 | 86 | |
|
88 | 87 | # The buffer being edited. |
|
89 | 88 | # We are duplicating the definition here because of multiple |
|
90 | 89 | # inheritence |
|
91 | 90 | def _set_input_buffer(self, string): |
|
92 | 91 | ConsoleWidget._set_input_buffer(self, string) |
|
93 | 92 | self._colorize_input_buffer() |
|
94 | 93 | |
|
95 | 94 | def _get_input_buffer(self): |
|
96 | 95 | """ Returns the text in current edit buffer. |
|
97 | 96 | """ |
|
98 | 97 | return ConsoleWidget._get_input_buffer(self) |
|
99 | 98 | |
|
100 | 99 | input_buffer = property(_get_input_buffer, _set_input_buffer) |
|
101 | 100 | |
|
102 | 101 | |
|
103 | 102 | #-------------------------------------------------------------------------- |
|
104 | 103 | # Private Attributes |
|
105 | 104 | #-------------------------------------------------------------------------- |
|
106 | 105 | |
|
107 | 106 | # A flag governing the behavior of the input. Can be: |
|
108 | 107 | # |
|
109 | 108 | # 'readline' for readline-like behavior with a prompt |
|
110 | 109 | # and an edit buffer. |
|
111 | 110 | # 'raw_input' similar to readline, but triggered by a raw-input |
|
112 | 111 | # call. Can be used by subclasses to act differently. |
|
113 | 112 | # 'subprocess' for sending the raw input directly to a |
|
114 | 113 | # subprocess. |
|
115 | 114 | # 'buffering' for buffering of the input, that will be used |
|
116 | 115 | # when the input state switches back to another state. |
|
117 | 116 | _input_state = 'readline' |
|
118 | 117 | |
|
119 | 118 | # Attribute to store reference to the pipes of a subprocess, if we |
|
120 | 119 | # are running any. |
|
121 | 120 | _running_process = False |
|
122 | 121 | |
|
123 | 122 | # A queue for writing fast streams to the screen without flooding the |
|
124 | 123 | # event loop |
|
125 | 124 | _out_buffer = [] |
|
126 | 125 | |
|
127 | 126 | # A lock to lock the _out_buffer to make sure we don't empty it |
|
128 | 127 | # while it is being swapped |
|
129 | 128 | _out_buffer_lock = Lock() |
|
130 | 129 | |
|
131 | 130 | # The different line markers used to higlight the prompts. |
|
132 | 131 | _markers = dict() |
|
133 | 132 | |
|
134 | 133 | #-------------------------------------------------------------------------- |
|
135 | 134 | # Public API |
|
136 | 135 | #-------------------------------------------------------------------------- |
|
137 | 136 | |
|
138 | 137 | def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, |
|
139 | 138 | size=wx.DefaultSize, |
|
140 | 139 | style=wx.CLIP_CHILDREN|wx.WANTS_CHARS, |
|
141 | 140 | *args, **kwds): |
|
142 | 141 | """ Create Shell instance. |
|
143 | 142 | """ |
|
144 | 143 | ConsoleWidget.__init__(self, parent, id, pos, size, style) |
|
145 | 144 | PrefilterFrontEnd.__init__(self, **kwds) |
|
146 | 145 | |
|
147 | 146 | # Stick in our own raw_input: |
|
148 | 147 | self.ipython0.raw_input = self.raw_input |
|
149 | 148 | |
|
150 | 149 | # Marker for complete buffer. |
|
151 | 150 | self.MarkerDefine(_COMPLETE_BUFFER_MARKER, stc.STC_MARK_BACKGROUND, |
|
152 | 151 | background=_COMPLETE_BUFFER_BG) |
|
153 | 152 | # Marker for current input buffer. |
|
154 | 153 | self.MarkerDefine(_INPUT_MARKER, stc.STC_MARK_BACKGROUND, |
|
155 | 154 | background=_INPUT_BUFFER_BG) |
|
156 | 155 | # Marker for tracebacks. |
|
157 | 156 | self.MarkerDefine(_ERROR_MARKER, stc.STC_MARK_BACKGROUND, |
|
158 | 157 | background=_ERROR_BG) |
|
159 | 158 | |
|
160 | 159 | # A time for flushing the write buffer |
|
161 | 160 | BUFFER_FLUSH_TIMER_ID = 100 |
|
162 | 161 | self._buffer_flush_timer = wx.Timer(self, BUFFER_FLUSH_TIMER_ID) |
|
163 | 162 | wx.EVT_TIMER(self, BUFFER_FLUSH_TIMER_ID, self._buffer_flush) |
|
164 | 163 | |
|
165 | 164 | if 'debug' in kwds: |
|
166 | 165 | self.debug = kwds['debug'] |
|
167 | 166 | kwds.pop('debug') |
|
168 | 167 | |
|
169 | 168 | # Inject self in namespace, for debug |
|
170 | 169 | if self.debug: |
|
171 | 170 | self.shell.user_ns['self'] = self |
|
172 | 171 | # Inject our own raw_input in namespace |
|
173 | 172 | self.shell.user_ns['raw_input'] = self.raw_input |
|
174 | 173 | |
|
175 | 174 | |
|
176 | 175 | def raw_input(self, prompt=''): |
|
177 | 176 | """ A replacement from python's raw_input. |
|
178 | 177 | """ |
|
179 | 178 | self.new_prompt(prompt) |
|
180 | 179 | self._input_state = 'raw_input' |
|
181 | 180 | if hasattr(self, '_cursor'): |
|
182 | 181 | del self._cursor |
|
183 | 182 | self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS)) |
|
184 | 183 | self.__old_on_enter = self._on_enter |
|
185 | 184 | event_loop = wx.EventLoop() |
|
186 | 185 | def my_on_enter(): |
|
187 | 186 | event_loop.Exit() |
|
188 | 187 | self._on_enter = my_on_enter |
|
189 | 188 | # XXX: Running a separate event_loop. Ugly. |
|
190 | 189 | event_loop.Run() |
|
191 | 190 | self._on_enter = self.__old_on_enter |
|
192 | 191 | self._input_state = 'buffering' |
|
193 | 192 | self._cursor = wx.BusyCursor() |
|
194 | 193 | return self.input_buffer.rstrip('\n') |
|
195 | 194 | |
|
196 | 195 | |
|
197 | 196 | def system_call(self, command_string): |
|
198 | 197 | self._input_state = 'subprocess' |
|
199 | 198 | event_loop = wx.EventLoop() |
|
200 | 199 | def _end_system_call(): |
|
201 | 200 | self._input_state = 'buffering' |
|
202 | 201 | self._running_process = False |
|
203 | 202 | event_loop.Exit() |
|
204 | 203 | |
|
205 | 204 | self._running_process = PipedProcess(command_string, |
|
206 | 205 | out_callback=self.buffered_write, |
|
207 | 206 | end_callback = _end_system_call) |
|
208 | 207 | self._running_process.start() |
|
209 | 208 | # XXX: Running a separate event_loop. Ugly. |
|
210 | 209 | event_loop.Run() |
|
211 | 210 | # Be sure to flush the buffer. |
|
212 | 211 | self._buffer_flush(event=None) |
|
213 | 212 | |
|
214 | 213 | |
|
215 | 214 | def do_calltip(self): |
|
216 | 215 | """ Analyse current and displays useful calltip for it. |
|
217 | 216 | """ |
|
218 | 217 | if self.debug: |
|
219 | 218 | print >>sys.__stdout__, "do_calltip" |
|
220 | 219 | separators = re.compile('[\s\{\}\[\]\(\)\= ,:]') |
|
221 | 220 | symbol = self.input_buffer |
|
222 | 221 | symbol_string = separators.split(symbol)[-1] |
|
223 | 222 | base_symbol_string = symbol_string.split('.')[0] |
|
224 | 223 | if base_symbol_string in self.shell.user_ns: |
|
225 | 224 | symbol = self.shell.user_ns[base_symbol_string] |
|
226 | 225 | elif base_symbol_string in self.shell.user_global_ns: |
|
227 | 226 | symbol = self.shell.user_global_ns[base_symbol_string] |
|
228 | 227 | elif base_symbol_string in __builtin__.__dict__: |
|
229 | 228 | symbol = __builtin__.__dict__[base_symbol_string] |
|
230 | 229 | else: |
|
231 | 230 | return False |
|
232 | 231 | try: |
|
233 | 232 | for name in symbol_string.split('.')[1:] + ['__doc__']: |
|
234 | 233 | symbol = getattr(symbol, name) |
|
235 | 234 | self.AutoCompCancel() |
|
236 | 235 | # Check that the symbol can indeed be converted to a string: |
|
237 | 236 | symbol += '' |
|
238 | 237 | wx.CallAfter(self.CallTipShow, self.GetCurrentPos(), symbol) |
|
239 | 238 | except: |
|
240 | 239 | # The retrieve symbol couldn't be converted to a string |
|
241 | 240 | pass |
|
242 | 241 | |
|
243 | 242 | |
|
244 | 243 | def _popup_completion(self, create=False): |
|
245 | 244 | """ Updates the popup completion menu if it exists. If create is |
|
246 | 245 | true, open the menu. |
|
247 | 246 | """ |
|
248 | 247 | if self.debug: |
|
249 | 248 | print >>sys.__stdout__, "_popup_completion" |
|
250 | 249 | line = self.input_buffer |
|
251 | 250 | if (self.AutoCompActive() and line and not line[-1] == '.') \ |
|
252 | 251 | or create==True: |
|
253 | 252 | suggestion, completions = self.complete(line) |
|
254 | 253 | offset=0 |
|
255 | 254 | if completions: |
|
256 | 255 | complete_sep = re.compile('[\s\{\}\[\]\(\)\= ,:]') |
|
257 | 256 | residual = complete_sep.split(line)[-1] |
|
258 | 257 | offset = len(residual) |
|
259 | 258 | self.pop_completion(completions, offset=offset) |
|
260 | 259 | if self.debug: |
|
261 | 260 | print >>sys.__stdout__, completions |
|
262 | 261 | |
|
263 | 262 | |
|
264 | 263 | def buffered_write(self, text): |
|
265 | 264 | """ A write method for streams, that caches the stream in order |
|
266 | 265 | to avoid flooding the event loop. |
|
267 | 266 | |
|
268 | 267 | This can be called outside of the main loop, in separate |
|
269 | 268 | threads. |
|
270 | 269 | """ |
|
271 | 270 | self._out_buffer_lock.acquire() |
|
272 | 271 | self._out_buffer.append(text) |
|
273 | 272 | self._out_buffer_lock.release() |
|
274 | 273 | if not self._buffer_flush_timer.IsRunning(): |
|
275 | 274 | wx.CallAfter(self._buffer_flush_timer.Start, |
|
276 | 275 | milliseconds=100, oneShot=True) |
|
277 | 276 | |
|
278 | 277 | |
|
278 | def execute_command(self, command, hidden=False): | |
|
279 | """ Execute a command, not only in the model, but also in the | |
|
280 | view. | |
|
281 | """ | |
|
282 | if hidden: | |
|
283 | return self.shell.execute(command) | |
|
284 | else: | |
|
285 | # XXX: we are not storing the input buffer previous to the | |
|
286 | # execution, as this forces us to run the execution | |
|
287 | # input_buffer a yield, which is not good. | |
|
288 | ##current_buffer = self.shell.control.input_buffer | |
|
289 | command = command.rstrip() | |
|
290 | if len(command.split('\n')) > 1: | |
|
291 | # The input command is several lines long, we need to | |
|
292 | # force the execution to happen | |
|
293 | command += '\n' | |
|
294 | cleaned_command = self.prefilter_input(command) | |
|
295 | self.input_buffer = command | |
|
296 | # Do not use wx.Yield() (aka GUI.process_events()) to avoid | |
|
297 | # recursive yields. | |
|
298 | self.ProcessEvent(wx.PaintEvent()) | |
|
299 | self.write('\n') | |
|
300 | if not self.is_complete(cleaned_command + '\n'): | |
|
301 | self._colorize_input_buffer() | |
|
302 | self.render_error('Incomplete or invalid input') | |
|
303 | self.new_prompt(self.input_prompt_template.substitute( | |
|
304 | number=(self.last_result['number'] + 1))) | |
|
305 | return False | |
|
306 | self._on_enter() | |
|
307 | return True | |
|
308 | ||
|
309 | ||
|
279 | 310 | #-------------------------------------------------------------------------- |
|
280 | 311 | # LineFrontEnd interface |
|
281 | 312 | #-------------------------------------------------------------------------- |
|
282 | 313 | |
|
283 | 314 | def execute(self, python_string, raw_string=None): |
|
284 | 315 | self._input_state = 'buffering' |
|
285 | 316 | self.CallTipCancel() |
|
286 | 317 | self._cursor = wx.BusyCursor() |
|
287 | 318 | if raw_string is None: |
|
288 | 319 | raw_string = python_string |
|
289 | 320 | end_line = self.current_prompt_line \ |
|
290 | 321 | + max(1, len(raw_string.split('\n'))-1) |
|
291 | 322 | for i in range(self.current_prompt_line, end_line): |
|
292 | 323 | if i in self._markers: |
|
293 | 324 | self.MarkerDeleteHandle(self._markers[i]) |
|
294 | 325 | self._markers[i] = self.MarkerAdd(i, _COMPLETE_BUFFER_MARKER) |
|
295 | 326 | # Use a callafter to update the display robustly under windows |
|
296 | 327 | def callback(): |
|
297 | 328 | self.GotoPos(self.GetLength()) |
|
298 | 329 | PrefilterFrontEnd.execute(self, python_string, |
|
299 | 330 | raw_string=raw_string) |
|
300 | 331 | wx.CallAfter(callback) |
|
301 | 332 | |
|
302 | 333 | def save_output_hooks(self): |
|
303 | 334 | self.__old_raw_input = __builtin__.raw_input |
|
304 | 335 | PrefilterFrontEnd.save_output_hooks(self) |
|
305 | 336 | |
|
306 | 337 | def capture_output(self): |
|
307 | 338 | self.SetLexer(stc.STC_LEX_NULL) |
|
308 | 339 | PrefilterFrontEnd.capture_output(self) |
|
309 | 340 | __builtin__.raw_input = self.raw_input |
|
310 | 341 | |
|
311 | 342 | |
|
312 | 343 | def release_output(self): |
|
313 | 344 | __builtin__.raw_input = self.__old_raw_input |
|
314 | 345 | PrefilterFrontEnd.release_output(self) |
|
315 | 346 | self.SetLexer(stc.STC_LEX_PYTHON) |
|
316 | 347 | |
|
317 | 348 | |
|
318 | 349 | def after_execute(self): |
|
319 | 350 | PrefilterFrontEnd.after_execute(self) |
|
320 | 351 | # Clear the wait cursor |
|
321 | 352 | if hasattr(self, '_cursor'): |
|
322 | 353 | del self._cursor |
|
323 | 354 | self.SetCursor(wx.StockCursor(wx.CURSOR_CHAR)) |
|
324 | 355 | |
|
325 | 356 | |
|
326 | 357 | def show_traceback(self): |
|
327 | 358 | start_line = self.GetCurrentLine() |
|
328 | 359 | PrefilterFrontEnd.show_traceback(self) |
|
329 | 360 | self.ProcessEvent(wx.PaintEvent()) |
|
330 | 361 | #wx.Yield() |
|
331 | 362 | for i in range(start_line, self.GetCurrentLine()): |
|
332 | 363 | self._markers[i] = self.MarkerAdd(i, _ERROR_MARKER) |
|
333 | 364 | |
|
334 | 365 | |
|
335 | 366 | #-------------------------------------------------------------------------- |
|
336 | 367 | # FrontEndBase interface |
|
337 | 368 | #-------------------------------------------------------------------------- |
|
338 | 369 | |
|
339 | 370 | def render_error(self, e): |
|
340 | 371 | start_line = self.GetCurrentLine() |
|
341 | 372 | self.write('\n' + e + '\n') |
|
342 | 373 | for i in range(start_line, self.GetCurrentLine()): |
|
343 | 374 | self._markers[i] = self.MarkerAdd(i, _ERROR_MARKER) |
|
344 | 375 | |
|
345 | 376 | |
|
346 | 377 | #-------------------------------------------------------------------------- |
|
347 | 378 | # ConsoleWidget interface |
|
348 | 379 | #-------------------------------------------------------------------------- |
|
349 | 380 | |
|
350 | 381 | def new_prompt(self, prompt): |
|
351 | 382 | """ Display a new prompt, and start a new input buffer. |
|
352 | 383 | """ |
|
353 | 384 | self._input_state = 'readline' |
|
354 | 385 | ConsoleWidget.new_prompt(self, prompt) |
|
355 | 386 | i = self.current_prompt_line |
|
356 | 387 | self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER) |
|
357 | 388 | |
|
358 | 389 | |
|
359 | 390 | def write(self, *args, **kwargs): |
|
360 | 391 | # Avoid multiple inheritence, be explicit about which |
|
361 | 392 | # parent method class gets called |
|
362 | 393 | ConsoleWidget.write(self, *args, **kwargs) |
|
363 | 394 | |
|
364 | 395 | |
|
365 | 396 | def _on_key_down(self, event, skip=True): |
|
366 | 397 | """ Capture the character events, let the parent |
|
367 | 398 | widget handle them, and put our logic afterward. |
|
368 | 399 | """ |
|
369 | 400 | # FIXME: This method needs to be broken down in smaller ones. |
|
370 | 401 | current_line_number = self.GetCurrentLine() |
|
371 | 402 | if event.KeyCode in (ord('c'), ord('C')) and event.ControlDown(): |
|
372 | 403 | # Capture Control-C |
|
373 | 404 | if self._input_state == 'subprocess': |
|
374 | 405 | if self.debug: |
|
375 | 406 | print >>sys.__stderr__, 'Killing running process' |
|
376 | 407 | if hasattr(self._running_process, 'process'): |
|
377 | 408 | self._running_process.process.kill() |
|
378 | 409 | elif self._input_state == 'buffering': |
|
379 | 410 | if self.debug: |
|
380 | 411 | print >>sys.__stderr__, 'Raising KeyboardInterrupt' |
|
381 | 412 | raise KeyboardInterrupt |
|
382 | 413 | # XXX: We need to make really sure we |
|
383 | 414 | # get back to a prompt. |
|
384 | 415 | elif self._input_state == 'subprocess' and ( |
|
385 | 416 | ( event.KeyCode<256 and |
|
386 | 417 | not event.ControlDown() ) |
|
387 | 418 | or |
|
388 | 419 | ( event.KeyCode in (ord('d'), ord('D')) and |
|
389 | 420 | event.ControlDown())): |
|
390 | 421 | # We are running a process, we redirect keys. |
|
391 | 422 | ConsoleWidget._on_key_down(self, event, skip=skip) |
|
392 | 423 | char = chr(event.KeyCode) |
|
393 | 424 | # Deal with some inconsistency in wx keycodes: |
|
394 | 425 | if char == '\r': |
|
395 | 426 | char = '\n' |
|
396 | 427 | elif not event.ShiftDown(): |
|
397 | 428 | char = char.lower() |
|
398 | 429 | if event.ControlDown() and event.KeyCode in (ord('d'), ord('D')): |
|
399 | 430 | char = '\04' |
|
400 | 431 | self._running_process.process.stdin.write(char) |
|
401 | 432 | self._running_process.process.stdin.flush() |
|
402 | 433 | elif event.KeyCode in (ord('('), 57, 53): |
|
403 | 434 | # Calltips |
|
404 | 435 | event.Skip() |
|
405 | 436 | self.do_calltip() |
|
406 | 437 | elif self.AutoCompActive() and not event.KeyCode == ord('\t'): |
|
407 | 438 | event.Skip() |
|
408 | 439 | if event.KeyCode in (wx.WXK_BACK, wx.WXK_DELETE): |
|
409 | 440 | wx.CallAfter(self._popup_completion, create=True) |
|
410 | 441 | elif not event.KeyCode in (wx.WXK_UP, wx.WXK_DOWN, wx.WXK_LEFT, |
|
411 | 442 | wx.WXK_RIGHT, wx.WXK_ESCAPE): |
|
412 | 443 | wx.CallAfter(self._popup_completion) |
|
413 | 444 | else: |
|
414 | 445 | # Up history |
|
415 | 446 | if event.KeyCode == wx.WXK_UP and ( |
|
416 | 447 | ( current_line_number == self.current_prompt_line and |
|
417 | 448 | event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN) ) |
|
418 | 449 | or event.ControlDown() ): |
|
419 | 450 | new_buffer = self.get_history_previous( |
|
420 | 451 | self.input_buffer) |
|
421 | 452 | if new_buffer is not None: |
|
422 | 453 | self.input_buffer = new_buffer |
|
423 | 454 | if self.GetCurrentLine() > self.current_prompt_line: |
|
424 | 455 | # Go to first line, for seemless history up. |
|
425 | 456 | self.GotoPos(self.current_prompt_pos) |
|
426 | 457 | # Down history |
|
427 | 458 | elif event.KeyCode == wx.WXK_DOWN and ( |
|
428 | 459 | ( current_line_number == self.LineCount -1 and |
|
429 | 460 | event.Modifiers in (wx.MOD_NONE, wx.MOD_WIN) ) |
|
430 | 461 | or event.ControlDown() ): |
|
431 | 462 | new_buffer = self.get_history_next() |
|
432 | 463 | if new_buffer is not None: |
|
433 | 464 | self.input_buffer = new_buffer |
|
434 | 465 | # Tab-completion |
|
435 | 466 | elif event.KeyCode == ord('\t'): |
|
436 | 467 | current_line, current_line_number = self.CurLine |
|
437 | 468 | if not re.match(r'^\s*$', current_line): |
|
438 | 469 | self.complete_current_input() |
|
439 | 470 | if self.AutoCompActive(): |
|
440 | 471 | wx.CallAfter(self._popup_completion, create=True) |
|
441 | 472 | else: |
|
442 | 473 | event.Skip() |
|
443 | 474 | else: |
|
444 | 475 | ConsoleWidget._on_key_down(self, event, skip=skip) |
|
445 | 476 | |
|
446 | 477 | |
|
447 | 478 | def _on_key_up(self, event, skip=True): |
|
448 | 479 | """ Called when any key is released. |
|
449 | 480 | """ |
|
450 | 481 | if event.KeyCode in (59, ord('.')): |
|
451 | 482 | # Intercepting '.' |
|
452 | 483 | event.Skip() |
|
453 | 484 | wx.CallAfter(self._popup_completion, create=True) |
|
454 | 485 | else: |
|
455 | 486 | ConsoleWidget._on_key_up(self, event, skip=skip) |
|
456 | 487 | |
|
457 | 488 | |
|
458 | 489 | def _on_enter(self): |
|
459 | 490 | """ Called on return key down, in readline input_state. |
|
460 | 491 | """ |
|
461 | 492 | if self.debug: |
|
462 | 493 | print >>sys.__stdout__, repr(self.input_buffer) |
|
463 | 494 | PrefilterFrontEnd._on_enter(self) |
|
464 | 495 | |
|
465 | 496 | |
|
466 | 497 | #-------------------------------------------------------------------------- |
|
467 | 498 | # EditWindow API |
|
468 | 499 | #-------------------------------------------------------------------------- |
|
469 | 500 | |
|
470 | 501 | def OnUpdateUI(self, event): |
|
471 | 502 | """ Override the OnUpdateUI of the EditWindow class, to prevent |
|
472 | 503 | syntax highlighting both for faster redraw, and for more |
|
473 | 504 | consistent look and feel. |
|
474 | 505 | """ |
|
475 | 506 | if not self._input_state == 'readline': |
|
476 | 507 | ConsoleWidget.OnUpdateUI(self, event) |
|
477 | 508 | |
|
478 | 509 | #-------------------------------------------------------------------------- |
|
479 | 510 | # Private API |
|
480 | 511 | #-------------------------------------------------------------------------- |
|
481 | 512 | |
|
482 | 513 | def _buffer_flush(self, event): |
|
483 | 514 | """ Called by the timer to flush the write buffer. |
|
484 | 515 | |
|
485 | 516 | This is always called in the mainloop, by the wx timer. |
|
486 | 517 | """ |
|
487 | 518 | self._out_buffer_lock.acquire() |
|
488 | 519 | _out_buffer = self._out_buffer |
|
489 | 520 | self._out_buffer = [] |
|
490 | 521 | self._out_buffer_lock.release() |
|
491 | 522 | self.write(''.join(_out_buffer), refresh=False) |
|
492 | 523 | |
|
493 | 524 | |
|
494 | 525 | def _colorize_input_buffer(self): |
|
495 | 526 | """ Keep the input buffer lines at a bright color. |
|
496 | 527 | """ |
|
497 | 528 | if not self._input_state in ('readline', 'raw_input'): |
|
498 | 529 | return |
|
499 | 530 | end_line = self.GetCurrentLine() |
|
500 | 531 | if not sys.platform == 'win32': |
|
501 | 532 | end_line += 1 |
|
502 | 533 | for i in range(self.current_prompt_line, end_line): |
|
503 | 534 | if i in self._markers: |
|
504 | 535 | self.MarkerDeleteHandle(self._markers[i]) |
|
505 | 536 | self._markers[i] = self.MarkerAdd(i, _INPUT_MARKER) |
|
506 | 537 | |
|
507 | 538 | |
|
508 | 539 | if __name__ == '__main__': |
|
509 | 540 | class MainWindow(wx.Frame): |
|
510 | 541 | def __init__(self, parent, id, title): |
|
511 | 542 | wx.Frame.__init__(self, parent, id, title, size=(300,250)) |
|
512 | 543 | self._sizer = wx.BoxSizer(wx.VERTICAL) |
|
513 | 544 | self.shell = WxController(self) |
|
514 | 545 | self._sizer.Add(self.shell, 1, wx.EXPAND) |
|
515 | 546 | self.SetSizer(self._sizer) |
|
516 | 547 | self.SetAutoLayout(1) |
|
517 | 548 | self.Show(True) |
|
518 | 549 | |
|
519 | 550 | app = wx.PySimpleApp() |
|
520 | 551 | frame = MainWindow(None, wx.ID_ANY, 'Ipython') |
|
521 | 552 | frame.shell.SetFocus() |
|
522 | 553 | frame.SetSize((680, 460)) |
|
523 | 554 | self = frame.shell |
|
524 | 555 | |
|
525 | 556 | app.MainLoop() |
|
526 | 557 |
@@ -1,34 +1,27 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.frontend.tests.test_frontendbase -*- |
|
3 | 3 | """ |
|
4 | 4 | zope.interface mock. If zope is installed, this module provides a zope |
|
5 | 5 | interface classes, if not it provides mocks for them. |
|
6 | 6 | |
|
7 | 7 | Classes provided: |
|
8 | 8 | Interface, Attribute, implements, classProvides |
|
9 | 9 | """ |
|
10 | 10 | __docformat__ = "restructuredtext en" |
|
11 | 11 | |
|
12 | 12 | #------------------------------------------------------------------------------- |
|
13 | 13 | # Copyright (C) 2008 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 | #------------------------------------------------------------------------------- | |
|
20 | # Imports | |
|
21 | #------------------------------------------------------------------------------- | |
|
22 | import string | |
|
23 | import uuid | |
|
24 | import _ast | |
|
25 | ||
|
26 | 19 | try: |
|
27 | 20 | from zope.interface import Interface, Attribute, implements, classProvides |
|
28 | 21 | except ImportError: |
|
29 | 22 | #zope.interface is not available |
|
30 | 23 | Interface = object |
|
31 | 24 | def Attribute(name, doc): pass |
|
32 | 25 | def implements(interface): pass |
|
33 | 26 | def classProvides(interface): pass |
|
34 | 27 |
@@ -1,143 +1,141 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.kernel.test.test_contexts -*- |
|
3 | 3 | """Context managers for IPython. |
|
4 | 4 | |
|
5 | 5 | Python 2.5 introduced the `with` statement, which is based on the context |
|
6 | 6 | manager protocol. This module offers a few context managers for common cases, |
|
7 | 7 | which can also be useful as templates for writing new, application-specific |
|
8 | 8 | managers. |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | from __future__ import with_statement | |
|
12 | ||
|
13 | 11 | __docformat__ = "restructuredtext en" |
|
14 | 12 | |
|
15 | 13 | #------------------------------------------------------------------------------- |
|
16 | 14 | # Copyright (C) 2008 The IPython Development Team |
|
17 | 15 | # |
|
18 | 16 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 17 | # the file COPYING, distributed as part of this software. |
|
20 | 18 | #------------------------------------------------------------------------------- |
|
21 | 19 | |
|
22 | 20 | #------------------------------------------------------------------------------- |
|
23 | 21 | # Imports |
|
24 | 22 | #------------------------------------------------------------------------------- |
|
25 | 23 | |
|
26 | 24 | import linecache |
|
27 | 25 | import sys |
|
28 | 26 | |
|
29 | 27 | from twisted.internet.error import ConnectionRefusedError |
|
30 | 28 | |
|
31 | 29 | from IPython.ultraTB import _fixed_getinnerframes, findsource |
|
32 | 30 | from IPython import ipapi |
|
33 | 31 | |
|
34 | 32 | from IPython.kernel import error |
|
35 | 33 | |
|
36 | 34 | #--------------------------------------------------------------------------- |
|
37 | 35 | # Utility functions needed by all context managers. |
|
38 | 36 | #--------------------------------------------------------------------------- |
|
39 | 37 | |
|
40 | 38 | def remote(): |
|
41 | 39 | """Raises a special exception meant to be caught by context managers. |
|
42 | 40 | """ |
|
43 | 41 | m = 'Special exception to stop local execution of parallel code.' |
|
44 | 42 | raise error.StopLocalExecution(m) |
|
45 | 43 | |
|
46 | 44 | |
|
47 | 45 | def strip_whitespace(source,require_remote=True): |
|
48 | 46 | """strip leading whitespace from input source. |
|
49 | 47 | |
|
50 | 48 | :Parameters: |
|
51 | 49 | |
|
52 | 50 | """ |
|
53 | 51 | remote_mark = 'remote()' |
|
54 | 52 | # Expand tabs to avoid any confusion. |
|
55 | 53 | wsource = [l.expandtabs(4) for l in source] |
|
56 | 54 | # Detect the indentation level |
|
57 | 55 | done = False |
|
58 | 56 | for line in wsource: |
|
59 | 57 | if line.isspace(): |
|
60 | 58 | continue |
|
61 | 59 | for col,char in enumerate(line): |
|
62 | 60 | if char != ' ': |
|
63 | 61 | done = True |
|
64 | 62 | break |
|
65 | 63 | if done: |
|
66 | 64 | break |
|
67 | 65 | # Now we know how much leading space there is in the code. Next, we |
|
68 | 66 | # extract up to the first line that has less indentation. |
|
69 | 67 | # WARNINGS: we skip comments that may be misindented, but we do NOT yet |
|
70 | 68 | # detect triple quoted strings that may have flush left text. |
|
71 | 69 | for lno,line in enumerate(wsource): |
|
72 | 70 | lead = line[:col] |
|
73 | 71 | if lead.isspace(): |
|
74 | 72 | continue |
|
75 | 73 | else: |
|
76 | 74 | if not lead.lstrip().startswith('#'): |
|
77 | 75 | break |
|
78 | 76 | # The real 'with' source is up to lno |
|
79 | 77 | src_lines = [l[col:] for l in wsource[:lno+1]] |
|
80 | 78 | |
|
81 | 79 | # Finally, check that the source's first non-comment line begins with the |
|
82 | 80 | # special call 'remote()' |
|
83 | 81 | if require_remote: |
|
84 | 82 | for nline,line in enumerate(src_lines): |
|
85 | 83 | if line.isspace() or line.startswith('#'): |
|
86 | 84 | continue |
|
87 | 85 | if line.startswith(remote_mark): |
|
88 | 86 | break |
|
89 | 87 | else: |
|
90 | 88 | raise ValueError('%s call missing at the start of code' % |
|
91 | 89 | remote_mark) |
|
92 | 90 | out_lines = src_lines[nline+1:] |
|
93 | 91 | else: |
|
94 | 92 | # If the user specified that the remote() call wasn't mandatory |
|
95 | 93 | out_lines = src_lines |
|
96 | 94 | |
|
97 | 95 | # src = ''.join(out_lines) # dbg |
|
98 | 96 | #print 'SRC:\n<<<<<<<>>>>>>>\n%s<<<<<>>>>>>' % src # dbg |
|
99 | 97 | return ''.join(out_lines) |
|
100 | 98 | |
|
101 | 99 | class RemoteContextBase(object): |
|
102 | 100 | def __init__(self): |
|
103 | 101 | self.ip = ipapi.get() |
|
104 | 102 | |
|
105 | 103 | def _findsource_file(self,f): |
|
106 | 104 | linecache.checkcache() |
|
107 | 105 | s = findsource(f.f_code) |
|
108 | 106 | lnum = f.f_lineno |
|
109 | 107 | wsource = s[0][f.f_lineno:] |
|
110 | 108 | return strip_whitespace(wsource) |
|
111 | 109 | |
|
112 | 110 | def _findsource_ipython(self,f): |
|
113 | 111 | from IPython import ipapi |
|
114 | 112 | self.ip = ipapi.get() |
|
115 | 113 | buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:] |
|
116 | 114 | wsource = [l+'\n' for l in buf ] |
|
117 | 115 | |
|
118 | 116 | return strip_whitespace(wsource) |
|
119 | 117 | |
|
120 | 118 | def findsource(self,frame): |
|
121 | 119 | local_ns = frame.f_locals |
|
122 | 120 | global_ns = frame.f_globals |
|
123 | 121 | if frame.f_code.co_filename == '<ipython console>': |
|
124 | 122 | src = self._findsource_ipython(frame) |
|
125 | 123 | else: |
|
126 | 124 | src = self._findsource_file(frame) |
|
127 | 125 | return src |
|
128 | 126 | |
|
129 | 127 | def __enter__(self): |
|
130 | 128 | raise NotImplementedError |
|
131 | 129 | |
|
132 | 130 | def __exit__ (self, etype, value, tb): |
|
133 | 131 | if issubclass(etype,error.StopLocalExecution): |
|
134 | 132 | return True |
|
135 | 133 | |
|
136 | 134 | class RemoteMultiEngine(RemoteContextBase): |
|
137 | 135 | def __init__(self,mec): |
|
138 | 136 | self.mec = mec |
|
139 | 137 | RemoteContextBase.__init__(self) |
|
140 | 138 | |
|
141 | 139 | def __enter__(self): |
|
142 | 140 | src = self.findsource(sys._getframe(1)) |
|
143 | 141 | return self.mec.execute(src) |
@@ -1,68 +1,68 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Test the output capture at the OS level, using file descriptors. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | __docformat__ = "restructuredtext en" |
|
7 | 7 | |
|
8 | 8 | #------------------------------------------------------------------------------- |
|
9 | 9 | # Copyright (C) 2008 The IPython Development Team |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is |
|
12 | 12 | # in the file COPYING, distributed as part of this software. |
|
13 | 13 | #------------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | |
|
16 | 16 | import os |
|
17 | 17 | from cStringIO import StringIO |
|
18 | 18 | |
|
19 | from IPython.testing import decorators as testdec | |
|
19 | # FIXME: | |
|
20 | import nose | |
|
21 | import sys | |
|
22 | if sys.platform == 'win32': | |
|
23 | raise nose.SkipTest("These tests are not reliable under windows") | |
|
20 | 24 | |
|
21 | # FIXME | |
|
22 | @testdec.skip("This doesn't work under Windows") | |
|
23 | 25 | def test_redirector(): |
|
24 | 26 | """ Checks that the redirector can be used to do synchronous capture. |
|
25 | 27 | """ |
|
26 | 28 | from IPython.kernel.core.fd_redirector import FDRedirector |
|
27 | 29 | r = FDRedirector() |
|
28 | 30 | out = StringIO() |
|
29 | 31 | try: |
|
30 | 32 | r.start() |
|
31 | 33 | for i in range(10): |
|
32 | 34 | os.system('echo %ic' % i) |
|
33 | 35 | print >>out, r.getvalue(), |
|
34 | 36 | print >>out, i |
|
35 | 37 | except: |
|
36 | 38 | r.stop() |
|
37 | 39 | raise |
|
38 | 40 | r.stop() |
|
39 | 41 | result1 = out.getvalue() |
|
40 | 42 | result2 = "".join("%ic\n%i\n" %(i, i) for i in range(10)) |
|
41 | 43 | assert result1 == result2 |
|
42 | 44 | |
|
43 | # FIXME | |
|
44 | @testdec.skip("This doesn't work under Windows") | |
|
45 | 45 | def test_redirector_output_trap(): |
|
46 | 46 | """ This test check not only that the redirector_output_trap does |
|
47 | 47 | trap the output, but also that it does it in a gready way, that |
|
48 | 48 | is by calling the callback ASAP. |
|
49 | 49 | """ |
|
50 | 50 | from IPython.kernel.core.redirector_output_trap import RedirectorOutputTrap |
|
51 | 51 | out = StringIO() |
|
52 | 52 | trap = RedirectorOutputTrap(out.write, out.write) |
|
53 | 53 | try: |
|
54 | 54 | trap.set() |
|
55 | 55 | for i in range(10): |
|
56 | 56 | os.system('echo %ic' % i) |
|
57 | 57 | print "%ip" % i |
|
58 | 58 | print >>out, i |
|
59 | 59 | except: |
|
60 | 60 | trap.unset() |
|
61 | 61 | raise |
|
62 | 62 | trap.unset() |
|
63 | 63 | result1 = out.getvalue() |
|
64 | 64 | result2 = "".join("%ic\n%ip\n%i\n" %(i, i, i) for i in range(10)) |
|
65 | 65 | assert result1 == result2 |
|
66 | 66 | |
|
67 | 67 | |
|
68 | 68 |
@@ -1,41 +1,43 b'' | |||
|
1 | from __future__ import with_statement | |
|
1 | #from __future__ import with_statement | |
|
2 | ||
|
3 | # XXX This file is currently disabled to preserve 2.4 compatibility. | |
|
2 | 4 | |
|
3 | 5 | #def test_simple(): |
|
4 | 6 | if 0: |
|
5 | 7 | |
|
6 | 8 | # XXX - for now, we need a running cluster to be started separately. The |
|
7 | 9 | # daemon work is almost finished, and will make much of this unnecessary. |
|
8 | 10 | from IPython.kernel import client |
|
9 | 11 | mec = client.MultiEngineClient(('127.0.0.1',10105)) |
|
10 | 12 | |
|
11 | 13 | try: |
|
12 | 14 | mec.get_ids() |
|
13 | 15 | except ConnectionRefusedError: |
|
14 | 16 | import os, time |
|
15 | 17 | os.system('ipcluster -n 2 &') |
|
16 | 18 | time.sleep(2) |
|
17 | 19 | mec = client.MultiEngineClient(('127.0.0.1',10105)) |
|
18 | 20 | |
|
19 | 21 | mec.block = False |
|
20 | 22 | |
|
21 | 23 | import itertools |
|
22 | 24 | c = itertools.count() |
|
23 | 25 | |
|
24 | 26 | parallel = RemoteMultiEngine(mec) |
|
25 | 27 | |
|
26 | 28 | mec.pushAll() |
|
27 | 29 | |
|
28 | with parallel as pr: | |
|
29 | # A comment | |
|
30 | remote() # this means the code below only runs remotely | |
|
31 | print 'Hello remote world' | |
|
32 | x = range(10) | |
|
33 | # Comments are OK | |
|
34 | # Even misindented. | |
|
35 | y = x+1 | |
|
30 | ## with parallel as pr: | |
|
31 | ## # A comment | |
|
32 | ## remote() # this means the code below only runs remotely | |
|
33 | ## print 'Hello remote world' | |
|
34 | ## x = range(10) | |
|
35 | ## # Comments are OK | |
|
36 | ## # Even misindented. | |
|
37 | ## y = x+1 | |
|
36 | 38 | |
|
37 | 39 | |
|
38 | with pfor('i',sequence) as pr: | |
|
39 | print x[i] | |
|
40 | ## with pfor('i',sequence) as pr: | |
|
41 | ## print x[i] | |
|
40 | 42 | |
|
41 | 43 | print pr.x + pr.y |
@@ -1,120 +1,123 b'' | |||
|
1 | 1 | """Example showing how to merge multiple remote data streams. |
|
2 | 2 | """ |
|
3 | 3 | # Slightly modified version of: |
|
4 | 4 | # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511509 |
|
5 | 5 | |
|
6 | 6 | import heapq |
|
7 | 7 | from IPython.kernel.error import CompositeError |
|
8 | 8 | |
|
9 | 9 | def mergesort(list_of_lists, key=None): |
|
10 | 10 | """ Perform an N-way merge operation on sorted lists. |
|
11 | 11 | |
|
12 | 12 | @param list_of_lists: (really iterable of iterable) of sorted elements |
|
13 | 13 | (either by naturally or by C{key}) |
|
14 | 14 | @param key: specify sort key function (like C{sort()}, C{sorted()}) |
|
15 | 15 | |
|
16 | 16 | Yields tuples of the form C{(item, iterator)}, where the iterator is the |
|
17 | 17 | built-in list iterator or something you pass in, if you pre-generate the |
|
18 | 18 | iterators. |
|
19 | 19 | |
|
20 | 20 | This is a stable merge; complexity O(N lg N) |
|
21 | 21 | |
|
22 | 22 | Examples:: |
|
23 | 23 | |
|
24 | 24 | >>> print list(mergesort([[1,2,3,4], |
|
25 | 25 | ... [2,3.25,3.75,4.5,6,7], |
|
26 | 26 | ... [2.625,3.625,6.625,9]])) |
|
27 | 27 | [1, 2, 2, 2.625, 3, 3.25, 3.625, 3.75, 4, 4.5, 6, 6.625, 7, 9] |
|
28 | 28 | |
|
29 | 29 | # note stability |
|
30 | 30 | >>> print list(mergesort([[1,2,3,4], |
|
31 | 31 | ... [2,3.25,3.75,4.5,6,7], |
|
32 | 32 | ... [2.625,3.625,6.625,9]], |
|
33 | 33 | ... key=int)) |
|
34 | 34 | [1, 2, 2, 2.625, 3, 3.25, 3.75, 3.625, 4, 4.5, 6, 6.625, 7, 9] |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | >>> print list(mergesort([[4, 3, 2, 1], |
|
38 | 38 | ... [7, 6, 4.5, 3.75, 3.25, 2], |
|
39 | 39 | ... [9, 6.625, 3.625, 2.625]], |
|
40 | 40 | ... key=lambda x: -x)) |
|
41 | 41 | [9, 7, 6.625, 6, 4.5, 4, 3.75, 3.625, 3.25, 3, 2.625, 2, 2, 1] |
|
42 | 42 | """ |
|
43 | 43 | |
|
44 | 44 | heap = [] |
|
45 | 45 | for i, itr in enumerate(iter(pl) for pl in list_of_lists): |
|
46 | 46 | try: |
|
47 | 47 | item = itr.next() |
|
48 | toadd = (key(item), i, item, itr) if key else (item, i, itr) | |
|
48 | if key: | |
|
49 | toadd = (key(item), i, item, itr) | |
|
50 | else: | |
|
51 | toadd = (item, i, itr) | |
|
49 | 52 | heap.append(toadd) |
|
50 | 53 | except StopIteration: |
|
51 | 54 | pass |
|
52 | 55 | heapq.heapify(heap) |
|
53 | 56 | |
|
54 | 57 | if key: |
|
55 | 58 | while heap: |
|
56 | 59 | _, idx, item, itr = heap[0] |
|
57 | 60 | yield item |
|
58 | 61 | try: |
|
59 | 62 | item = itr.next() |
|
60 | 63 | heapq.heapreplace(heap, (key(item), idx, item, itr) ) |
|
61 | 64 | except StopIteration: |
|
62 | 65 | heapq.heappop(heap) |
|
63 | 66 | |
|
64 | 67 | else: |
|
65 | 68 | while heap: |
|
66 | 69 | item, idx, itr = heap[0] |
|
67 | 70 | yield item |
|
68 | 71 | try: |
|
69 | 72 | heapq.heapreplace(heap, (itr.next(), idx, itr)) |
|
70 | 73 | except StopIteration: |
|
71 | 74 | heapq.heappop(heap) |
|
72 | 75 | |
|
73 | 76 | |
|
74 | 77 | def remote_iterator(rc,engine,name): |
|
75 | 78 | """Return an iterator on an object living on a remote engine. |
|
76 | 79 | """ |
|
77 | 80 | # Check that the object exists on the engine and pin a reference to it |
|
78 | 81 | iter_name = '_%s_rmt_iter_' % name |
|
79 | 82 | rc.execute('%s = iter(%s)' % (iter_name,name), targets=engine) |
|
80 | 83 | tpl = '_tmp = %s.next()' % iter_name |
|
81 | 84 | while True: |
|
82 | 85 | try: |
|
83 | 86 | rc.execute(tpl, targets=engine) |
|
84 | 87 | result = rc.pull('_tmp', targets=engine)[0] |
|
85 | 88 | # This causes the StopIteration exception to be raised. |
|
86 | 89 | except CompositeError, e: |
|
87 | 90 | e.raise_exception() |
|
88 | 91 | else: |
|
89 | 92 | yield result |
|
90 | 93 | |
|
91 | 94 | # Main, interactive testing |
|
92 | 95 | if __name__ == '__main__': |
|
93 | 96 | |
|
94 | 97 | from IPython.kernel import client |
|
95 | 98 | ipc = client.MultiEngineClient() |
|
96 | 99 | print 'Engine IDs:',ipc.get_ids() |
|
97 | 100 | |
|
98 | 101 | # Make a set of 'sorted datasets' |
|
99 | 102 | a0 = range(5,20) |
|
100 | 103 | a1 = range(10) |
|
101 | 104 | a2 = range(15,25) |
|
102 | 105 | |
|
103 | 106 | # Now, imagine these had been created in the remote engines by some long |
|
104 | 107 | # computation. In this simple example, we just send them over into the |
|
105 | 108 | # remote engines. They will all be called 'a' in each engine. |
|
106 | 109 | ipc.push(dict(a=a0), targets=0) |
|
107 | 110 | ipc.push(dict(a=a1), targets=1) |
|
108 | 111 | ipc.push(dict(a=a2), targets=2) |
|
109 | 112 | |
|
110 | 113 | # And we now make a local object which represents the remote iterator |
|
111 | 114 | aa0 = remote_iterator(ipc,0,'a') |
|
112 | 115 | aa1 = remote_iterator(ipc,1,'a') |
|
113 | 116 | aa2 = remote_iterator(ipc,2,'a') |
|
114 | 117 | |
|
115 | 118 | # Let's merge them, both locally and remotely: |
|
116 | 119 | print 'Merge the local datasets:' |
|
117 | 120 | print list(mergesort([a0,a1,a2])) |
|
118 | 121 | |
|
119 | 122 | print 'Locally merge the remote sets:' |
|
120 | 123 | print list(mergesort([aa0,aa1,aa2])) |
@@ -1,252 +1,325 b'' | |||
|
1 | 1 | .. _changes: |
|
2 | 2 | |
|
3 | 3 | ========== |
|
4 | 4 | What's new |
|
5 | 5 | ========== |
|
6 | 6 | |
|
7 | 7 | .. contents:: |
|
8 | 8 | .. |
|
9 | 9 | 1 Release 0.9 |
|
10 | 10 | 1.1 New features |
|
11 | 11 | 1.2 Bug fixes |
|
12 | 12 | 1.3 Backwards incompatible changes |
|
13 | 13 | 1.4 Changes merged in from IPython1 |
|
14 | 14 | 1.4.1 New features |
|
15 | 15 | 1.4.2 Bug fixes |
|
16 | 16 | 1.4.3 Backwards incompatible changes |
|
17 | 17 | 2 Release 0.8.4 |
|
18 |
3 Release 0.8. |
|
|
19 |
4 Release 0.8. |
|
|
18 | 3 Release 0.8.3 | |
|
19 | 4 Release 0.8.2 | |
|
20 | 20 | 5 Older releases |
|
21 | 21 | .. |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | Release 0.9 |
|
25 | 25 | =========== |
|
26 | 26 | |
|
27 | 27 | New features |
|
28 | 28 | ------------ |
|
29 | 29 | |
|
30 | * All furl files and security certificates are now put in a read-only directory | |
|
31 | named ~./ipython/security. | |
|
32 | ||
|
33 | * A single function :func:`get_ipython_dir`, in :mod:`IPython.genutils` that | |
|
34 | determines the user's IPython directory in a robust manner. | |
|
35 | ||
|
30 | 36 | * Laurent's WX application has been given a top-level script called ipython-wx, |
|
31 | 37 | and it has received numerous fixes. We expect this code to be |
|
32 | 38 | architecturally better integrated with Gael's WX 'ipython widget' over the |
|
33 | 39 | next few releases. |
|
34 | 40 | |
|
35 | 41 | * The Editor synchronization work by Vivian De Smedt has been merged in. This |
|
36 | 42 | code adds a number of new editor hooks to synchronize with editors under |
|
37 | 43 | Windows. |
|
38 | 44 | |
|
39 | 45 | * A new, still experimental but highly functional, WX shell by Gael Varoquaux. |
|
40 | 46 | This work was sponsored by Enthought, and while it's still very new, it is |
|
41 | 47 | based on a more cleanly organized arhictecture of the various IPython |
|
42 | 48 | components. We will continue to develop this over the next few releases as a |
|
43 | 49 | model for GUI components that use IPython. |
|
44 | 50 | |
|
45 | 51 | * Another GUI frontend, Cocoa based (Cocoa is the OSX native GUI framework), |
|
46 | 52 | authored by Barry Wark. Currently the WX and the Cocoa ones have slightly |
|
47 | 53 | different internal organizations, but the whole team is working on finding |
|
48 | 54 | what the right abstraction points are for a unified codebase. |
|
49 | 55 | |
|
50 | 56 | * As part of the frontend work, Barry Wark also implemented an experimental |
|
51 | 57 | event notification system that various ipython components can use. In the |
|
52 | 58 | next release the implications and use patterns of this system regarding the |
|
53 | 59 | various GUI options will be worked out. |
|
54 | 60 | |
|
55 | 61 | * IPython finally has a full test system, that can test docstrings with |
|
56 | 62 | IPython-specific functionality. There are still a few pieces missing for it |
|
57 | 63 | to be widely accessible to all users (so they can run the test suite at any |
|
58 | 64 | time and report problems), but it now works for the developers. We are |
|
59 | 65 | working hard on continuing to improve it, as this was probably IPython's |
|
60 | 66 | major Achilles heel (the lack of proper test coverage made it effectively |
|
61 | impossible to do large-scale refactoring). | |
|
62 | ||
|
63 | * The notion of a task has been completely reworked. An `ITask` interface has | |
|
64 | been created. This interface defines the methods that tasks need to implement. | |
|
65 | These methods are now responsible for things like submitting tasks and processing | |
|
66 | results. There are two basic task types: :class:`IPython.kernel.task.StringTask` | |
|
67 | (this is the old `Task` object, but renamed) and the new | |
|
68 |
|
|
|
69 | * A new interface, :class:`IPython.kernel.mapper.IMapper` has been defined to | |
|
70 | standardize the idea of a `map` method. This interface has a single | |
|
71 | `map` method that has the same syntax as the built-in `map`. We have also defined | |
|
72 | a `mapper` factory interface that creates objects that implement | |
|
73 | :class:`IPython.kernel.mapper.IMapper` for different controllers. Both | |
|
74 | the multiengine and task controller now have mapping capabilties. | |
|
75 | * The parallel function capabilities have been reworks. The major changes are that | |
|
76 | i) there is now an `@parallel` magic that creates parallel functions, ii) | |
|
77 | the syntax for mulitple variable follows that of `map`, iii) both the | |
|
78 | multiengine and task controller now have a parallel function implementation. | |
|
79 | * All of the parallel computing capabilities from `ipython1-dev` have been merged into | |
|
80 | IPython proper. This resulted in the following new subpackages: | |
|
81 | :mod:`IPython.kernel`, :mod:`IPython.kernel.core`, :mod:`IPython.config`, | |
|
82 | :mod:`IPython.tools` and :mod:`IPython.testing`. | |
|
83 | * As part of merging in the `ipython1-dev` stuff, the `setup.py` script and friends | |
|
84 | have been completely refactored. Now we are checking for dependencies using | |
|
85 | the approach that matplotlib uses. | |
|
86 | * The documentation has been completely reorganized to accept the documentation | |
|
87 | from `ipython1-dev`. | |
|
88 | * We have switched to using Foolscap for all of our network protocols in | |
|
89 | :mod:`IPython.kernel`. This gives us secure connections that are both encrypted | |
|
90 | and authenticated. | |
|
91 | * We have a brand new `COPYING.txt` files that describes the IPython license | |
|
92 | and copyright. The biggest change is that we are putting "The IPython | |
|
93 | Development Team" as the copyright holder. We give more details about exactly | |
|
94 | what this means in this file. All developer should read this and use the new | |
|
95 | banner in all IPython source code files. | |
|
96 | * sh profile: ./foo runs foo as system command, no need to do !./foo anymore | |
|
97 | * String lists now support 'sort(field, nums = True)' method (to easily | |
|
98 | sort system command output). Try it with 'a = !ls -l ; a.sort(1, nums=1)' | |
|
99 | * '%cpaste foo' now assigns the pasted block as string list, instead of string | |
|
100 | * The ipcluster script now run by default with no security. This is done because | |
|
101 | the main usage of the script is for starting things on localhost. Eventually | |
|
102 | when ipcluster is able to start things on other hosts, we will put security | |
|
103 | back. | |
|
104 | * 'cd --foo' searches directory history for string foo, and jumps to that dir. | |
|
105 | Last part of dir name is checked first. If no matches for that are found, | |
|
106 | look at the whole path. | |
|
67 | impossible to do large-scale refactoring). The full test suite can now | |
|
68 | be run using the :command:`iptest` command line program. | |
|
69 | ||
|
70 | * The notion of a task has been completely reworked. An `ITask` interface has | |
|
71 | been created. This interface defines the methods that tasks need to | |
|
72 | implement. These methods are now responsible for things like submitting | |
|
73 | tasks and processing results. There are two basic task types: | |
|
74 | :class:`IPython.kernel.task.StringTask` (this is the old `Task` object, but | |
|
75 | renamed) and the new :class:`IPython.kernel.task.MapTask`, which is based on | |
|
76 | a function. | |
|
77 | ||
|
78 | * A new interface, :class:`IPython.kernel.mapper.IMapper` has been defined to | |
|
79 | standardize the idea of a `map` method. This interface has a single `map` | |
|
80 | method that has the same syntax as the built-in `map`. We have also defined | |
|
81 | a `mapper` factory interface that creates objects that implement | |
|
82 | :class:`IPython.kernel.mapper.IMapper` for different controllers. Both the | |
|
83 | multiengine and task controller now have mapping capabilties. | |
|
84 | ||
|
85 | * The parallel function capabilities have been reworks. The major changes are | |
|
86 | that i) there is now an `@parallel` magic that creates parallel functions, | |
|
87 | ii) the syntax for mulitple variable follows that of `map`, iii) both the | |
|
88 | multiengine and task controller now have a parallel function implementation. | |
|
89 | ||
|
90 | * All of the parallel computing capabilities from `ipython1-dev` have been | |
|
91 | merged into IPython proper. This resulted in the following new subpackages: | |
|
92 | :mod:`IPython.kernel`, :mod:`IPython.kernel.core`, :mod:`IPython.config`, | |
|
93 | :mod:`IPython.tools` and :mod:`IPython.testing`. | |
|
94 | ||
|
95 | * As part of merging in the `ipython1-dev` stuff, the `setup.py` script and | |
|
96 | friends have been completely refactored. Now we are checking for | |
|
97 | dependencies using the approach that matplotlib uses. | |
|
98 | ||
|
99 | * The documentation has been completely reorganized to accept the documentation | |
|
100 | from `ipython1-dev`. | |
|
101 | ||
|
102 | * We have switched to using Foolscap for all of our network protocols in | |
|
103 | :mod:`IPython.kernel`. This gives us secure connections that are both | |
|
104 | encrypted and authenticated. | |
|
107 | 105 | |
|
106 | * We have a brand new `COPYING.txt` files that describes the IPython license | |
|
107 | and copyright. The biggest change is that we are putting "The IPython | |
|
108 | Development Team" as the copyright holder. We give more details about | |
|
109 | exactly what this means in this file. All developer should read this and use | |
|
110 | the new banner in all IPython source code files. | |
|
111 | ||
|
112 | * sh profile: ./foo runs foo as system command, no need to do !./foo anymore | |
|
113 | ||
|
114 | * String lists now support ``sort(field, nums = True)`` method (to easily sort | |
|
115 | system command output). Try it with ``a = !ls -l ; a.sort(1, nums=1)``. | |
|
116 | ||
|
117 | * '%cpaste foo' now assigns the pasted block as string list, instead of string | |
|
118 | ||
|
119 | * The ipcluster script now run by default with no security. This is done | |
|
120 | because the main usage of the script is for starting things on localhost. | |
|
121 | Eventually when ipcluster is able to start things on other hosts, we will put | |
|
122 | security back. | |
|
123 | ||
|
124 | * 'cd --foo' searches directory history for string foo, and jumps to that dir. | |
|
125 | Last part of dir name is checked first. If no matches for that are found, | |
|
126 | look at the whole path. | |
|
127 | ||
|
128 | ||
|
108 | 129 | Bug fixes |
|
109 | 130 | --------- |
|
110 | 131 | |
|
111 | * The colors escapes in the multiengine client are now turned off on win32 as they | |
|
112 | don't print correctly. | |
|
113 | * The :mod:`IPython.kernel.scripts.ipengine` script was exec'ing mpi_import_statement | |
|
114 | incorrectly, which was leading the engine to crash when mpi was enabled. | |
|
115 | * A few subpackages has missing `__init__.py` files. | |
|
116 | * The documentation is only created is Sphinx is found. Previously, the `setup.py` | |
|
117 | script would fail if it was missing. | |
|
118 | * Greedy 'cd' completion has been disabled again (it was enabled in 0.8.4) | |
|
132 | * The Windows installer has been fixed. Now all IPython scripts have ``.bat`` | |
|
133 | versions created. Also, the Start Menu shortcuts have been updated. | |
|
134 | ||
|
135 | * The colors escapes in the multiengine client are now turned off on win32 as | |
|
136 | they don't print correctly. | |
|
137 | ||
|
138 | * The :mod:`IPython.kernel.scripts.ipengine` script was exec'ing | |
|
139 | mpi_import_statement incorrectly, which was leading the engine to crash when | |
|
140 | mpi was enabled. | |
|
141 | ||
|
142 | * A few subpackages had missing ``__init__.py`` files. | |
|
143 | ||
|
144 | * The documentation is only created if Sphinx is found. Previously, the | |
|
145 | ``setup.py`` script would fail if it was missing. | |
|
146 | ||
|
147 | * Greedy ``cd`` completion has been disabled again (it was enabled in 0.8.4) as | |
|
148 | it caused problems on certain platforms. | |
|
119 | 149 | |
|
120 | 150 | |
|
121 | 151 | Backwards incompatible changes |
|
122 | 152 | ------------------------------ |
|
123 | 153 | |
|
154 | * The ``clusterfile`` options of the :command:`ipcluster` command has been | |
|
155 | removed as it was not working and it will be replaced soon by something much | |
|
156 | more robust. | |
|
157 | ||
|
158 | * The :mod:`IPython.kernel` configuration now properly find the user's | |
|
159 | IPython directory. | |
|
160 | ||
|
124 | 161 | * In ipapi, the :func:`make_user_ns` function has been replaced with |
|
125 | 162 | :func:`make_user_namespaces`, to support dict subclasses in namespace |
|
126 | 163 | creation. |
|
127 | 164 | |
|
128 |
|
|
|
129 |
|
|
|
130 | * The keyword argument `style` has been renamed `dist` in `scatter`, `gather` | |
|
131 | and `map`. | |
|
132 | * Renamed the values that the rename `dist` keyword argument can have from | |
|
133 | `'basic'` to `'b'`. | |
|
134 | * IPython has a larger set of dependencies if you want all of its capabilities. | |
|
135 | See the `setup.py` script for details. | |
|
136 | * The constructors for :class:`IPython.kernel.client.MultiEngineClient` and | |
|
137 | :class:`IPython.kernel.client.TaskClient` no longer take the (ip,port) tuple. | |
|
138 | Instead they take the filename of a file that contains the FURL for that | |
|
139 | client. If the FURL file is in your IPYTHONDIR, it will be found automatically | |
|
140 | and the constructor can be left empty. | |
|
141 | * The asynchronous clients in :mod:`IPython.kernel.asyncclient` are now created | |
|
142 | using the factory functions :func:`get_multiengine_client` and | |
|
143 | :func:`get_task_client`. These return a `Deferred` to the actual client. | |
|
144 | * The command line options to `ipcontroller` and `ipengine` have changed to | |
|
145 | reflect the new Foolscap network protocol and the FURL files. Please see the | |
|
146 | help for these scripts for details. | |
|
147 | * The configuration files for the kernel have changed because of the Foolscap stuff. | |
|
148 | If you were using custom config files before, you should delete them and regenerate | |
|
149 | new ones. | |
|
165 | * :class:`IPython.kernel.client.Task` has been renamed | |
|
166 | :class:`IPython.kernel.client.StringTask` to make way for new task types. | |
|
167 | ||
|
168 | * The keyword argument `style` has been renamed `dist` in `scatter`, `gather` | |
|
169 | and `map`. | |
|
170 | ||
|
171 | * Renamed the values that the rename `dist` keyword argument can have from | |
|
172 | `'basic'` to `'b'`. | |
|
173 | ||
|
174 | * IPython has a larger set of dependencies if you want all of its capabilities. | |
|
175 | See the `setup.py` script for details. | |
|
176 | ||
|
177 | * The constructors for :class:`IPython.kernel.client.MultiEngineClient` and | |
|
178 | :class:`IPython.kernel.client.TaskClient` no longer take the (ip,port) tuple. | |
|
179 | Instead they take the filename of a file that contains the FURL for that | |
|
180 | client. If the FURL file is in your IPYTHONDIR, it will be found automatically | |
|
181 | and the constructor can be left empty. | |
|
182 | ||
|
183 | * The asynchronous clients in :mod:`IPython.kernel.asyncclient` are now created | |
|
184 | using the factory functions :func:`get_multiengine_client` and | |
|
185 | :func:`get_task_client`. These return a `Deferred` to the actual client. | |
|
186 | ||
|
187 | * The command line options to `ipcontroller` and `ipengine` have changed to | |
|
188 | reflect the new Foolscap network protocol and the FURL files. Please see the | |
|
189 | help for these scripts for details. | |
|
190 | ||
|
191 | * The configuration files for the kernel have changed because of the Foolscap | |
|
192 | stuff. If you were using custom config files before, you should delete them | |
|
193 | and regenerate new ones. | |
|
150 | 194 | |
|
151 | 195 | Changes merged in from IPython1 |
|
152 | 196 | ------------------------------- |
|
153 | 197 | |
|
154 | 198 | New features |
|
155 | 199 | ............ |
|
156 | 200 | |
|
157 |
|
|
|
158 |
|
|
|
159 |
|
|
|
160 | * IPython is now compatible with Twisted 2.5.0 and 8.x. | |
|
161 | * Added a new example of how to use :mod:`ipython1.kernel.asynclient`. | |
|
162 | * Initial draft of a process daemon in :mod:`ipython1.daemon`. This has not | |
|
163 | been merged into IPython and is still in `ipython1-dev`. | |
|
164 | * The ``TaskController`` now has methods for getting the queue status. | |
|
165 | * The ``TaskResult`` objects not have information about how long the task | |
|
166 | took to run. | |
|
167 | * We are attaching additional attributes to exceptions ``(_ipython_*)`` that | |
|
168 | we use to carry additional info around. | |
|
169 | * New top-level module :mod:`asyncclient` that has asynchronous versions (that | |
|
170 | return deferreds) of the client classes. This is designed to users who want | |
|
171 | to run their own Twisted reactor | |
|
172 | * All the clients in :mod:`client` are now based on Twisted. This is done by | |
|
173 | running the Twisted reactor in a separate thread and using the | |
|
174 | :func:`blockingCallFromThread` function that is in recent versions of Twisted. | |
|
175 | * Functions can now be pushed/pulled to/from engines using | |
|
176 | :meth:`MultiEngineClient.push_function` and :meth:`MultiEngineClient.pull_function`. | |
|
177 | * Gather/scatter are now implemented in the client to reduce the work load | |
|
178 | of the controller and improve performance. | |
|
179 | * Complete rewrite of the IPython docuementation. All of the documentation | |
|
180 | from the IPython website has been moved into docs/source as restructured | |
|
181 | text documents. PDF and HTML documentation are being generated using | |
|
182 | Sphinx. | |
|
183 | * New developer oriented documentation: development guidelines and roadmap. | |
|
184 | * Traditional ``ChangeLog`` has been changed to a more useful ``changes.txt`` file | |
|
185 | that is organized by release and is meant to provide something more relevant | |
|
186 | for users. | |
|
201 | * Much improved ``setup.py`` and ``setupegg.py`` scripts. Because Twisted and | |
|
202 | zope.interface are now easy installable, we can declare them as dependencies | |
|
203 | in our setupegg.py script. | |
|
204 | ||
|
205 | * IPython is now compatible with Twisted 2.5.0 and 8.x. | |
|
206 | ||
|
207 | * Added a new example of how to use :mod:`ipython1.kernel.asynclient`. | |
|
208 | ||
|
209 | * Initial draft of a process daemon in :mod:`ipython1.daemon`. This has not | |
|
210 | been merged into IPython and is still in `ipython1-dev`. | |
|
211 | ||
|
212 | * The ``TaskController`` now has methods for getting the queue status. | |
|
213 | ||
|
214 | * The ``TaskResult`` objects not have information about how long the task | |
|
215 | took to run. | |
|
216 | ||
|
217 | * We are attaching additional attributes to exceptions ``(_ipython_*)`` that | |
|
218 | we use to carry additional info around. | |
|
219 | ||
|
220 | * New top-level module :mod:`asyncclient` that has asynchronous versions (that | |
|
221 | return deferreds) of the client classes. This is designed to users who want | |
|
222 | to run their own Twisted reactor. | |
|
223 | ||
|
224 | * All the clients in :mod:`client` are now based on Twisted. This is done by | |
|
225 | running the Twisted reactor in a separate thread and using the | |
|
226 | :func:`blockingCallFromThread` function that is in recent versions of Twisted. | |
|
227 | ||
|
228 | * Functions can now be pushed/pulled to/from engines using | |
|
229 | :meth:`MultiEngineClient.push_function` and | |
|
230 | :meth:`MultiEngineClient.pull_function`. | |
|
231 | ||
|
232 | * Gather/scatter are now implemented in the client to reduce the work load | |
|
233 | of the controller and improve performance. | |
|
234 | ||
|
235 | * Complete rewrite of the IPython docuementation. All of the documentation | |
|
236 | from the IPython website has been moved into docs/source as restructured | |
|
237 | text documents. PDF and HTML documentation are being generated using | |
|
238 | Sphinx. | |
|
239 | ||
|
240 | * New developer oriented documentation: development guidelines and roadmap. | |
|
241 | ||
|
242 | * Traditional ``ChangeLog`` has been changed to a more useful ``changes.txt`` | |
|
243 | file that is organized by release and is meant to provide something more | |
|
244 | relevant for users. | |
|
187 | 245 | |
|
188 | 246 | Bug fixes |
|
189 | 247 | ......... |
|
190 | 248 | |
|
191 |
|
|
|
192 | * Fixed a bug in the ``MultiEngine`` interface. Previously, multi-engine | |
|
193 | actions were being collected with a :class:`DeferredList` with | |
|
194 | ``fireononeerrback=1``. This meant that methods were returning | |
|
195 | before all engines had given their results. This was causing extremely odd | |
|
196 | bugs in certain cases. To fix this problem, we have 1) set | |
|
197 | ``fireononeerrback=0`` to make sure all results (or exceptions) are in | |
|
198 | before returning and 2) introduced a :exc:`CompositeError` exception | |
|
199 | that wraps all of the engine exceptions. This is a huge change as it means | |
|
200 | that users will have to catch :exc:`CompositeError` rather than the actual | |
|
201 | exception. | |
|
249 | * Created a proper ``MANIFEST.in`` file to create source distributions. | |
|
250 | ||
|
251 | * Fixed a bug in the ``MultiEngine`` interface. Previously, multi-engine | |
|
252 | actions were being collected with a :class:`DeferredList` with | |
|
253 | ``fireononeerrback=1``. This meant that methods were returning | |
|
254 | before all engines had given their results. This was causing extremely odd | |
|
255 | bugs in certain cases. To fix this problem, we have 1) set | |
|
256 | ``fireononeerrback=0`` to make sure all results (or exceptions) are in | |
|
257 | before returning and 2) introduced a :exc:`CompositeError` exception | |
|
258 | that wraps all of the engine exceptions. This is a huge change as it means | |
|
259 | that users will have to catch :exc:`CompositeError` rather than the actual | |
|
260 | exception. | |
|
202 | 261 | |
|
203 | 262 | Backwards incompatible changes |
|
204 | 263 | .............................. |
|
205 | 264 | |
|
206 |
|
|
|
207 |
|
|
|
208 |
|
|
|
209 | * Previously, methods like :meth:`MultiEngineClient.push` and | |
|
210 | :meth:`MultiEngineClient.push` used ``*args`` and ``**kwargs``. This was | |
|
211 | becoming a problem as we weren't able to introduce new keyword arguments into | |
|
212 | the API. Now these methods simple take a dict or sequence. This has also allowed | |
|
213 | us to get rid of the ``*All`` methods like :meth:`pushAll` and :meth:`pullAll`. | |
|
214 | These things are now handled with the ``targets`` keyword argument that defaults | |
|
215 | to ``'all'``. | |
|
216 | * The :attr:`MultiEngineClient.magicTargets` has been renamed to | |
|
217 | :attr:`MultiEngineClient.targets`. | |
|
218 | * All methods in the MultiEngine interface now accept the optional keyword argument | |
|
219 | ``block``. | |
|
220 | * Renamed :class:`RemoteController` to :class:`MultiEngineClient` and | |
|
221 | :class:`TaskController` to :class:`TaskClient`. | |
|
222 | * Renamed the top-level module from :mod:`api` to :mod:`client`. | |
|
223 | * Most methods in the multiengine interface now raise a :exc:`CompositeError` exception | |
|
224 | that wraps the user's exceptions, rather than just raising the raw user's exception. | |
|
225 | * Changed the ``setupNS`` and ``resultNames`` in the ``Task`` class to ``push`` | |
|
226 | and ``pull``. | |
|
265 | * All names have been renamed to conform to the lowercase_with_underscore | |
|
266 | convention. This will require users to change references to all names like | |
|
267 | ``queueStatus`` to ``queue_status``. | |
|
268 | ||
|
269 | * Previously, methods like :meth:`MultiEngineClient.push` and | |
|
270 | :meth:`MultiEngineClient.push` used ``*args`` and ``**kwargs``. This was | |
|
271 | becoming a problem as we weren't able to introduce new keyword arguments into | |
|
272 | the API. Now these methods simple take a dict or sequence. This has also | |
|
273 | allowed us to get rid of the ``*All`` methods like :meth:`pushAll` and | |
|
274 | :meth:`pullAll`. These things are now handled with the ``targets`` keyword | |
|
275 | argument that defaults to ``'all'``. | |
|
276 | ||
|
277 | * The :attr:`MultiEngineClient.magicTargets` has been renamed to | |
|
278 | :attr:`MultiEngineClient.targets`. | |
|
279 | ||
|
280 | * All methods in the MultiEngine interface now accept the optional keyword | |
|
281 | argument ``block``. | |
|
282 | ||
|
283 | * Renamed :class:`RemoteController` to :class:`MultiEngineClient` and | |
|
284 | :class:`TaskController` to :class:`TaskClient`. | |
|
285 | ||
|
286 | * Renamed the top-level module from :mod:`api` to :mod:`client`. | |
|
287 | ||
|
288 | * Most methods in the multiengine interface now raise a :exc:`CompositeError` | |
|
289 | exception that wraps the user's exceptions, rather than just raising the raw | |
|
290 | user's exception. | |
|
291 | ||
|
292 | * Changed the ``setupNS`` and ``resultNames`` in the ``Task`` class to ``push`` | |
|
293 | and ``pull``. | |
|
227 | 294 | |
|
295 | ||
|
228 | 296 | Release 0.8.4 |
|
229 | 297 | ============= |
|
230 | 298 | |
|
231 | Someone needs to describe what went into 0.8.4. | |
|
299 | This was a quick release to fix an unfortunate bug that slipped into the 0.8.3 | |
|
300 | release. The ``--twisted`` option was disabled, as it turned out to be broken | |
|
301 | across several platforms. | |
|
232 | 302 | |
|
233 | Release 0.8.2 | |
|
234 | ============= | |
|
235 | 303 | |
|
236 | * %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory | |
|
237 | and jumps to /foo. The current behaviour is closer to the documented | |
|
238 | behaviour, and should not trip anyone. | |
|
239 | ||
|
240 | 304 | Release 0.8.3 |
|
241 | 305 | ============= |
|
242 | 306 | |
|
243 | 307 | * pydb is now disabled by default (due to %run -d problems). You can enable |
|
244 | 308 | it by passing -pydb command line argument to IPython. Note that setting |
|
245 | 309 | it in config file won't work. |
|
246 | 310 | |
|
311 | ||
|
312 | Release 0.8.2 | |
|
313 | ============= | |
|
314 | ||
|
315 | * %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory | |
|
316 | and jumps to /foo. The current behaviour is closer to the documented | |
|
317 | behaviour, and should not trip anyone. | |
|
318 | ||
|
319 | ||
|
247 | 320 | Older releases |
|
248 | 321 | ============== |
|
249 | 322 | |
|
250 |
Changes in earlier releases of IPython are described in the older file |
|
|
251 | Please refer to this document for details. | |
|
323 | Changes in earlier releases of IPython are described in the older file | |
|
324 | ``ChangeLog``. Please refer to this document for details. | |
|
252 | 325 |
@@ -1,180 +1,187 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | # |
|
3 |
# IPython documentation build configuration file |
|
|
4 | # sphinx-quickstart on Thu May 8 16:45:02 2008. | |
|
3 | # IPython documentation build configuration file. | |
|
5 | 4 | |
|
6 | 5 | # NOTE: This file has been edited manually from the auto-generated one from |
|
7 | 6 | # sphinx. Do NOT delete and re-generate. If any changes from sphinx are |
|
8 | 7 | # needed, generate a scratch one and merge by hand any new fields needed. |
|
9 | 8 | |
|
10 | 9 | # |
|
11 | 10 | # This file is execfile()d with the current directory set to its containing dir. |
|
12 | 11 | # |
|
13 | 12 | # The contents of this file are pickled, so don't put values in the namespace |
|
14 | 13 | # that aren't pickleable (module imports are okay, they're removed automatically). |
|
15 | 14 | # |
|
16 | 15 | # All configuration values have a default value; values that are commented out |
|
17 | 16 | # serve to show the default value. |
|
18 | 17 | |
|
19 | 18 | import sys, os |
|
20 | 19 | |
|
21 | 20 | # If your extensions are in another directory, add it here. If the directory |
|
22 | 21 | # is relative to the documentation root, use os.path.abspath to make it |
|
23 | 22 | # absolute, like shown here. |
|
24 |
|
|
|
23 | sys.path.append(os.path.abspath('../sphinxext')) | |
|
24 | ||
|
25 | # Import support for ipython console session syntax highlighting (lives | |
|
26 | # in the sphinxext directory defined above) | |
|
27 | import ipython_console_highlighting | |
|
25 | 28 | |
|
26 | 29 | # We load the ipython release info into a dict by explicit execution |
|
27 | 30 | iprelease = {} |
|
28 | 31 | execfile('../../IPython/Release.py',iprelease) |
|
29 | 32 | |
|
30 | 33 | # General configuration |
|
31 | 34 | # --------------------- |
|
32 | 35 | |
|
33 | 36 | # Add any Sphinx extension module names here, as strings. They can be extensions |
|
34 | 37 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. |
|
35 | #extensions = [] | |
|
38 | extensions = ['sphinx.ext.autodoc', | |
|
39 | 'inheritance_diagram', 'only_directives', | |
|
40 | 'ipython_console_highlighting', | |
|
41 | # 'plot_directive', # disabled for now, needs matplotlib | |
|
42 | ] | |
|
36 | 43 | |
|
37 | 44 | # Add any paths that contain templates here, relative to this directory. |
|
38 | 45 | templates_path = ['_templates'] |
|
39 | 46 | |
|
40 | 47 | # The suffix of source filenames. |
|
41 | 48 | source_suffix = '.txt' |
|
42 | 49 | |
|
43 | 50 | # The master toctree document. |
|
44 | 51 | master_doc = 'index' |
|
45 | 52 | |
|
46 | 53 | # General substitutions. |
|
47 | 54 | project = 'IPython' |
|
48 | 55 | copyright = '2008, The IPython Development Team' |
|
49 | 56 | |
|
50 | 57 | # The default replacements for |version| and |release|, also used in various |
|
51 | 58 | # other places throughout the built documents. |
|
52 | 59 | # |
|
53 | 60 | # The full version, including alpha/beta/rc tags. |
|
54 | 61 | release = iprelease['version'] |
|
55 | 62 | # The short X.Y version. |
|
56 | 63 | version = '.'.join(release.split('.',2)[:2]) |
|
57 | 64 | |
|
58 | 65 | |
|
59 | 66 | # There are two options for replacing |today|: either, you set today to some |
|
60 | 67 | # non-false value, then it is used: |
|
61 | 68 | #today = '' |
|
62 | 69 | # Else, today_fmt is used as the format for a strftime call. |
|
63 | 70 | today_fmt = '%B %d, %Y' |
|
64 | 71 | |
|
65 | 72 | # List of documents that shouldn't be included in the build. |
|
66 | 73 | #unused_docs = [] |
|
67 | 74 | |
|
68 | 75 | # List of directories, relative to source directories, that shouldn't be searched |
|
69 | 76 | # for source files. |
|
70 |
|
|
|
77 | exclude_dirs = ['attic'] | |
|
71 | 78 | |
|
72 | 79 | # If true, '()' will be appended to :func: etc. cross-reference text. |
|
73 | 80 | #add_function_parentheses = True |
|
74 | 81 | |
|
75 | 82 | # If true, the current module name will be prepended to all description |
|
76 | 83 | # unit titles (such as .. function::). |
|
77 | 84 | #add_module_names = True |
|
78 | 85 | |
|
79 | 86 | # If true, sectionauthor and moduleauthor directives will be shown in the |
|
80 | 87 | # output. They are ignored by default. |
|
81 | 88 | #show_authors = False |
|
82 | 89 | |
|
83 | 90 | # The name of the Pygments (syntax highlighting) style to use. |
|
84 | 91 | pygments_style = 'sphinx' |
|
85 | 92 | |
|
86 | 93 | |
|
87 | 94 | # Options for HTML output |
|
88 | 95 | # ----------------------- |
|
89 | 96 | |
|
90 | 97 | # The style sheet to use for HTML and HTML Help pages. A file of that name |
|
91 | 98 | # must exist either in Sphinx' static/ path, or in one of the custom paths |
|
92 | 99 | # given in html_static_path. |
|
93 | 100 | html_style = 'default.css' |
|
94 | 101 | |
|
95 | 102 | # The name for this set of Sphinx documents. If None, it defaults to |
|
96 | 103 | # "<project> v<release> documentation". |
|
97 | 104 | #html_title = None |
|
98 | 105 | |
|
99 | 106 | # The name of an image file (within the static path) to place at the top of |
|
100 | 107 | # the sidebar. |
|
101 | 108 | #html_logo = None |
|
102 | 109 | |
|
103 | 110 | # Add any paths that contain custom static files (such as style sheets) here, |
|
104 | 111 | # relative to this directory. They are copied after the builtin static files, |
|
105 | 112 | # so a file named "default.css" will overwrite the builtin "default.css". |
|
106 | 113 | html_static_path = ['_static'] |
|
107 | 114 | |
|
108 | 115 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, |
|
109 | 116 | # using the given strftime format. |
|
110 | 117 | html_last_updated_fmt = '%b %d, %Y' |
|
111 | 118 | |
|
112 | 119 | # If true, SmartyPants will be used to convert quotes and dashes to |
|
113 | 120 | # typographically correct entities. |
|
114 | 121 | #html_use_smartypants = True |
|
115 | 122 | |
|
116 | 123 | # Custom sidebar templates, maps document names to template names. |
|
117 | 124 | #html_sidebars = {} |
|
118 | 125 | |
|
119 | 126 | # Additional templates that should be rendered to pages, maps page names to |
|
120 | 127 | # template names. |
|
121 | 128 | #html_additional_pages = {} |
|
122 | 129 | |
|
123 | 130 | # If false, no module index is generated. |
|
124 | 131 | #html_use_modindex = True |
|
125 | 132 | |
|
126 | 133 | # If true, the reST sources are included in the HTML build as _sources/<name>. |
|
127 | 134 | #html_copy_source = True |
|
128 | 135 | |
|
129 | 136 | # If true, an OpenSearch description file will be output, and all pages will |
|
130 | 137 | # contain a <link> tag referring to it. The value of this option must be the |
|
131 | 138 | # base URL from which the finished HTML is served. |
|
132 | 139 | #html_use_opensearch = '' |
|
133 | 140 | |
|
134 | 141 | # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). |
|
135 | 142 | #html_file_suffix = '' |
|
136 | 143 | |
|
137 | 144 | # Output file base name for HTML help builder. |
|
138 |
htmlhelp_basename = ' |
|
|
145 | htmlhelp_basename = 'ipythondoc' | |
|
139 | 146 | |
|
140 | 147 | |
|
141 | 148 | # Options for LaTeX output |
|
142 | 149 | # ------------------------ |
|
143 | 150 | |
|
144 | 151 | # The paper size ('letter' or 'a4'). |
|
145 | 152 | latex_paper_size = 'letter' |
|
146 | 153 | |
|
147 | 154 | # The font size ('10pt', '11pt' or '12pt'). |
|
148 | 155 | latex_font_size = '11pt' |
|
149 | 156 | |
|
150 | 157 | # Grouping the document tree into LaTeX files. List of tuples |
|
151 | 158 | # (source start file, target name, title, author, document class [howto/manual]). |
|
152 | 159 | |
|
153 | 160 | latex_documents = [ ('index', 'ipython.tex', 'IPython Documentation', |
|
154 | ur"""Brian Granger, Fernando Pérez and Ville Vainio\\ | |
|
155 | \ \\ | |
|
156 | With contributions from:\\ | |
|
157 | Benjamin Ragan-Kelley and Barry Wark.""", | |
|
161 | ur"""The IPython Development Team""", | |
|
158 | 162 | 'manual'), |
|
159 | 163 | ] |
|
160 | 164 | |
|
161 | 165 | # The name of an image file (relative to this directory) to place at the top of |
|
162 | 166 | # the title page. |
|
163 | 167 | #latex_logo = None |
|
164 | 168 | |
|
165 | 169 | # For "manual" documents, if this is true, then toplevel headings are parts, |
|
166 | 170 | # not chapters. |
|
167 | 171 | #latex_use_parts = False |
|
168 | 172 | |
|
169 | 173 | # Additional stuff for the LaTeX preamble. |
|
170 | 174 | #latex_preamble = '' |
|
171 | 175 | |
|
172 | 176 | # Documents to append as an appendix to all manuals. |
|
173 | 177 | #latex_appendices = [] |
|
174 | 178 | |
|
175 | 179 | # If false, no module index is generated. |
|
176 | 180 | #latex_use_modindex = True |
|
177 | 181 | |
|
178 | 182 | |
|
179 | # Cleanup: delete release info to avoid pickling errors from sphinx | |
|
183 | # Cleanup | |
|
184 | # ------- | |
|
185 | # delete release info to avoid pickling errors from sphinx | |
|
186 | ||
|
180 | 187 | del iprelease |
@@ -1,284 +1,286 b'' | |||
|
1 | 1 | .. _customization: |
|
2 | 2 | |
|
3 | 3 | ======================== |
|
4 | 4 | Customization of IPython |
|
5 | 5 | ======================== |
|
6 | 6 | |
|
7 | 7 | There are 2 ways to configure IPython - the old way of using ipythonrc |
|
8 | 8 | files (an INI-file like format), and the new way that involves editing |
|
9 | 9 | your ipy_user_conf.py. Both configuration systems work at the same |
|
10 | 10 | time, so you can set your options in both, but if you are hesitating |
|
11 | 11 | about which alternative to choose, we recommend the ipy_user_conf.py |
|
12 | 12 | approach, as it will give you more power and control in the long |
|
13 | 13 | run. However, there are few options such as pylab_import_all that can |
|
14 | 14 | only be specified in ipythonrc file or command line - the reason for |
|
15 | 15 | this is that they are needed before IPython has been started up, and |
|
16 | 16 | the IPApi object used in ipy_user_conf.py is not yet available at that |
|
17 | 17 | time. A hybrid approach of specifying a few options in ipythonrc and |
|
18 | 18 | doing the more advanced configuration in ipy_user_conf.py is also |
|
19 | 19 | possible. |
|
20 | 20 | |
|
21 | .. _ipythonrc: | |
|
22 | ||
|
21 | 23 | The ipythonrc approach |
|
22 | 24 | ====================== |
|
23 | 25 | |
|
24 | 26 | As we've already mentioned, IPython reads a configuration file which can |
|
25 | 27 | be specified at the command line (-rcfile) or which by default is |
|
26 | 28 | assumed to be called ipythonrc. Such a file is looked for in the current |
|
27 | 29 | directory where IPython is started and then in your IPYTHONDIR, which |
|
28 | 30 | allows you to have local configuration files for specific projects. In |
|
29 | 31 | this section we will call these types of configuration files simply |
|
30 | 32 | rcfiles (short for resource configuration file). |
|
31 | 33 | |
|
32 | 34 | The syntax of an rcfile is one of key-value pairs separated by |
|
33 | 35 | whitespace, one per line. Lines beginning with a # are ignored as |
|
34 | 36 | comments, but comments can not be put on lines with data (the parser is |
|
35 | 37 | fairly primitive). Note that these are not python files, and this is |
|
36 | 38 | deliberate, because it allows us to do some things which would be quite |
|
37 | 39 | tricky to implement if they were normal python files. |
|
38 | 40 | |
|
39 | First, an rcfile can contain permanent default values for almost all | |
|
40 |
|
|
|
41 |
|
|
|
42 | options. However, values you explicitly specify at the command line | |
|
43 |
|
|
|
41 | First, an rcfile can contain permanent default values for almost all command | |
|
42 | line options (except things like -help or -Version). :ref:`This section | |
|
43 | <command_line_options>` contains a description of all command-line | |
|
44 | options. However, values you explicitly specify at the command line override | |
|
45 | the values defined in the rcfile. | |
|
44 | 46 | |
|
45 | 47 | Besides command line option values, the rcfile can specify values for |
|
46 | 48 | certain extra special options which are not available at the command |
|
47 | 49 | line. These options are briefly described below. |
|
48 | 50 | |
|
49 | 51 | Each of these options may appear as many times as you need it in the file. |
|
50 | 52 | |
|
51 | 53 | * include <file1> <file2> ...: you can name other rcfiles you want |
|
52 | 54 | to recursively load up to 15 levels (don't use the <> brackets in |
|
53 | 55 | your names!). This feature allows you to define a 'base' rcfile |
|
54 | 56 | with general options and special-purpose files which can be loaded |
|
55 | 57 | only when needed with particular configuration options. To make |
|
56 | 58 | this more convenient, IPython accepts the -profile <name> option |
|
57 | 59 | (abbreviates to -p <name>) which tells it to look for an rcfile |
|
58 | 60 | named ipythonrc-<name>. |
|
59 | 61 | * import_mod <mod1> <mod2> ...: import modules with 'import |
|
60 | 62 | <mod1>,<mod2>,...' |
|
61 | 63 | * import_some <mod> <f1> <f2> ...: import functions with 'from |
|
62 | 64 | <mod> import <f1>,<f2>,...' |
|
63 | 65 | * import_all <mod1> <mod2> ...: for each module listed import |
|
64 | 66 | functions with ``from <mod> import *``. |
|
65 | 67 | * execute <python code>: give any single-line python code to be |
|
66 | 68 | executed. |
|
67 | 69 | * execfile <filename>: execute the python file given with an |
|
68 | 70 | 'execfile(filename)' command. Username expansion is performed on |
|
69 | 71 | the given names. So if you need any amount of extra fancy |
|
70 | 72 | customization that won't fit in any of the above 'canned' options, |
|
71 | 73 | you can just put it in a separate python file and execute it. |
|
72 | 74 | * alias <alias_def>: this is equivalent to calling |
|
73 | 75 | '%alias <alias_def>' at the IPython command line. This way, from |
|
74 | 76 | within IPython you can do common system tasks without having to |
|
75 | 77 | exit it or use the ! escape. IPython isn't meant to be a shell |
|
76 | 78 | replacement, but it is often very useful to be able to do things |
|
77 | 79 | with files while testing code. This gives you the flexibility to |
|
78 | 80 | have within IPython any aliases you may be used to under your |
|
79 | 81 | normal system shell. |
|
80 | 82 | |
|
81 | 83 | ipy_user_conf.py |
|
82 | 84 | ================ |
|
83 | 85 | |
|
84 | 86 | There should be a simple template ipy_user_conf.py file in your |
|
85 | 87 | ~/.ipython directory. It is a plain python module that is imported |
|
86 | 88 | during IPython startup, so you can do pretty much what you want there |
|
87 | 89 | - import modules, configure extensions, change options, define magic |
|
88 | 90 | commands, put variables and functions in the IPython namespace, |
|
89 | 91 | etc. You use the IPython extension api object, acquired by |
|
90 | 92 | IPython.ipapi.get() and documented in the "IPython extension API" |
|
91 | 93 | chapter, to interact with IPython. A sample ipy_user_conf.py is listed |
|
92 | 94 | below for reference:: |
|
93 | 95 | |
|
94 | 96 | # Most of your config files and extensions will probably start |
|
95 | 97 | # with this import |
|
96 | 98 | |
|
97 | 99 | import IPython.ipapi |
|
98 | 100 | ip = IPython.ipapi.get() |
|
99 | 101 | |
|
100 | 102 | # You probably want to uncomment this if you did %upgrade -nolegacy |
|
101 | 103 | # import ipy_defaults |
|
102 | 104 | |
|
103 | 105 | import os |
|
104 | 106 | |
|
105 | 107 | def main(): |
|
106 | 108 | |
|
107 | 109 | #ip.dbg.debugmode = True |
|
108 | 110 | ip.dbg.debug_stack() |
|
109 | 111 | |
|
110 | 112 | # uncomment if you want to get ipython -p sh behaviour |
|
111 | 113 | # without having to use command line switches |
|
112 | 114 | import ipy_profile_sh |
|
113 | 115 | import jobctrl |
|
114 | 116 | |
|
115 | 117 | # Configure your favourite editor? |
|
116 | 118 | # Good idea e.g. for %edit os.path.isfile |
|
117 | 119 | |
|
118 | 120 | #import ipy_editors |
|
119 | 121 | |
|
120 | 122 | # Choose one of these: |
|
121 | 123 | |
|
122 | 124 | #ipy_editors.scite() |
|
123 | 125 | #ipy_editors.scite('c:/opt/scite/scite.exe') |
|
124 | 126 | #ipy_editors.komodo() |
|
125 | 127 | #ipy_editors.idle() |
|
126 | 128 | # ... or many others, try 'ipy_editors??' after import to see them |
|
127 | 129 | |
|
128 | 130 | # Or roll your own: |
|
129 | 131 | #ipy_editors.install_editor("c:/opt/jed +$line $file") |
|
130 | 132 | |
|
131 | 133 | |
|
132 | 134 | o = ip.options |
|
133 | 135 | # An example on how to set options |
|
134 | 136 | #o.autocall = 1 |
|
135 | 137 | o.system_verbose = 0 |
|
136 | 138 | |
|
137 | 139 | #import_all("os sys") |
|
138 | 140 | #execf('~/_ipython/ns.py') |
|
139 | 141 | |
|
140 | 142 | |
|
141 | 143 | # -- prompt |
|
142 | 144 | # A different, more compact set of prompts from the default ones, that |
|
143 | 145 | # always show your current location in the filesystem: |
|
144 | 146 | |
|
145 | 147 | #o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>' |
|
146 | 148 | #o.prompt_in2 = r'.\D: ' |
|
147 | 149 | #o.prompt_out = r'[\#] ' |
|
148 | 150 | |
|
149 | 151 | # Try one of these color settings if you can't read the text easily |
|
150 | 152 | # autoexec is a list of IPython commands to execute on startup |
|
151 | 153 | #o.autoexec.append('%colors LightBG') |
|
152 | 154 | #o.autoexec.append('%colors NoColor') |
|
153 | 155 | o.autoexec.append('%colors Linux') |
|
154 | 156 | |
|
155 | 157 | |
|
156 | 158 | # some config helper functions you can use |
|
157 | 159 | def import_all(modules): |
|
158 | 160 | """ Usage: import_all("os sys") """ |
|
159 | 161 | for m in modules.split(): |
|
160 | 162 | ip.ex("from %s import *" % m) |
|
161 | 163 | |
|
162 | 164 | def execf(fname): |
|
163 | 165 | """ Execute a file in user namespace """ |
|
164 | 166 | ip.ex('execfile("%s")' % os.path.expanduser(fname)) |
|
165 | 167 | |
|
166 | 168 | main() |
|
167 | 169 | |
|
168 | 170 | .. _Prompts: |
|
169 | 171 | |
|
170 | 172 | Fine-tuning your prompt |
|
171 | 173 | ======================= |
|
172 | 174 | |
|
173 | 175 | IPython's prompts can be customized using a syntax similar to that of |
|
174 | 176 | the bash shell. Many of bash's escapes are supported, as well as a few |
|
175 | 177 | additional ones. We list them below:: |
|
176 | 178 | |
|
177 | 179 | \# |
|
178 | 180 | the prompt/history count number. This escape is automatically |
|
179 | 181 | wrapped in the coloring codes for the currently active color scheme. |
|
180 | 182 | \N |
|
181 | 183 | the 'naked' prompt/history count number: this is just the number |
|
182 | 184 | itself, without any coloring applied to it. This lets you produce |
|
183 | 185 | numbered prompts with your own colors. |
|
184 | 186 | \D |
|
185 | 187 | the prompt/history count, with the actual digits replaced by dots. |
|
186 | 188 | Used mainly in continuation prompts (prompt_in2) |
|
187 | 189 | \w |
|
188 | 190 | the current working directory |
|
189 | 191 | \W |
|
190 | 192 | the basename of current working directory |
|
191 | 193 | \Xn |
|
192 | 194 | where $n=0\ldots5.$ The current working directory, with $HOME |
|
193 | 195 | replaced by ~, and filtered out to contain only $n$ path elements |
|
194 | 196 | \Yn |
|
195 | 197 | Similar to \Xn, but with the $n+1$ element included if it is ~ (this |
|
196 | 198 | is similar to the behavior of the %cn escapes in tcsh) |
|
197 | 199 | \u |
|
198 | 200 | the username of the current user |
|
199 | 201 | \$ |
|
200 | 202 | if the effective UID is 0, a #, otherwise a $ |
|
201 | 203 | \h |
|
202 | 204 | the hostname up to the first '.' |
|
203 | 205 | \H |
|
204 | 206 | the hostname |
|
205 | 207 | \n |
|
206 | 208 | a newline |
|
207 | 209 | \r |
|
208 | 210 | a carriage return |
|
209 | 211 | \v |
|
210 | 212 | IPython version string |
|
211 | 213 | |
|
212 | 214 | In addition to these, ANSI color escapes can be insterted into the |
|
213 | 215 | prompts, as \C_ColorName. The list of valid color names is: Black, Blue, |
|
214 | 216 | Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray, |
|
215 | 217 | LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White, |
|
216 | 218 | Yellow. |
|
217 | 219 | |
|
218 | 220 | Finally, IPython supports the evaluation of arbitrary expressions in |
|
219 | 221 | your prompt string. The prompt strings are evaluated through the syntax |
|
220 | 222 | of PEP 215, but basically you can use $x.y to expand the value of x.y, |
|
221 | 223 | and for more complicated expressions you can use braces: ${foo()+x} will |
|
222 | 224 | call function foo and add to it the value of x, before putting the |
|
223 | 225 | result into your prompt. For example, using |
|
224 | 226 | prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: ' |
|
225 | 227 | will print the result of the uptime command on each prompt (assuming the |
|
226 | 228 | commands module has been imported in your ipythonrc file). |
|
227 | 229 | |
|
228 | 230 | |
|
229 | 231 | Prompt examples |
|
230 | 232 | |
|
231 | 233 | The following options in an ipythonrc file will give you IPython's |
|
232 | 234 | default prompts:: |
|
233 | 235 | |
|
234 | 236 | prompt_in1 'In [\#]:' |
|
235 | 237 | prompt_in2 ' .\D.:' |
|
236 | 238 | prompt_out 'Out[\#]:' |
|
237 | 239 | |
|
238 | 240 | which look like this:: |
|
239 | 241 | |
|
240 | 242 | In [1]: 1+2 |
|
241 | 243 | Out[1]: 3 |
|
242 | 244 | |
|
243 | 245 | In [2]: for i in (1,2,3): |
|
244 | 246 | ...: print i, |
|
245 | 247 | ...: |
|
246 | 248 | 1 2 3 |
|
247 | 249 | |
|
248 | 250 | These will give you a very colorful prompt with path information:: |
|
249 | 251 | |
|
250 | 252 | #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>' |
|
251 | 253 | prompt_in2 ' ..\D>' |
|
252 | 254 | prompt_out '<\#>' |
|
253 | 255 | |
|
254 | 256 | which look like this:: |
|
255 | 257 | |
|
256 | 258 | fperez[~/ipython]1> 1+2 |
|
257 | 259 | <1> 3 |
|
258 | 260 | fperez[~/ipython]2> for i in (1,2,3): |
|
259 | 261 | ...> print i, |
|
260 | 262 | ...> |
|
261 | 263 | 1 2 3 |
|
262 | 264 | |
|
263 | 265 | |
|
264 | 266 | .. _Profiles: |
|
265 | 267 | |
|
266 | 268 | IPython profiles |
|
267 | 269 | ================ |
|
268 | 270 | |
|
269 | As we already mentioned, IPython supports the -profile command-line | |
|
270 |
|
|
|
271 |
|
|
|
272 |
|
|
|
273 |
|
|
|
274 | IPYTHONDIR there is a file called ipythonrc-<name> or | |
|
275 | ipy_profile_<name>.py, and loads it instead of the normal ipythonrc. | |
|
271 | As we already mentioned, IPython supports the -profile command-line option (see | |
|
272 | :ref:`here <command_line_options>`). A profile is nothing more than a | |
|
273 | particular configuration file like your basic ipythonrc one, but with | |
|
274 | particular customizations for a specific purpose. When you start IPython with | |
|
275 | 'ipython -profile <name>', it assumes that in your IPYTHONDIR there is a file | |
|
276 | called ipythonrc-<name> or ipy_profile_<name>.py, and loads it instead of the | |
|
277 | normal ipythonrc. | |
|
276 | 278 | |
|
277 | 279 | This system allows you to maintain multiple configurations which load |
|
278 | 280 | modules, set options, define functions, etc. suitable for different |
|
279 | 281 | tasks and activate them in a very simple manner. In order to avoid |
|
280 | 282 | having to repeat all of your basic options (common things that don't |
|
281 | 283 | change such as your color preferences, for example), any profile can |
|
282 | 284 | include another configuration file. The most common way to use profiles |
|
283 | 285 | is then to have each one include your basic ipythonrc file as a starting |
|
284 | 286 | point, and then add further customizations. No newline at end of file |
@@ -1,243 +1,244 b'' | |||
|
1 | 1 | .. _initial config: |
|
2 | 2 | |
|
3 | 3 | ========================================= |
|
4 | 4 | Initial configuration of your environment |
|
5 | 5 | ========================================= |
|
6 | 6 | |
|
7 | 7 | This section will help you set various things in your environment for |
|
8 | 8 | your IPython sessions to be as efficient as possible. All of IPython's |
|
9 | 9 | configuration information, along with several example files, is stored |
|
10 | 10 | in a directory named by default $HOME/.ipython. You can change this by |
|
11 | 11 | defining the environment variable IPYTHONDIR, or at runtime with the |
|
12 | 12 | command line option -ipythondir. |
|
13 | 13 | |
|
14 | If all goes well, the first time you run IPython it should | |
|
15 |
|
|
|
16 | based on its builtin defaults. You can look at the files it creates to | |
|
17 | learn more about configuring the system. The main file you will modify | |
|
18 | to configure IPython's behavior is called ipythonrc (with a .ini | |
|
19 | extension under Windows), included for reference in `ipythonrc`_ | |
|
20 | section. This file is very commented and has many variables you can | |
|
21 | change to suit your taste, you can find more details in | |
|
22 | Sec. customization_. Here we discuss the basic things you will want to | |
|
23 | make sure things are working properly from the beginning. | |
|
14 | If all goes well, the first time you run IPython it should automatically create | |
|
15 | a user copy of the config directory for you, based on its builtin defaults. You | |
|
16 | can look at the files it creates to learn more about configuring the | |
|
17 | system. The main file you will modify to configure IPython's behavior is called | |
|
18 | ipythonrc (with a .ini extension under Windows), included for reference | |
|
19 | :ref:`here <ipythonrc>`. This file is very commented and has many variables you | |
|
20 | can change to suit your taste, you can find more details :ref:`here | |
|
21 | <customization>`. Here we discuss the basic things you will want to make sure | |
|
22 | things are working properly from the beginning. | |
|
24 | 23 | |
|
25 | 24 | |
|
26 |
.. _ |
|
|
25 | .. _accessing_help: | |
|
27 | 26 | |
|
28 | 27 | Access to the Python help system |
|
29 | 28 | ================================ |
|
30 | 29 | |
|
31 | This is true for Python in general (not just for IPython): you should | |
|
32 |
|
|
|
33 |
|
|
|
34 |
/usr/share/doc/python-doc |
|
|
35 |
|
|
|
30 | This is true for Python in general (not just for IPython): you should have an | |
|
31 | environment variable called PYTHONDOCS pointing to the directory where your | |
|
32 | HTML Python documentation lives. In my system it's | |
|
33 | :file:`/usr/share/doc/python-doc/html`, check your local details or ask your | |
|
34 | systems administrator. | |
|
36 | 35 | |
|
37 | 36 | This is the directory which holds the HTML version of the Python |
|
38 | 37 | manuals. Unfortunately it seems that different Linux distributions |
|
39 | 38 | package these files differently, so you may have to look around a bit. |
|
40 | 39 | Below I show the contents of this directory on my system for reference:: |
|
41 | 40 | |
|
42 | 41 | [html]> ls |
|
43 | about.dat acks.html dist/ ext/ index.html lib/ modindex.html | |
|
44 | stdabout.dat tut/ about.html api/ doc/ icons/ inst/ mac/ ref/ style.css | |
|
42 | about.html dist/ icons/ lib/ python2.5.devhelp.gz whatsnew/ | |
|
43 | acks.html doc/ index.html mac/ ref/ | |
|
44 | api/ ext/ inst/ modindex.html tut/ | |
|
45 | 45 | |
|
46 | 46 | You should really make sure this variable is correctly set so that |
|
47 | 47 | Python's pydoc-based help system works. It is a powerful and convenient |
|
48 | 48 | system with full access to the Python manuals and all modules accessible |
|
49 | 49 | to you. |
|
50 | 50 | |
|
51 | 51 | Under Windows it seems that pydoc finds the documentation automatically, |
|
52 | 52 | so no extra setup appears necessary. |
|
53 | 53 | |
|
54 | 54 | |
|
55 | 55 | Editor |
|
56 | 56 | ====== |
|
57 | 57 | |
|
58 | 58 | The %edit command (and its alias %ed) will invoke the editor set in your |
|
59 | 59 | environment as EDITOR. If this variable is not set, it will default to |
|
60 | 60 | vi under Linux/Unix and to notepad under Windows. You may want to set |
|
61 | 61 | this variable properly and to a lightweight editor which doesn't take |
|
62 | 62 | too long to start (that is, something other than a new instance of |
|
63 | 63 | Emacs). This way you can edit multi-line code quickly and with the power |
|
64 | 64 | of a real editor right inside IPython. |
|
65 | 65 | |
|
66 | 66 | If you are a dedicated Emacs user, you should set up the Emacs server so |
|
67 | 67 | that new requests are handled by the original process. This means that |
|
68 | 68 | almost no time is spent in handling the request (assuming an Emacs |
|
69 | 69 | process is already running). For this to work, you need to set your |
|
70 | 70 | EDITOR environment variable to 'emacsclient'. The code below, supplied |
|
71 | 71 | by Francois Pinard, can then be used in your .emacs file to enable the |
|
72 | 72 | server:: |
|
73 | 73 | |
|
74 | 74 | (defvar server-buffer-clients) |
|
75 | 75 | (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm)) |
|
76 | 76 | (server-start) |
|
77 | 77 | (defun fp-kill-server-with-buffer-routine () |
|
78 | 78 | (and server-buffer-clients (server-done))) |
|
79 | 79 | (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine)) |
|
80 | 80 | |
|
81 | 81 | You can also set the value of this editor via the commmand-line option |
|
82 | 82 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
83 | 83 | specifically for IPython an editor different from your typical default |
|
84 | 84 | (and for Windows users who tend to use fewer environment variables). |
|
85 | 85 | |
|
86 | 86 | |
|
87 | 87 | Color |
|
88 | 88 | ===== |
|
89 | 89 | |
|
90 | 90 | The default IPython configuration has most bells and whistles turned on |
|
91 | 91 | (they're pretty safe). But there's one that may cause problems on some |
|
92 | 92 | systems: the use of color on screen for displaying information. This is |
|
93 | 93 | very useful, since IPython can show prompts and exception tracebacks |
|
94 | 94 | with various colors, display syntax-highlighted source code, and in |
|
95 | 95 | general make it easier to visually parse information. |
|
96 | 96 | |
|
97 | 97 | The following terminals seem to handle the color sequences fine: |
|
98 | 98 | |
|
99 | 99 | * Linux main text console, KDE Konsole, Gnome Terminal, E-term, |
|
100 | 100 | rxvt, xterm. |
|
101 | 101 | * CDE terminal (tested under Solaris). This one boldfaces light colors. |
|
102 | 102 | * (X)Emacs buffers. See the emacs_ section for more details on |
|
103 | 103 | using IPython with (X)Emacs. |
|
104 | 104 | * A Windows (XP/2k) command prompt with pyreadline_. |
|
105 | 105 | * A Windows (XP/2k) CygWin shell. Although some users have reported |
|
106 | 106 | problems; it is not clear whether there is an issue for everyone |
|
107 | 107 | or only under specific configurations. If you have full color |
|
108 | 108 | support under cygwin, please post to the IPython mailing list so |
|
109 | 109 | this issue can be resolved for all users. |
|
110 | 110 | |
|
111 | .. _pyreadline: https://code.launchpad.net/pyreadline | |
|
112 | ||
|
111 | 113 | These have shown problems: |
|
112 | 114 | |
|
113 | 115 | * Windows command prompt in WinXP/2k logged into a Linux machine via |
|
114 | 116 | telnet or ssh. |
|
115 | 117 | * Windows native command prompt in WinXP/2k, without Gary Bishop's |
|
116 | 118 | extensions. Once Gary's readline library is installed, the normal |
|
117 | 119 | WinXP/2k command prompt works perfectly. |
|
118 | 120 | |
|
119 | 121 | Currently the following color schemes are available: |
|
120 | 122 | |
|
121 | 123 | * NoColor: uses no color escapes at all (all escapes are empty '' '' |
|
122 | 124 | strings). This 'scheme' is thus fully safe to use in any terminal. |
|
123 | 125 | * Linux: works well in Linux console type environments: dark |
|
124 | 126 | background with light fonts. It uses bright colors for |
|
125 | 127 | information, so it is difficult to read if you have a light |
|
126 | 128 | colored background. |
|
127 | 129 | * LightBG: the basic colors are similar to those in the Linux scheme |
|
128 | 130 | but darker. It is easy to read in terminals with light backgrounds. |
|
129 | 131 | |
|
130 | 132 | IPython uses colors for two main groups of things: prompts and |
|
131 | 133 | tracebacks which are directly printed to the terminal, and the object |
|
132 | 134 | introspection system which passes large sets of data through a pager. |
|
133 | 135 | |
|
134 | 136 | |
|
135 | 137 | Input/Output prompts and exception tracebacks |
|
136 | 138 | ============================================= |
|
137 | 139 | |
|
138 | 140 | You can test whether the colored prompts and tracebacks work on your |
|
139 | 141 | system interactively by typing '%colors Linux' at the prompt (use |
|
140 | 142 | '%colors LightBG' if your terminal has a light background). If the input |
|
141 | 143 | prompt shows garbage like:: |
|
142 | 144 | |
|
143 | 145 | [0;32mIn [[1;32m1[0;32m]: [0;00m |
|
144 | 146 | |
|
145 | 147 | instead of (in color) something like:: |
|
146 | 148 | |
|
147 | 149 | In [1]: |
|
148 | 150 | |
|
149 | 151 | this means that your terminal doesn't properly handle color escape |
|
150 | 152 | sequences. You can go to a 'no color' mode by typing '%colors NoColor'. |
|
151 | 153 | |
|
152 | 154 | You can try using a different terminal emulator program (Emacs users, |
|
153 | 155 | see below). To permanently set your color preferences, edit the file |
|
154 | 156 | $HOME/.ipython/ipythonrc and set the colors option to the desired value. |
|
155 | 157 | |
|
156 | 158 | |
|
157 | 159 | Object details (types, docstrings, source code, etc.) |
|
158 | 160 | ===================================================== |
|
159 | 161 | |
|
160 | IPython has a set of special functions for studying the objects you | |
|
161 | are working with, discussed in detail in Sec. `dynamic object | |
|
162 | information`_. But this system relies on passing information which is | |
|
163 | longer than your screen through a data pager, such as the common Unix | |
|
164 | less and more programs. In order to be able to see this information in | |
|
165 | color, your pager needs to be properly configured. I strongly | |
|
166 | recommend using less instead of more, as it seems that more simply can | |
|
162 | IPython has a set of special functions for studying the objects you are working | |
|
163 | with, discussed in detail :ref:`here <dynamic_object_info>`. But this system | |
|
164 | relies on passing information which is longer than your screen through a data | |
|
165 | pager, such as the common Unix less and more programs. In order to be able to | |
|
166 | see this information in color, your pager needs to be properly configured. I | |
|
167 | strongly recommend using less instead of more, as it seems that more simply can | |
|
167 | 168 | not understand colored text correctly. |
|
168 | 169 | |
|
169 | 170 | In order to configure less as your default pager, do the following: |
|
170 | 171 | |
|
171 | 172 | 1. Set the environment PAGER variable to less. |
|
172 | 173 | 2. Set the environment LESS variable to -r (plus any other options |
|
173 | 174 | you always want to pass to less by default). This tells less to |
|
174 | 175 | properly interpret control sequences, which is how color |
|
175 | 176 | information is given to your terminal. |
|
176 | 177 | |
|
177 | 178 | For the csh or tcsh shells, add to your ~/.cshrc file the lines:: |
|
178 | 179 | |
|
179 | 180 | setenv PAGER less |
|
180 | 181 | setenv LESS -r |
|
181 | 182 | |
|
182 | 183 | There is similar syntax for other Unix shells, look at your system |
|
183 | 184 | documentation for details. |
|
184 | 185 | |
|
185 | 186 | If you are on a system which lacks proper data pagers (such as Windows), |
|
186 | 187 | IPython will use a very limited builtin pager. |
|
187 | 188 | |
|
188 | 189 | .. _emacs: |
|
189 | 190 | |
|
190 | 191 | (X)Emacs configuration |
|
191 | 192 | ====================== |
|
192 | 193 | |
|
193 | 194 | Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, |
|
194 | 195 | currently (X)Emacs and IPython get along very well. |
|
195 | 196 | |
|
196 | 197 | Important note: You will need to use a recent enough version of |
|
197 | 198 | python-mode.el, along with the file ipython.el. You can check that the |
|
198 | 199 | version you have of python-mode.el is new enough by either looking at |
|
199 | 200 | the revision number in the file itself, or asking for it in (X)Emacs via |
|
200 | 201 | M-x py-version. Versions 4.68 and newer contain the necessary fixes for |
|
201 | 202 | proper IPython support. |
|
202 | 203 | |
|
203 | 204 | The file ipython.el is included with the IPython distribution, in the |
|
204 | 205 | documentation directory (where this manual resides in PDF and HTML |
|
205 | 206 | formats). |
|
206 | 207 | |
|
207 | 208 | Once you put these files in your Emacs path, all you need in your .emacs |
|
208 | 209 | file is:: |
|
209 | 210 | |
|
210 | 211 | (require 'ipython) |
|
211 | 212 | |
|
212 | 213 | This should give you full support for executing code snippets via |
|
213 | 214 | IPython, opening IPython as your Python shell via ``C-c !``, etc. |
|
214 | 215 | |
|
215 | 216 | You can customize the arguments passed to the IPython instance at startup by |
|
216 | 217 | setting the ``py-python-command-args`` variable. For example, to start always |
|
217 | 218 | in ``pylab`` mode with hardcoded light-background colors, you can use:: |
|
218 | 219 | |
|
219 | 220 | (setq py-python-command-args '("-pylab" "-colors" "LightBG")) |
|
220 | 221 | |
|
221 | 222 | If you happen to get garbage instead of colored prompts as described in |
|
222 | 223 | the previous section, you may need to set also in your .emacs file:: |
|
223 | 224 | |
|
224 | 225 | (setq ansi-color-for-comint-mode t) |
|
225 | 226 | |
|
226 | 227 | Notes: |
|
227 | 228 | |
|
228 | 229 | * There is one caveat you should be aware of: you must start the |
|
229 | 230 | IPython shell before attempting to execute any code regions via |
|
230 | 231 | ``C-c |``. Simply type C-c ! to start IPython before passing any code |
|
231 | 232 | regions to the interpreter, and you shouldn't experience any |
|
232 | 233 | problems. |
|
233 | 234 | This is due to a bug in Python itself, which has been fixed for |
|
234 | 235 | Python 2.3, but exists as of Python 2.2.2 (reported as SF bug [ |
|
235 | 236 | 737947 ]). |
|
236 | 237 | * The (X)Emacs support is maintained by Alexander Schmolck, so all |
|
237 | 238 | comments/requests should be directed to him through the IPython |
|
238 | 239 | mailing lists. |
|
239 | 240 | * This code is still somewhat experimental so it's a bit rough |
|
240 | 241 | around the edges (although in practice, it works quite well). |
|
241 | 242 | * Be aware that if you customize py-python-command previously, this |
|
242 | 243 | value will override what ipython.el does (because loading the |
|
243 | 244 | customization variables comes later). |
@@ -1,139 +1,207 b'' | |||
|
1 | 1 | .. _credits: |
|
2 | 2 | |
|
3 | 3 | ======= |
|
4 | 4 | Credits |
|
5 | 5 | ======= |
|
6 | 6 | |
|
7 |
IPython is |
|
|
8 | <Fernando.Perez@colorado.edu>, but the project was born from mixing in | |
|
9 | Fernando's code with the IPP project by Janko Hauser | |
|
10 | <jhauser-AT-zscout.de> and LazyPython by Nathan Gray | |
|
11 | <n8gray-AT-caltech.edu>. For all IPython-related requests, please | |
|
12 | contact Fernando. | |
|
13 | ||
|
14 | As of early 2006, the following developers have joined the core team: | |
|
15 | ||
|
16 | * [Robert Kern] <rkern-AT-enthought.com>: co-mentored the 2005 | |
|
17 | Google Summer of Code project to develop python interactive | |
|
18 | notebooks (XML documents) and graphical interface. This project | |
|
19 | was awarded to the students Tzanko Matev <tsanko-AT-gmail.com> and | |
|
20 | Toni Alatalo <antont-AT-an.org> | |
|
21 | * [Brian Granger] <bgranger-AT-scu.edu>: extending IPython to allow | |
|
22 | support for interactive parallel computing. | |
|
23 |
|
|
|
24 | maintainer for the main trunk of IPython after version 0.7.1. | |
|
7 | IPython is led by Fernando Pérez. | |
|
8 | ||
|
9 | As of this writing, the following developers have joined the core team: | |
|
10 | ||
|
11 | * [Robert Kern] <rkern-AT-enthought.com>: co-mentored the 2005 | |
|
12 | Google Summer of Code project to develop python interactive | |
|
13 | notebooks (XML documents) and graphical interface. This project | |
|
14 | was awarded to the students Tzanko Matev <tsanko-AT-gmail.com> and | |
|
15 | Toni Alatalo <antont-AT-an.org>. | |
|
16 | ||
|
17 | * [Brian Granger] <ellisonbg-AT-gmail.com>: extending IPython to allow | |
|
18 | support for interactive parallel computing. | |
|
19 | ||
|
20 | * [Benjamin (Min) Ragan-Kelley]: key work on IPython's parallel | |
|
21 | computing infrastructure. | |
|
22 | ||
|
23 | * [Ville Vainio] <vivainio-AT-gmail.com>: Ville has made many improvements | |
|
24 | to the core of IPython and was the maintainer of the main IPython | |
|
25 | trunk from version 0.7.1 to 0.8.4. | |
|
26 | ||
|
27 | * [Gael Varoquaux] <gael.varoquaux-AT-normalesup.org>: work on the merged | |
|
28 | architecture for the interpreter as of version 0.9, implementing a new WX GUI | |
|
29 | based on this system. | |
|
30 | ||
|
31 | * [Barry Wark] <barrywark-AT-gmail.com>: implementing a new Cocoa GUI, as well | |
|
32 | as work on the new interpreter architecture and Twisted support. | |
|
33 | ||
|
34 | * [Laurent Dufrechou] <laurent.dufrechou-AT-gmail.com>: development of the WX | |
|
35 | GUI support. | |
|
36 | ||
|
37 | * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu>: maintainer of the | |
|
38 | PyReadline project, necessary for IPython under windows. | |
|
39 | ||
|
25 | 40 | |
|
26 | 41 | The IPython project is also very grateful to: |
|
27 | 42 | |
|
28 | 43 | Bill Bumgarner <bbum-AT-friday.com>: for providing the DPyGetOpt module |
|
29 | 44 | which gives very powerful and convenient handling of command-line |
|
30 | 45 | options (light years ahead of what Python 2.1.1's getopt module does). |
|
31 | 46 | |
|
32 | 47 | Ka-Ping Yee <ping-AT-lfw.org>: for providing the Itpl module for |
|
33 | 48 | convenient and powerful string interpolation with a much nicer syntax |
|
34 | 49 | than formatting through the '%' operator. |
|
35 | 50 | |
|
36 | 51 | Arnd Baecker <baecker-AT-physik.tu-dresden.de>: for his many very useful |
|
37 | 52 | suggestions and comments, and lots of help with testing and |
|
38 | 53 | documentation checking. Many of IPython's newer features are a result of |
|
39 | 54 | discussions with him (bugs are still my fault, not his). |
|
40 | 55 | |
|
41 | 56 | Obviously Guido van Rossum and the whole Python development team, that |
|
42 | 57 | goes without saying. |
|
43 | 58 | |
|
44 | 59 | IPython's website is generously hosted at http://ipython.scipy.orgby |
|
45 | 60 | Enthought (http://www.enthought.com). I am very grateful to them and all |
|
46 | 61 | of the SciPy team for their contribution. |
|
47 | 62 | |
|
48 | 63 | Fernando would also like to thank Stephen Figgins <fig-AT-monitor.net>, |
|
49 | 64 | an O'Reilly Python editor. His Oct/11/2001 article about IPP and |
|
50 | 65 | LazyPython, was what got this project started. You can read it at: |
|
51 | 66 | http://www.onlamp.com/pub/a/python/2001/10/11/pythonnews.html. |
|
52 | 67 | |
|
53 | And last but not least, all the kind IPython users who have emailed new | |
|
54 |
|
|
|
55 |
|
|
|
56 | ||
|
57 | * [Jack Moffit] <jack-AT-xiph.org> Bug fixes, including the infamous | |
|
58 | color problem. This bug alone caused many lost hours and | |
|
59 | frustration, many thanks to him for the fix. I've always been a | |
|
60 | fan of Ogg & friends, now I have one more reason to like these folks. | |
|
61 | Jack is also contributing with Debian packaging and many other | |
|
62 | things. | |
|
63 | * [Alexander Schmolck] <a.schmolck-AT-gmx.net> Emacs work, bug | |
|
64 | reports, bug fixes, ideas, lots more. The ipython.el mode for | |
|
65 | (X)Emacs is Alex's code, providing full support for IPython under | |
|
66 | (X)Emacs. | |
|
67 | * [Andrea Riciputi] <andrea.riciputi-AT-libero.it> Mac OSX | |
|
68 | information, Fink package management. | |
|
69 | * [Gary Bishop] <gb-AT-cs.unc.edu> Bug reports, and patches to work | |
|
70 | around the exception handling idiosyncracies of WxPython. Readline | |
|
71 | and color support for Windows. | |
|
72 | * [Jeffrey Collins] <Jeff.Collins-AT-vexcel.com> Bug reports. Much | |
|
73 | improved readline support, including fixes for Python 2.3. | |
|
74 | * [Dryice Liu] <dryice-AT-liu.com.cn> FreeBSD port. | |
|
75 | * [Mike Heeter] <korora-AT-SDF.LONESTAR.ORG> | |
|
76 | * [Christopher Hart] <hart-AT-caltech.edu> PDB integration. | |
|
77 | * [Milan Zamazal] <pdm-AT-zamazal.org> Emacs info. | |
|
78 | * [Philip Hisley] <compsys-AT-starpower.net> | |
|
79 | * [Holger Krekel] <pyth-AT-devel.trillke.net> Tab completion, lots | |
|
80 | more. | |
|
81 | * [Robin Siebler] <robinsiebler-AT-starband.net> | |
|
82 | * [Ralf Ahlbrink] <ralf_ahlbrink-AT-web.de> | |
|
83 | * [Thorsten Kampe] <thorsten-AT-thorstenkampe.de> | |
|
84 | * [Fredrik Kant] <fredrik.kant-AT-front.com> Windows setup. | |
|
85 | * [Syver Enstad] <syver-en-AT-online.no> Windows setup. | |
|
86 | * [Richard] <rxe-AT-renre-europe.com> Global embedding. | |
|
87 | * [Hayden Callow] <h.callow-AT-elec.canterbury.ac.nz> Gnuplot.py 1.6 | |
|
88 | compatibility. | |
|
89 | * [Leonardo Santagada] <retype-AT-terra.com.br> Fixes for Windows | |
|
90 | installation. | |
|
91 | * [Christopher Armstrong] <radix-AT-twistedmatrix.com> Bugfixes. | |
|
92 | * [Francois Pinard] <pinard-AT-iro.umontreal.ca> Code and | |
|
93 | documentation fixes. | |
|
94 | * [Cory Dodt] <cdodt-AT-fcoe.k12.ca.us> Bug reports and Windows | |
|
95 | ideas. Patches for Windows installer. | |
|
96 | * [Olivier Aubert] <oaubert-AT-bat710.univ-lyon1.fr> New magics. | |
|
97 | * [King C. Shu] <kingshu-AT-myrealbox.com> Autoindent patch. | |
|
98 | * [Chris Drexler] <chris-AT-ac-drexler.de> Readline packages for | |
|
99 | Win32/CygWin. | |
|
100 | * [Gustavo Cordova Avila] <gcordova-AT-sismex.com> EvalDict code for | |
|
101 | nice, lightweight string interpolation. | |
|
102 | * [Kasper Souren] <Kasper.Souren-AT-ircam.fr> Bug reports, ideas. | |
|
103 | * [Gever Tulley] <gever-AT-helium.com> Code contributions. | |
|
104 | * [Ralf Schmitt] <ralf-AT-brainbot.com> Bug reports & fixes. | |
|
105 | * [Oliver Sander] <osander-AT-gmx.de> Bug reports. | |
|
106 | * [Rod Holland] <rhh-AT-structurelabs.com> Bug reports and fixes to | |
|
107 | logging module. | |
|
108 | * [Daniel 'Dang' Griffith] <pythondev-dang-AT-lazytwinacres.net> | |
|
109 | Fixes, enhancement suggestions for system shell use. | |
|
110 | * [Viktor Ransmayr] <viktor.ransmayr-AT-t-online.de> Tests and | |
|
111 | reports on Windows installation issues. Contributed a true Windows | |
|
112 | binary installer. | |
|
113 | * [Mike Salib] <msalib-AT-mit.edu> Help fixing a subtle bug related | |
|
114 | to traceback printing. | |
|
115 | * [W.J. van der Laan] <gnufnork-AT-hetdigitalegat.nl> Bash-like | |
|
116 | prompt specials. | |
|
117 | * [Antoon Pardon] <Antoon.Pardon-AT-rece.vub.ac.be> Critical fix for | |
|
118 | the multithreaded IPython. | |
|
119 | * [John Hunter] <jdhunter-AT-nitace.bsd.uchicago.edu> Matplotlib | |
|
120 | author, helped with all the development of support for matplotlib | |
|
121 | in IPyhton, including making necessary changes to matplotlib itself. | |
|
122 | * [Matthew Arnison] <maffew-AT-cat.org.au> Bug reports, '%run -d' idea. | |
|
123 | * [Prabhu Ramachandran] <prabhu_r-AT-users.sourceforge.net> Help | |
|
124 | with (X)Emacs support, threading patches, ideas... | |
|
125 | * [Norbert Tretkowski] <tretkowski-AT-inittab.de> help with Debian | |
|
126 | packaging and distribution. | |
|
127 | * [George Sakkis] <gsakkis-AT-eden.rutgers.edu> New matcher for | |
|
128 | tab-completing named arguments of user-defined functions. | |
|
129 | * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu> Wildcard | |
|
130 | support implementation for searching namespaces. | |
|
131 | * [Vivian De Smedt] <vivian-AT-vdesmedt.com> Debugger enhancements, | |
|
132 | so that when pdb is activated from within IPython, coloring, tab | |
|
133 | completion and other features continue to work seamlessly. | |
|
134 | * [Scott Tsai] <scottt958-AT-yahoo.com.tw> Support for automatic | |
|
135 | editor invocation on syntax errors (see | |
|
136 | http://www.scipy.net/roundup/ipython/issue36). | |
|
137 | * [Alexander Belchenko] <bialix-AT-ukr.net> Improvements for win32 | |
|
138 | paging system. | |
|
139 | * [Will Maier] <willmaier-AT-ml1.net> Official OpenBSD port. No newline at end of file | |
|
68 | And last but not least, all the kind IPython users who have emailed new code, | |
|
69 | bug reports, fixes, comments and ideas. A brief list follows, please let us | |
|
70 | know if we have ommitted your name by accident: | |
|
71 | ||
|
72 | * Dan Milstein <danmil-AT-comcast.net>. A bold refactoring of the | |
|
73 | core prefilter stuff in the IPython interpreter. | |
|
74 | ||
|
75 | * [Jack Moffit] <jack-AT-xiph.org> Bug fixes, including the infamous | |
|
76 | color problem. This bug alone caused many lost hours and | |
|
77 | frustration, many thanks to him for the fix. I've always been a | |
|
78 | fan of Ogg & friends, now I have one more reason to like these folks. | |
|
79 | Jack is also contributing with Debian packaging and many other | |
|
80 | things. | |
|
81 | ||
|
82 | * [Alexander Schmolck] <a.schmolck-AT-gmx.net> Emacs work, bug | |
|
83 | reports, bug fixes, ideas, lots more. The ipython.el mode for | |
|
84 | (X)Emacs is Alex's code, providing full support for IPython under | |
|
85 | (X)Emacs. | |
|
86 | ||
|
87 | * [Andrea Riciputi] <andrea.riciputi-AT-libero.it> Mac OSX | |
|
88 | information, Fink package management. | |
|
89 | ||
|
90 | * [Gary Bishop] <gb-AT-cs.unc.edu> Bug reports, and patches to work | |
|
91 | around the exception handling idiosyncracies of WxPython. Readline | |
|
92 | and color support for Windows. | |
|
93 | ||
|
94 | * [Jeffrey Collins] <Jeff.Collins-AT-vexcel.com> Bug reports. Much | |
|
95 | improved readline support, including fixes for Python 2.3. | |
|
96 | ||
|
97 | * [Dryice Liu] <dryice-AT-liu.com.cn> FreeBSD port. | |
|
98 | ||
|
99 | * [Mike Heeter] <korora-AT-SDF.LONESTAR.ORG> | |
|
100 | ||
|
101 | * [Christopher Hart] <hart-AT-caltech.edu> PDB integration. | |
|
102 | ||
|
103 | * [Milan Zamazal] <pdm-AT-zamazal.org> Emacs info. | |
|
104 | ||
|
105 | * [Philip Hisley] <compsys-AT-starpower.net> | |
|
106 | ||
|
107 | * [Holger Krekel] <pyth-AT-devel.trillke.net> Tab completion, lots | |
|
108 | more. | |
|
109 | ||
|
110 | * [Robin Siebler] <robinsiebler-AT-starband.net> | |
|
111 | ||
|
112 | * [Ralf Ahlbrink] <ralf_ahlbrink-AT-web.de> | |
|
113 | ||
|
114 | * [Thorsten Kampe] <thorsten-AT-thorstenkampe.de> | |
|
115 | ||
|
116 | * [Fredrik Kant] <fredrik.kant-AT-front.com> Windows setup. | |
|
117 | ||
|
118 | * [Syver Enstad] <syver-en-AT-online.no> Windows setup. | |
|
119 | ||
|
120 | * [Richard] <rxe-AT-renre-europe.com> Global embedding. | |
|
121 | ||
|
122 | * [Hayden Callow] <h.callow-AT-elec.canterbury.ac.nz> Gnuplot.py 1.6 | |
|
123 | compatibility. | |
|
124 | ||
|
125 | * [Leonardo Santagada] <retype-AT-terra.com.br> Fixes for Windows | |
|
126 | installation. | |
|
127 | ||
|
128 | * [Christopher Armstrong] <radix-AT-twistedmatrix.com> Bugfixes. | |
|
129 | ||
|
130 | * [Francois Pinard] <pinard-AT-iro.umontreal.ca> Code and | |
|
131 | documentation fixes. | |
|
132 | ||
|
133 | * [Cory Dodt] <cdodt-AT-fcoe.k12.ca.us> Bug reports and Windows | |
|
134 | ideas. Patches for Windows installer. | |
|
135 | ||
|
136 | * [Olivier Aubert] <oaubert-AT-bat710.univ-lyon1.fr> New magics. | |
|
137 | ||
|
138 | * [King C. Shu] <kingshu-AT-myrealbox.com> Autoindent patch. | |
|
139 | ||
|
140 | * [Chris Drexler] <chris-AT-ac-drexler.de> Readline packages for | |
|
141 | Win32/CygWin. | |
|
142 | ||
|
143 | * [Gustavo Cordova Avila] <gcordova-AT-sismex.com> EvalDict code for | |
|
144 | nice, lightweight string interpolation. | |
|
145 | ||
|
146 | * [Kasper Souren] <Kasper.Souren-AT-ircam.fr> Bug reports, ideas. | |
|
147 | ||
|
148 | * [Gever Tulley] <gever-AT-helium.com> Code contributions. | |
|
149 | ||
|
150 | * [Ralf Schmitt] <ralf-AT-brainbot.com> Bug reports & fixes. | |
|
151 | ||
|
152 | * [Oliver Sander] <osander-AT-gmx.de> Bug reports. | |
|
153 | ||
|
154 | * [Rod Holland] <rhh-AT-structurelabs.com> Bug reports and fixes to | |
|
155 | logging module. | |
|
156 | ||
|
157 | * [Daniel 'Dang' Griffith] <pythondev-dang-AT-lazytwinacres.net> | |
|
158 | Fixes, enhancement suggestions for system shell use. | |
|
159 | ||
|
160 | * [Viktor Ransmayr] <viktor.ransmayr-AT-t-online.de> Tests and | |
|
161 | reports on Windows installation issues. Contributed a true Windows | |
|
162 | binary installer. | |
|
163 | ||
|
164 | * [Mike Salib] <msalib-AT-mit.edu> Help fixing a subtle bug related | |
|
165 | to traceback printing. | |
|
166 | ||
|
167 | * [W.J. van der Laan] <gnufnork-AT-hetdigitalegat.nl> Bash-like | |
|
168 | prompt specials. | |
|
169 | ||
|
170 | * [Antoon Pardon] <Antoon.Pardon-AT-rece.vub.ac.be> Critical fix for | |
|
171 | the multithreaded IPython. | |
|
172 | ||
|
173 | * [John Hunter] <jdhunter-AT-nitace.bsd.uchicago.edu> Matplotlib | |
|
174 | author, helped with all the development of support for matplotlib | |
|
175 | in IPyhton, including making necessary changes to matplotlib itself. | |
|
176 | ||
|
177 | * [Matthew Arnison] <maffew-AT-cat.org.au> Bug reports, '%run -d' idea. | |
|
178 | ||
|
179 | * [Prabhu Ramachandran] <prabhu_r-AT-users.sourceforge.net> Help | |
|
180 | with (X)Emacs support, threading patches, ideas... | |
|
181 | ||
|
182 | * [Norbert Tretkowski] <tretkowski-AT-inittab.de> help with Debian | |
|
183 | packaging and distribution. | |
|
184 | ||
|
185 | * [George Sakkis] <gsakkis-AT-eden.rutgers.edu> New matcher for | |
|
186 | tab-completing named arguments of user-defined functions. | |
|
187 | ||
|
188 | * [Jörgen Stenarson] <jorgen.stenarson-AT-bostream.nu> Wildcard | |
|
189 | support implementation for searching namespaces. | |
|
190 | ||
|
191 | * [Vivian De Smedt] <vivian-AT-vdesmedt.com> Debugger enhancements, | |
|
192 | so that when pdb is activated from within IPython, coloring, tab | |
|
193 | completion and other features continue to work seamlessly. | |
|
194 | ||
|
195 | * [Scott Tsai] <scottt958-AT-yahoo.com.tw> Support for automatic | |
|
196 | editor invocation on syntax errors (see | |
|
197 | http://www.scipy.net/roundup/ipython/issue36). | |
|
198 | ||
|
199 | * [Alexander Belchenko] <bialix-AT-ukr.net> Improvements for win32 | |
|
200 | paging system. | |
|
201 | ||
|
202 | * [Will Maier] <willmaier-AT-ml1.net> Official OpenBSD port. | |
|
203 | ||
|
204 | * [Ondrej Certik] <ondrej-AT-certik.cz>: set up the IPython docs to use the new | |
|
205 | Sphinx system used by Python, Matplotlib and many more projects. | |
|
206 | ||
|
207 | * [Stefan van der Walt] <stefan-AT-sun.ac.za>: support for the new config system. |
@@ -1,397 +1,426 b'' | |||
|
1 | 1 | .. _development: |
|
2 | 2 | |
|
3 | 3 | ================================== |
|
4 | 4 | IPython development guidelines |
|
5 | 5 | ================================== |
|
6 | 6 | |
|
7 | 7 | .. contents:: |
|
8 | 8 | |
|
9 | 9 | |
|
10 | 10 | Overview |
|
11 | 11 | ======== |
|
12 | 12 | |
|
13 | 13 | IPython is the next generation of IPython. It is named such for two reasons: |
|
14 | 14 | |
|
15 | 15 | - Eventually, IPython will become IPython version 1.0. |
|
16 | 16 | - This new code base needs to be able to co-exist with the existing IPython until |
|
17 | 17 | it is a full replacement for it. Thus we needed a different name. We couldn't |
|
18 | 18 | use ``ipython`` (lowercase) as some files systems are case insensitive. |
|
19 | 19 | |
|
20 | 20 | There are two, no three, main goals of the IPython effort: |
|
21 | 21 | |
|
22 | 22 | 1. Clean up the existing codebase and write lots of tests. |
|
23 | 23 | 2. Separate the core functionality of IPython from the terminal to enable IPython |
|
24 | 24 | to be used from within a variety of GUI applications. |
|
25 | 25 | 3. Implement a system for interactive parallel computing. |
|
26 | 26 | |
|
27 |
While the third goal may seem a bit unrelated to the main focus of IPython, it |
|
|
28 |
out that the technologies required for this goal are nearly identical |
|
|
29 |
required for goal two. This is the main reason the interactive |
|
|
30 |
capabilities are being put into IPython proper. Currently |
|
|
31 | furthest along. | |
|
27 | While the third goal may seem a bit unrelated to the main focus of IPython, it | |
|
28 | turns out that the technologies required for this goal are nearly identical | |
|
29 | with those required for goal two. This is the main reason the interactive | |
|
30 | parallel computing capabilities are being put into IPython proper. Currently | |
|
31 | the third of these goals is furthest along. | |
|
32 | 32 | |
|
33 | 33 | This document describes IPython from the perspective of developers. |
|
34 | 34 | |
|
35 | 35 | |
|
36 | 36 | Project organization |
|
37 | 37 | ==================== |
|
38 | 38 | |
|
39 | 39 | Subpackages |
|
40 | 40 | ----------- |
|
41 | 41 | |
|
42 |
IPython is organized into semi self-contained subpackages. Each of the |
|
|
42 | IPython is organized into semi self-contained subpackages. Each of the | |
|
43 | subpackages will have its own: | |
|
43 | 44 | |
|
44 | 45 | - **Dependencies**. One of the most important things to keep in mind in |
|
45 | 46 | partitioning code amongst subpackages, is that they should be used to cleanly |
|
46 |
encapsulate dependencies. |
|
|
47 | encapsulate dependencies. | |
|
48 | ||
|
47 | 49 | - **Tests**. Each subpackage shoud have its own ``tests`` subdirectory that |
|
48 |
contains all of the tests for that package. For information about writing |
|
|
49 | for IPython, see the `Testing System`_ section of this document. | |
|
50 | - **Configuration**. Each subpackage should have its own ``config`` subdirectory | |
|
51 | that contains the configuration information for the components of the | |
|
52 | subpackage. For information about how the IPython configuration system | |
|
53 | works, see the `Configuration System`_ section of this document. | |
|
54 | - **Scripts**. Each subpackage should have its own ``scripts`` subdirectory that | |
|
55 | contains all of the command line scripts associated with the subpackage. | |
|
50 | contains all of the tests for that package. For information about writing | |
|
51 | tests for IPython, see the `Testing System`_ section of this document. | |
|
52 | ||
|
53 | - **Configuration**. Each subpackage should have its own ``config`` | |
|
54 | subdirectory that contains the configuration information for the components | |
|
55 | of the subpackage. For information about how the IPython configuration | |
|
56 | system works, see the `Configuration System`_ section of this document. | |
|
57 | ||
|
58 | - **Scripts**. Each subpackage should have its own ``scripts`` subdirectory | |
|
59 | that contains all of the command line scripts associated with the subpackage. | |
|
56 | 60 | |
|
57 | 61 | Installation and dependencies |
|
58 | 62 | ----------------------------- |
|
59 | 63 | |
|
60 |
IPython will not use `setuptools`_ for installation. Instead, we will use |
|
|
61 |
``setup.py`` scripts that use `distutils`_. While there are a number a |
|
|
62 |
features that `setuptools`_ has (like namespace packages), the |
|
|
63 |
of `setuptools`_ has performance problems, particularly |
|
|
64 |
particular, when Python packages are installed on |
|
|
65 |
become much too long (up towards 10 seconds). |
|
|
64 | IPython will not use `setuptools`_ for installation. Instead, we will use | |
|
65 | standard ``setup.py`` scripts that use `distutils`_. While there are a number a | |
|
66 | extremely nice features that `setuptools`_ has (like namespace packages), the | |
|
67 | current implementation of `setuptools`_ has performance problems, particularly | |
|
68 | on shared file systems. In particular, when Python packages are installed on | |
|
69 | NSF file systems, import times become much too long (up towards 10 seconds). | |
|
66 | 70 | |
|
67 | 71 | Because IPython is being used extensively in the context of high performance |
|
68 |
computing, where performance is critical but shared file systems are common, we |
|
|
69 |
these performance hits are not acceptable. Thus, until the performance |
|
|
70 |
associated with `setuptools`_ are addressed, we will stick with plain |
|
|
71 |
are hopeful that these problems will be addressed and that we |
|
|
72 |
using `setuptools`_. Because of this, we are trying to |
|
|
73 | will make the eventual transition to `setuptools`_ as painless as possible. | |
|
74 | ||
|
75 | Because we will be using `distutils`_, there will be no method for automatically installing dependencies. Instead, we are following the approach of `Matplotlib`_ which can be summarized as follows: | |
|
72 | computing, where performance is critical but shared file systems are common, we | |
|
73 | feel these performance hits are not acceptable. Thus, until the performance | |
|
74 | problems associated with `setuptools`_ are addressed, we will stick with plain | |
|
75 | `distutils`_. We are hopeful that these problems will be addressed and that we | |
|
76 | will eventually begin using `setuptools`_. Because of this, we are trying to | |
|
77 | organize IPython in a way that will make the eventual transition to | |
|
78 | `setuptools`_ as painless as possible. | |
|
79 | ||
|
80 | Because we will be using `distutils`_, there will be no method for | |
|
81 | automatically installing dependencies. Instead, we are following the approach | |
|
82 | of `Matplotlib`_ which can be summarized as follows: | |
|
76 | 83 | |
|
77 | 84 | - Distinguish between required and optional dependencies. However, the required |
|
78 | 85 | dependencies for IPython should be only the Python standard library. |
|
79 | - Upon installation check to see which optional dependencies are present and tell | |
|
80 | the user which parts of IPython need which optional dependencies. | |
|
86 | ||
|
87 | - Upon installation check to see which optional dependencies are present and | |
|
88 | tell the user which parts of IPython need which optional dependencies. | |
|
81 | 89 | |
|
82 |
It is absolutely critical that each subpackage of IPython has a clearly |
|
|
83 |
of dependencies and that dependencies are not carelessly |
|
|
84 |
subpackages. Furthermore, tests that have certain |
|
|
85 | those dependencies are not present. Instead they should be skipped and print a | |
|
86 | message. | |
|
90 | It is absolutely critical that each subpackage of IPython has a clearly | |
|
91 | specified set of dependencies and that dependencies are not carelessly | |
|
92 | inherited from other IPython subpackages. Furthermore, tests that have certain | |
|
93 | dependencies should not fail if those dependencies are not present. Instead | |
|
94 | they should be skipped and print a message. | |
|
87 | 95 | |
|
88 | 96 | .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools |
|
89 | 97 | .. _distutils: http://docs.python.org/lib/module-distutils.html |
|
90 | 98 | .. _Matplotlib: http://matplotlib.sourceforge.net/ |
|
91 | 99 | |
|
92 | 100 | Specific subpackages |
|
93 | 101 | -------------------- |
|
94 | 102 | |
|
95 | 103 | ``core`` |
|
96 | 104 | This is the core functionality of IPython that is independent of the |
|
97 | 105 | terminal, network and GUIs. Most of the code that is in the current |
|
98 | 106 | IPython trunk will be refactored, cleaned up and moved here. |
|
99 | 107 | |
|
100 | 108 | ``kernel`` |
|
101 | 109 | The enables the IPython core to be expose to a the network. This is |
|
102 | 110 | also where all of the parallel computing capabilities are to be found. |
|
103 | 111 | |
|
104 | 112 | ``config`` |
|
105 | 113 | The configuration package used by IPython. |
|
106 | 114 | |
|
107 | 115 | ``frontends`` |
|
108 | 116 | The various frontends for IPython. A frontend is the end-user application |
|
109 |
that exposes the capabilities of IPython to the user. The most basic |
|
|
110 |
will simply be a terminal based application that looks just like |
|
|
111 |
IPython. Other frontends will likely be more powerful and based |
|
|
117 | that exposes the capabilities of IPython to the user. The most basic | |
|
118 | frontend will simply be a terminal based application that looks just like | |
|
119 | today 's IPython. Other frontends will likely be more powerful and based | |
|
120 | on GUI toolkits. | |
|
112 | 121 | |
|
113 | 122 | ``notebook`` |
|
114 | 123 | An application that allows users to work with IPython notebooks. |
|
115 | 124 | |
|
116 | 125 | ``tools`` |
|
117 | 126 | This is where general utilities go. |
|
118 | 127 | |
|
119 | 128 | |
|
120 | 129 | Version control |
|
121 | 130 | =============== |
|
122 | 131 | |
|
123 |
In the past, IPython development has been done using `Subversion`__. Recently, |
|
|
124 | to contribute code to IPython. Here is a sketch of how to use Bazaar for IPython | |
|
125 | development. First, you should install Bazaar. After you have done that, make | |
|
126 | sure that it is working by getting the latest main branch of IPython:: | |
|
132 | In the past, IPython development has been done using `Subversion`__. Recently, | |
|
133 | we made the transition to using `Bazaar`__ and `Launchpad`__. This makes it | |
|
134 | much easier for people to contribute code to IPython. Here is a sketch of how | |
|
135 | to use Bazaar for IPython development. First, you should install Bazaar. | |
|
136 | After you have done that, make sure that it is working by getting the latest | |
|
137 | main branch of IPython:: | |
|
127 | 138 | |
|
128 | 139 | $ bzr branch lp:ipython |
|
129 | 140 | |
|
130 | 141 | Now you can create a new branch for you to do your work in:: |
|
131 | 142 | |
|
132 | 143 | $ bzr branch ipython ipython-mybranch |
|
133 | 144 | |
|
134 |
The typical work cycle in this branch will be to make changes in |
|
|
135 | and then commit those changes using the commit command:: | |
|
145 | The typical work cycle in this branch will be to make changes in | |
|
146 | ``ipython-mybranch`` and then commit those changes using the commit command:: | |
|
136 | 147 | |
|
137 | 148 | $ ...do work in ipython-mybranch... |
|
138 | 149 | $ bzr ci -m "the commit message goes here" |
|
139 | 150 | |
|
140 | Please note that since we now don't use an old-style linear ChangeLog | |
|
141 |
|
|
|
142 |
|
|
|
143 | detailed. Use a docstring-like approach in the commit messages | |
|
144 | (including the second line being left *blank*):: | |
|
151 | Please note that since we now don't use an old-style linear ChangeLog (that | |
|
152 | tends to cause problems with distributed version control systems), you should | |
|
153 | ensure that your log messages are reasonably detailed. Use a docstring-like | |
|
154 | approach in the commit messages (including the second line being left | |
|
155 | *blank*):: | |
|
145 | 156 | |
|
146 | 157 | Single line summary of changes being committed. |
|
147 | 158 | |
|
148 | 159 | - more details when warranted ... |
|
149 | 160 | - including crediting outside contributors if they sent the |
|
150 | 161 | code/bug/idea! |
|
151 | 162 | |
|
152 | If we couple this with a policy of making single commits for each | |
|
153 |
|
|
|
154 |
|
|
|
163 | If we couple this with a policy of making single commits for each reasonably | |
|
164 | atomic change, the bzr log should give an excellent view of the project, and | |
|
165 | the `--short` log option becomes a nice summary. | |
|
155 | 166 | |
|
156 |
While working with this branch, it is a good idea to merge in changes that have |
|
|
157 | made upstream in the parent branch. This can be done by doing:: | |
|
167 | While working with this branch, it is a good idea to merge in changes that have | |
|
168 | been made upstream in the parent branch. This can be done by doing:: | |
|
158 | 169 | |
|
159 | 170 | $ bzr pull |
|
160 | 171 | |
|
161 |
If this command shows that the branches have diverged, then you should do a |
|
|
162 | instead:: | |
|
172 | If this command shows that the branches have diverged, then you should do a | |
|
173 | merge instead:: | |
|
163 | 174 | |
|
164 | 175 | $ bzr merge lp:ipython |
|
165 | 176 | |
|
166 |
If you want others to be able to see your branch, you can create an account |
|
|
167 | launchpad and push the branch to your own workspace:: | |
|
177 | If you want others to be able to see your branch, you can create an account | |
|
178 | with launchpad and push the branch to your own workspace:: | |
|
168 | 179 | |
|
169 | 180 | $ bzr push bzr+ssh://<me>@bazaar.launchpad.net/~<me>/+junk/ipython-mybranch |
|
170 | 181 | |
|
171 |
Finally, once the work in your branch is done, you can merge your changes back |
|
|
172 | the `ipython` branch by using merge:: | |
|
182 | Finally, once the work in your branch is done, you can merge your changes back | |
|
183 | into the `ipython` branch by using merge:: | |
|
173 | 184 | |
|
174 | 185 | $ cd ipython |
|
175 | 186 | $ merge ../ipython-mybranch |
|
176 | 187 | [resolve any conflicts] |
|
177 | 188 | $ bzr ci -m "Fixing that bug" |
|
178 | 189 | $ bzr push |
|
179 | 190 | |
|
180 |
But this will require you to have write permissions to the `ipython` branch. |
|
|
181 |
you can tell one of the IPython devs about your branch and they |
|
|
191 | But this will require you to have write permissions to the `ipython` branch. | |
|
192 | It you don't you can tell one of the IPython devs about your branch and they | |
|
193 | can do the merge for you. | |
|
182 | 194 | |
|
183 | 195 | More information about Bazaar workflows can be found `here`__. |
|
184 | 196 | |
|
185 | 197 | .. __: http://subversion.tigris.org/ |
|
186 | 198 | .. __: http://bazaar-vcs.org/ |
|
187 | 199 | .. __: http://www.launchpad.net/ipython |
|
188 | 200 | .. __: http://doc.bazaar-vcs.org/bzr.dev/en/user-guide/index.html |
|
189 | 201 | |
|
190 | 202 | Documentation |
|
191 | 203 | ============= |
|
192 | 204 | |
|
193 | 205 | Standalone documentation |
|
194 | 206 | ------------------------ |
|
195 | 207 | |
|
196 |
All standalone documentation should be written in plain text (``.txt``) files |
|
|
197 |
`reStructuredText`_ for markup and formatting. All such documentation |
|
|
198 |
in the top level directory ``docs`` of the IPython source |
|
|
199 |
a suitably named subdirectory should be used. The |
|
|
200 | serve as the main source for IPython documentation and all existing documentation | |
|
201 | should be converted to this format. | |
|
208 | All standalone documentation should be written in plain text (``.txt``) files | |
|
209 | using `reStructuredText`_ for markup and formatting. All such documentation | |
|
210 | should be placed in the top level directory ``docs`` of the IPython source | |
|
211 | tree. Or, when appropriate, a suitably named subdirectory should be used. The | |
|
212 | documentation in this location will serve as the main source for IPython | |
|
213 | documentation and all existing documentation should be converted to this | |
|
214 | format. | |
|
202 | 215 | |
|
203 |
In the future, the text files in the ``docs`` directory will be used to |
|
|
204 |
forms of documentation for IPython. This include documentation on |
|
|
205 | as well as *pdf* documentation. | |
|
216 | In the future, the text files in the ``docs`` directory will be used to | |
|
217 | generate all forms of documentation for IPython. This include documentation on | |
|
218 | the IPython website as well as *pdf* documentation. | |
|
206 | 219 | |
|
207 | 220 | .. _reStructuredText: http://docutils.sourceforge.net/rst.html |
|
208 | 221 | |
|
209 | 222 | Docstring format |
|
210 | 223 | ---------------- |
|
211 | 224 | |
|
212 |
Good docstrings are very important. All new code will use `Epydoc`_ for |
|
|
213 |
docs, so we will follow the `Epydoc`_ conventions. More |
|
|
214 |
`reStructuredText`_ for markup and formatting, since |
|
|
215 |
variety of tools. This means that if in the future |
|
|
216 |
`Epydoc`_ to something else, we'll have fewer |
|
|
225 | Good docstrings are very important. All new code will use `Epydoc`_ for | |
|
226 | generating API docs, so we will follow the `Epydoc`_ conventions. More | |
|
227 | specifically, we will use `reStructuredText`_ for markup and formatting, since | |
|
228 | it is understood by a wide variety of tools. This means that if in the future | |
|
229 | we have any reason to change from `Epydoc`_ to something else, we'll have fewer | |
|
230 | transition pains. | |
|
217 | 231 | |
|
218 | 232 | Details about using `reStructuredText`_ for docstrings can be found `here |
|
219 | 233 | <http://epydoc.sourceforge.net/manual-othermarkup.html>`_. |
|
220 | 234 | |
|
221 | 235 | .. _Epydoc: http://epydoc.sourceforge.net/ |
|
222 | 236 | |
|
223 | 237 | Additional PEPs of interest regarding documentation of code: |
|
224 | 238 | |
|
225 | 239 | - `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_ |
|
226 | 240 | - `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ |
|
227 | 241 | - `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ |
|
228 | 242 | |
|
229 | 243 | |
|
230 | 244 | Coding conventions |
|
231 | 245 | ================== |
|
232 | 246 | |
|
233 | 247 | General |
|
234 | 248 | ------- |
|
235 | 249 | |
|
236 |
In general, we'll try to follow the standard Python style conventions as |
|
|
250 | In general, we'll try to follow the standard Python style conventions as | |
|
251 | described here: | |
|
237 | 252 | |
|
238 | 253 | - `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_ |
|
239 | 254 | |
|
240 | 255 | |
|
241 | 256 | Other comments: |
|
242 | 257 | |
|
243 | 258 | - In a large file, top level classes and functions should be |
|
244 | 259 | separated by 2-3 lines to make it easier to separate them visually. |
|
245 | 260 | - Use 4 spaces for indentation. |
|
246 | 261 | - Keep the ordering of methods the same in classes that have the same |
|
247 | 262 | methods. This is particularly true for classes that implement |
|
248 | 263 | similar interfaces and for interfaces that are similar. |
|
249 | 264 | |
|
250 | 265 | Naming conventions |
|
251 | 266 | ------------------ |
|
252 | 267 | |
|
253 |
In terms of naming conventions, we'll follow the guidelines from the `Style |
|
|
254 | Python Code`_. | |
|
268 | In terms of naming conventions, we'll follow the guidelines from the `Style | |
|
269 | Guide for Python Code`_. | |
|
255 | 270 | |
|
256 | 271 | For all new IPython code (and much existing code is being refactored), we'll use: |
|
257 | 272 | |
|
258 | 273 | - All ``lowercase`` module names. |
|
259 | 274 | |
|
260 | 275 | - ``CamelCase`` for class names. |
|
261 | 276 | |
|
262 |
- ``lowercase_with_underscores`` for methods, functions, variables and |
|
|
277 | - ``lowercase_with_underscores`` for methods, functions, variables and | |
|
278 | attributes. | |
|
263 | 279 | |
|
264 | This may be confusing as most of the existing IPython codebase uses a different convention (``lowerCamelCase`` for methods and attributes). Slowly, we will move IPython over to the new | |
|
265 | convention, providing shadow names for backward compatibility in public interfaces. | |
|
280 | This may be confusing as most of the existing IPython codebase uses a different | |
|
281 | convention (``lowerCamelCase`` for methods and attributes). Slowly, we will | |
|
282 | move IPython over to the new convention, providing shadow names for backward | |
|
283 | compatibility in public interfaces. | |
|
266 | 284 | |
|
267 |
There are, however, some important exceptions to these rules. In some cases, |
|
|
268 | code will interface with packages (Twisted, Wx, Qt) that use other conventions. At some level this makes it impossible to adhere to our own standards at all times. In particular, when subclassing classes that use other naming conventions, you must follow their naming conventions. To deal with cases like this, we propose the following policy: | |
|
285 | There are, however, some important exceptions to these rules. In some cases, | |
|
286 | IPython code will interface with packages (Twisted, Wx, Qt) that use other | |
|
287 | conventions. At some level this makes it impossible to adhere to our own | |
|
288 | standards at all times. In particular, when subclassing classes that use other | |
|
289 | naming conventions, you must follow their naming conventions. To deal with | |
|
290 | cases like this, we propose the following policy: | |
|
269 | 291 | |
|
270 | 292 | - If you are subclassing a class that uses different conventions, use its |
|
271 |
naming conventions throughout your subclass. Thus, if you are creating a |
|
|
272 |
Twisted Protocol class, used Twisted's |
|
|
273 | ||
|
274 | - All IPython's official interfaces should use our conventions. In some cases | |
|
275 | this will mean that you need to provide shadow names (first implement ``fooBar`` | |
|
276 | and then ``foo_bar = fooBar``). We want to avoid this at all costs, but it | |
|
277 | will probably be necessary at times. But, please use this sparingly! | |
|
278 | ||
|
279 | Implementation-specific *private* methods will use ``_single_underscore_prefix``. | |
|
280 | Names with a leading double underscore will *only* be used in special cases, as they | |
|
281 | makes subclassing difficult (such names are not easily seen by child classes). | |
|
282 | ||
|
283 | Occasionally some run-in lowercase names are used, but mostly for very short names or | |
|
284 | where we are implementing methods very similar to existing ones in a base class (like | |
|
285 | ``runlines()`` where ``runsource()`` and ``runcode()`` had established precedent). | |
|
293 | naming conventions throughout your subclass. Thus, if you are creating a | |
|
294 | Twisted Protocol class, used Twisted's | |
|
295 | ``namingSchemeForMethodsAndAttributes.`` | |
|
296 | ||
|
297 | - All IPython's official interfaces should use our conventions. In some cases | |
|
298 | this will mean that you need to provide shadow names (first implement | |
|
299 | ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all | |
|
300 | costs, but it will probably be necessary at times. But, please use this | |
|
301 | sparingly! | |
|
302 | ||
|
303 | Implementation-specific *private* methods will use | |
|
304 | ``_single_underscore_prefix``. Names with a leading double underscore will | |
|
305 | *only* be used in special cases, as they makes subclassing difficult (such | |
|
306 | names are not easily seen by child classes). | |
|
307 | ||
|
308 | Occasionally some run-in lowercase names are used, but mostly for very short | |
|
309 | names or where we are implementing methods very similar to existing ones in a | |
|
310 | base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had | |
|
311 | established precedent). | |
|
286 | 312 | |
|
287 | 313 | The old IPython codebase has a big mix of classes and modules prefixed with an |
|
288 |
explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned |
|
|
289 |
namespaces offer cleaner prefixing. The only case where this approach |
|
|
290 |
for classes which are expected to be imported into external |
|
|
291 |
generic name (like Shell) is too likely to clash with |
|
|
292 | revisit this issue as we clean up and refactor the code, but in general we should | |
|
293 | remove as many unnecessary ``IP``/``ip`` prefixes as possible. However, if a prefix | |
|
294 | seems absolutely necessary the more specific ``IPY`` or ``ipy`` are preferred. | |
|
314 | explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned | |
|
315 | upon, as namespaces offer cleaner prefixing. The only case where this approach | |
|
316 | is justified is for classes which are expected to be imported into external | |
|
317 | namespaces and a very generic name (like Shell) is too likely to clash with | |
|
318 | something else. We'll need to revisit this issue as we clean up and refactor | |
|
319 | the code, but in general we should remove as many unnecessary ``IP``/``ip`` | |
|
320 | prefixes as possible. However, if a prefix seems absolutely necessary the more | |
|
321 | specific ``IPY`` or ``ipy`` are preferred. | |
|
295 | 322 | |
|
296 | 323 | .. _devel_testing: |
|
297 | 324 | |
|
298 | 325 | Testing system |
|
299 | 326 | ============== |
|
300 | 327 | |
|
301 |
It is extremely important that all code contributed to IPython has tests. Tests |
|
|
302 |
be written as unittests, doctests or as entities that the `Nose`_ |
|
|
303 |
find. Regardless of how the tests are written, we will use |
|
|
304 |
running the tests. `Nose`_ will be required to run |
|
|
305 | not be required to simply use IPython. | |
|
328 | It is extremely important that all code contributed to IPython has tests. Tests | |
|
329 | should be written as unittests, doctests or as entities that the `Nose`_ | |
|
330 | testing package will find. Regardless of how the tests are written, we will use | |
|
331 | `Nose`_ for discovering and running the tests. `Nose`_ will be required to run | |
|
332 | the IPython test suite, but will not be required to simply use IPython. | |
|
306 | 333 | |
|
307 | 334 | .. _Nose: http://code.google.com/p/python-nose/ |
|
308 | 335 | |
|
309 |
Tests of `Twisted`__ using code should be written by subclassing the |
|
|
310 |
that comes with ``twisted.trial.unittest``. When this is |
|
|
311 |
run the tests and the twisted reactor will be |
|
|
336 | Tests of `Twisted`__ using code should be written by subclassing the | |
|
337 | ``TestCase`` class that comes with ``twisted.trial.unittest``. When this is | |
|
338 | done, `Nose`_ will be able to run the tests and the twisted reactor will be | |
|
339 | handled correctly. | |
|
312 | 340 | |
|
313 | 341 | .. __: http://www.twistedmatrix.com |
|
314 | 342 | |
|
315 |
Each subpackage in IPython should have its own ``tests`` directory that |
|
|
316 |
of the tests for that subpackage. This allows each subpackage to |
|
|
317 |
a subpackage has any dependencies beyond the Python |
|
|
318 | that subpackage should be skipped if the dependencies are not found. This is very | |
|
319 | important so users don't get tests failing simply because they don't have dependencies. | |
|
343 | Each subpackage in IPython should have its own ``tests`` directory that | |
|
344 | contains all of the tests for that subpackage. This allows each subpackage to | |
|
345 | be self-contained. If a subpackage has any dependencies beyond the Python | |
|
346 | standard library, the tests for that subpackage should be skipped if the | |
|
347 | dependencies are not found. This is very important so users don't get tests | |
|
348 | failing simply because they don't have dependencies. | |
|
320 | 349 | |
|
321 |
We also need to look into use Noses ability to tag tests to allow a more |
|
|
322 | approach of running tests. | |
|
350 | We also need to look into use Noses ability to tag tests to allow a more | |
|
351 | modular approach of running tests. | |
|
323 | 352 | |
|
324 | 353 | .. _devel_config: |
|
325 | 354 | |
|
326 | 355 | Configuration system |
|
327 | 356 | ==================== |
|
328 | 357 | |
|
329 | 358 | IPython uses `.ini`_ files for configuration purposes. This represents a huge |
|
330 |
improvement over the configuration system used in IPython. IPython works with |
|
|
331 | files using the `ConfigObj`_ package, which IPython includes as | |
|
359 | improvement over the configuration system used in IPython. IPython works with | |
|
360 | these files using the `ConfigObj`_ package, which IPython includes as | |
|
332 | 361 | ``ipython1/external/configobj.py``. |
|
333 | 362 | |
|
334 |
Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of |
|
|
335 |
should contain a ``config`` subdirectory that contains all of the |
|
|
336 |
information for the subpackage. To see how configuration |
|
|
337 | with defaults) see at the examples in ``ipython1/kernel/config`` and | |
|
338 | ``ipython1/core/config``. Likewise, to see how the configuration information is used, | |
|
339 | see examples in ``ipython1/kernel/scripts/ipengine.py``. | |
|
340 | ||
|
341 | Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We are | |
|
342 | calling this new layer, ``tconfig``, as it will use a `Traits`_-like validation model. | |
|
343 | We won't actually use `Traits`_, but will implement something similar in pure Python. | |
|
344 | But, even in this new system, we will still use `ConfigObj`_ and `.ini`_ files | |
|
345 | underneath the hood. Talk to Fernando if you are interested in working on this part of | |
|
346 | IPython. The current prototype of ``tconfig`` is located in the IPython sandbox. | |
|
363 | Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of | |
|
364 | IPython should contain a ``config`` subdirectory that contains all of the | |
|
365 | configuration information for the subpackage. To see how configuration | |
|
366 | information is defined (along with defaults) see at the examples in | |
|
367 | ``ipython1/kernel/config`` and ``ipython1/core/config``. Likewise, to see how | |
|
368 | the configuration information is used, see examples in | |
|
369 | ``ipython1/kernel/scripts/ipengine.py``. | |
|
370 | ||
|
371 | Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We | |
|
372 | are calling this new layer, ``tconfig``, as it will use a `Traits`_-like | |
|
373 | validation model. We won't actually use `Traits`_, but will implement | |
|
374 | something similar in pure Python. But, even in this new system, we will still | |
|
375 | use `ConfigObj`_ and `.ini`_ files underneath the hood. Talk to Fernando if you | |
|
376 | are interested in working on this part of IPython. The current prototype of | |
|
377 | ``tconfig`` is located in the IPython sandbox. | |
|
347 | 378 | |
|
348 | 379 | .. _.ini: http://docs.python.org/lib/module-ConfigParser.html |
|
349 | 380 | .. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html |
|
350 | 381 | .. _Traits: http://code.enthought.com/traits/ |
|
351 | 382 | |
|
352 | 383 | Installation and testing scenarios |
|
353 | 384 | ================================== |
|
354 | 385 | |
|
355 | This section outlines the various scenarios that we need to test before we release an IPython version. These scenarios represent different ways of installing IPython and its dependencies. | |
|
386 | This section outlines the various scenarios that we need to test before we | |
|
387 | release an IPython version. These scenarios represent different ways of | |
|
388 | installing IPython and its dependencies. | |
|
356 | 389 | |
|
357 | 390 | Installation scenarios under Linux and OS X |
|
358 | 391 | ------------------------------------------- |
|
359 | 392 | |
|
360 | 1. Install from tarball using `python setup.py install`. | |
|
393 | 1. Install from tarball using ``python setup.py install``. | |
|
361 | 394 | a. With only readline+nose dependencies installed. |
|
362 | b. With all dependencies installed (readline, zope.interface, | |
|
363 |
|
|
|
395 | b. With all dependencies installed (readline, zope.interface, Twisted, | |
|
396 | foolscap, Sphinx, nose, pyOpenSSL). | |
|
397 | ||
|
364 | 398 | 2. Install using easy_install. |
|
399 | ||
|
365 | 400 | a. With only readline+nose dependencies installed. |
|
366 | i. Default dependencies: `easy_install ipython-0.9.beta3-py2.5.egg` | |
|
367 | ii. Optional dependency sets: `easy_install -f ipython-0.9.beta3-py2.5.egg IPython[kernel,doc,test,security]` | |
|
401 | i. Default dependencies: ``easy_install ipython-0.9.beta3-py2.5.egg`` | |
|
402 | ii. Optional dependency sets: ``easy_install -f ipython-0.9.beta3-py2.5.egg IPython[kernel,doc,test,security]`` | |
|
403 | ||
|
368 | 404 | b. With all dependencies already installed. |
|
405 | ||
|
369 | 406 | |
|
370 | 407 | Installation scenarios under Win32 |
|
371 | 408 | ---------------------------------- |
|
372 | 409 | |
|
373 | 410 | 1. Install everything from .exe installers |
|
374 | 411 | 2. easy_install? |
|
375 | 412 | |
|
376 | 413 | |
|
377 | 414 | Tests to run for these scenarios |
|
378 | 415 | -------------------------------- |
|
379 | 416 | |
|
380 | 417 | 1. Run the full test suite. |
|
381 | 418 | 2. Start a controller and engines and try a few things by hand. |
|
382 | 419 | a. Using ipcluster. |
|
383 | 420 | b. Using ipcontroller/ipengine by hand. |
|
421 | ||
|
384 | 422 | 3. Run a few of the parallel examples. |
|
385 | 423 | 4. Try the kernel with and without security with and without PyOpenSSL |
|
386 | 424 | installed. |
|
387 | 425 | 5. Beat on the IPython terminal a bunch. |
|
388 | 426 | 6. Make sure that furl files are being put in proper locations. |
|
389 | ||
|
390 | ||
|
391 | ||
|
392 | ||
|
393 | ||
|
394 | ||
|
395 | ||
|
396 | ||
|
397 |
@@ -1,9 +1,10 b'' | |||
|
1 | 1 | ================== |
|
2 | 2 | Development |
|
3 | 3 | ================== |
|
4 | 4 | |
|
5 | 5 | .. toctree:: |
|
6 | 6 | :maxdepth: 2 |
|
7 | 7 | |
|
8 | 8 | development.txt |
|
9 | 9 | roadmap.txt |
|
10 | notification_blueprint.txt |
@@ -1,47 +1,49 b'' | |||
|
1 |
.. |
|
|
1 | .. _notification: | |
|
2 | 2 | |
|
3 | 3 | ========================================== |
|
4 | 4 | IPython.kernel.core.notification blueprint |
|
5 | 5 | ========================================== |
|
6 | 6 | |
|
7 | 7 | Overview |
|
8 | 8 | ======== |
|
9 | 9 | The :mod:`IPython.kernel.core.notification` module will provide a simple implementation of a notification center and support for the observer pattern within the :mod:`IPython.kernel.core`. The main intended use case is to provide notification of Interpreter events to an observing frontend during the execution of a single block of code. |
|
10 | 10 | |
|
11 | 11 | Functional Requirements |
|
12 | 12 | ======================= |
|
13 | 13 | The notification center must: |
|
14 |
|
|
|
15 |
|
|
|
16 |
|
|
|
17 |
|
|
|
18 |
|
|
|
19 |
|
|
|
20 |
|
|
|
21 | ||
|
14 | * Provide synchronous notification of events to all registered observers. | |
|
15 | * Provide typed or labeled notification types | |
|
16 | * Allow observers to register callbacks for individual or all notification types | |
|
17 | * Allow observers to register callbacks for events from individual or all notifying objects | |
|
18 | * Notification to the observer consists of the notification type, notifying object and user-supplied extra information [implementation: as keyword parameters to the registered callback] | |
|
19 | * Perform as O(1) in the case of no registered observers. | |
|
20 | * Permit out-of-process or cross-network extension. | |
|
21 | ||
|
22 | 22 | What's not included |
|
23 | 23 | ============================================================== |
|
24 | 24 | As written, the :mod:`IPython.kernel.core.notificaiton` module does not: |
|
25 |
|
|
|
26 |
|
|
|
27 | ||
|
25 | * Provide out-of-process or network notifications [these should be handled by a separate, Twisted aware module in :mod:`IPython.kernel`]. | |
|
26 | * Provide zope.interface-style interfaces for the notification system [these should also be provided by the :mod:`IPython.kernel` module] | |
|
27 | ||
|
28 | 28 | Use Cases |
|
29 | 29 | ========= |
|
30 | 30 | The following use cases describe the main intended uses of the notificaiton module and illustrate the main success scenario for each use case: |
|
31 | 31 | |
|
32 |
|
|
|
33 | from IPython.kernel.core.notification import NotificationCenter | |
|
34 | center = NotificationCenter.sharedNotificationCenter | |
|
35 | center.registerObserver(self, type=IPython.kernel.core.Interpreter.STDOUT_NOTIFICATION_TYPE, notifying_object=self.interpreter, callback=self.stdout_notification) | |
|
36 | ||
|
37 | and elsewhere in his front end:: | |
|
38 | def stdout_notification(self, type, notifying_object, out_string=None): | |
|
39 | self.writeStdOut(out_string) | |
|
40 | ||
|
41 | If everything works, the Interpreter will (according to its published API) fire a notification via the :data:`IPython.kernel.core.notification.sharedCenter` of type :const:`STD_OUT_NOTIFICATION_TYPE` before writing anything to stdout [it's up to the Intereter implementation to figure out when to do this]. The notificaiton center will then call the registered callbacks for that event type (in this case, Dwight's frontend's stdout_notification method). Again, according to its API, the Interpreter provides an additional keyword argument when firing the notificaiton of out_string, a copy of the string it will write to stdout. | |
|
42 | ||
|
43 | Like magic, Dwight's frontend is able to provide output, even during long-running calculations. Now if Jim could just convince Dwight to use Twisted... | |
|
44 | ||
|
45 | 2. Boss Hog is writing a frontend for the IPython project. Because Boss Hog is stuck in the stone age, his frontend will be written in a new Fortran-like dialect of python and will run only from the command line. Because he doesn't need any fancy notification system and is used to worrying about every cycle on his rat-wheel powered mini, Boss Hog is adamant that the new notification system not produce any performance penalty. As they say in Hazard county, there's no such thing as a free lunch. If he wanted zero overhead, he should have kept using IPython 0.8. Instead, those tricky Duke boys slide in a suped-up bridge-out jumpin' awkwardly confederate-lovin' notification module that imparts only a constant (and small) performance penalty when the Interpreter (or any other object) fires an event for which there are no registered observers. Of course, the same notificaiton-enabled Interpreter can then be used in frontends that require notifications, thus saving the IPython project from a nasty civil war. | |
|
46 | ||
|
47 | 3. Barry is wrting a frontend for the IPython project. Because Barry's front end is the *new hotness*, it uses an asynchronous event model to communicate with a Twisted :mod:`~IPython.kernel.engineservice` that communicates with the IPython :class:`~IPython.kernel.core.interpreter.Interpreter`. Using the :mod:`IPython.kernel.notification` module, an asynchronous wrapper on the :mod:`IPython.kernel.core.notification` module, Barry's frontend can register for notifications from the interpreter that are delivered asynchronously. Even if Barry's frontend is running on a separate process or even host from the Interpreter, the notifications are delivered, as if by dark and twisted magic. Just like Dwight's frontend, Barry's frontend can now recieve notifications of e.g. writing to stdout/stderr, opening/closing an external file, an exception in the executing code, etc. No newline at end of file | |
|
32 | 1. Dwight Schroot is writing a frontend for the IPython project. His frontend is stuck in the stone age and must communicate synchronously with an IPython.kernel.core.Interpreter instance. Because code is executed in blocks by the Interpreter, Dwight's UI freezes every time he executes a long block of code. To keep track of the progress of his long running block, Dwight adds the following code to his frontend's set-up code:: | |
|
33 | ||
|
34 | from IPython.kernel.core.notification import NotificationCenter | |
|
35 | center = NotificationCenter.sharedNotificationCenter | |
|
36 | center.registerObserver(self, type=IPython.kernel.core.Interpreter.STDOUT_NOTIFICATION_TYPE, notifying_object=self.interpreter, callback=self.stdout_notification) | |
|
37 | ||
|
38 | and elsewhere in his front end:: | |
|
39 | ||
|
40 | def stdout_notification(self, type, notifying_object, out_string=None): | |
|
41 | self.writeStdOut(out_string) | |
|
42 | ||
|
43 | If everything works, the Interpreter will (according to its published API) fire a notification via the :data:`IPython.kernel.core.notification.sharedCenter` of type :const:`STD_OUT_NOTIFICATION_TYPE` before writing anything to stdout [it's up to the Intereter implementation to figure out when to do this]. The notificaiton center will then call the registered callbacks for that event type (in this case, Dwight's frontend's stdout_notification method). Again, according to its API, the Interpreter provides an additional keyword argument when firing the notificaiton of out_string, a copy of the string it will write to stdout. | |
|
44 | ||
|
45 | Like magic, Dwight's frontend is able to provide output, even during long-running calculations. Now if Jim could just convince Dwight to use Twisted... | |
|
46 | ||
|
47 | 2. Boss Hog is writing a frontend for the IPython project. Because Boss Hog is stuck in the stone age, his frontend will be written in a new Fortran-like dialect of python and will run only from the command line. Because he doesn't need any fancy notification system and is used to worrying about every cycle on his rat-wheel powered mini, Boss Hog is adamant that the new notification system not produce any performance penalty. As they say in Hazard county, there's no such thing as a free lunch. If he wanted zero overhead, he should have kept using IPython 0.8. Instead, those tricky Duke boys slide in a suped-up bridge-out jumpin' awkwardly confederate-lovin' notification module that imparts only a constant (and small) performance penalty when the Interpreter (or any other object) fires an event for which there are no registered observers. Of course, the same notificaiton-enabled Interpreter can then be used in frontends that require notifications, thus saving the IPython project from a nasty civil war. | |
|
48 | ||
|
49 | 3. Barry is wrting a frontend for the IPython project. Because Barry's front end is the *new hotness*, it uses an asynchronous event model to communicate with a Twisted :mod:`~IPython.kernel.engineservice` that communicates with the IPython :class:`~IPython.kernel.core.interpreter.Interpreter`. Using the :mod:`IPython.kernel.notification` module, an asynchronous wrapper on the :mod:`IPython.kernel.core.notification` module, Barry's frontend can register for notifications from the interpreter that are delivered asynchronously. Even if Barry's frontend is running on a separate process or even host from the Interpreter, the notifications are delivered, as if by dark and twisted magic. Just like Dwight's frontend, Barry's frontend can now recieve notifications of e.g. writing to stdout/stderr, opening/closing an external file, an exception in the executing code, etc. No newline at end of file |
@@ -1,96 +1,107 b'' | |||
|
1 | 1 | .. _roadmap: |
|
2 | 2 | |
|
3 | 3 | =================== |
|
4 | 4 | Development roadmap |
|
5 | 5 | =================== |
|
6 | 6 | |
|
7 | 7 | .. contents:: |
|
8 | 8 | |
|
9 | 9 | IPython is an ambitious project that is still under heavy development. However, we want IPython to become useful to as many people as possible, as quickly as possible. To help us accomplish this, we are laying out a roadmap of where we are headed and what needs to happen to get there. Hopefully, this will help the IPython developers figure out the best things to work on for each upcoming release. |
|
10 | 10 | |
|
11 | 11 | Speaking of releases, we are going to begin releasing a new version of IPython every four weeks. We are hoping that a regular release schedule, along with a clear roadmap of where we are headed will propel the project forward. |
|
12 | 12 | |
|
13 | 13 | Where are we headed |
|
14 | 14 | =================== |
|
15 | 15 | |
|
16 | 16 | Our goal with IPython is simple: to provide a *powerful*, *robust* and *easy to use* framework for parallel computing. While there are other secondary goals you will hear us talking about at various times, this is the primary goal of IPython that frames the roadmap. |
|
17 | 17 | |
|
18 | 18 | Steps along the way |
|
19 | 19 | =================== |
|
20 | 20 | |
|
21 | 21 | Here we describe the various things that we need to work on to accomplish this goal. |
|
22 | 22 | |
|
23 | 23 | Setting up for regular release schedule |
|
24 | 24 | --------------------------------------- |
|
25 | 25 | |
|
26 | 26 | We would like to begin to release IPython regularly (probably a 4 week release cycle). To get ready for this, we need to revisit the development guidelines and put in information about releasing IPython. |
|
27 | 27 | |
|
28 | 28 | Process startup and management |
|
29 | 29 | ------------------------------ |
|
30 | 30 | |
|
31 | 31 | IPython is implemented using a distributed set of processes that communicate using TCP/IP network channels. Currently, users have to start each of the various processes separately using command line scripts. This is both difficult and error prone. Furthermore, there are a number of things that often need to be managed once the processes have been started, such as the sending of signals and the shutting down and cleaning up of processes. |
|
32 | 32 | |
|
33 | 33 | We need to build a system that makes it trivial for users to start and manage IPython processes. This system should have the following properties: |
|
34 | 34 | |
|
35 |
|
|
|
36 |
|
|
|
37 | * This simple API should be configured using standard .ini files. | |
|
38 | * The system should make it possible to start processes using a number of different | |
|
39 | approaches: SSH, PBS/Torque, Xgrid, Windows Server, mpirun, etc. | |
|
40 | * The controller and engine processes should each have a daemon for monitoring, | |
|
41 | signaling and clean up. | |
|
42 | * The system should be secure. | |
|
43 | * The system should work under all the major operating systems, including | |
|
44 | Windows. | |
|
35 | * It should possible to do everything through an extremely simple API that users | |
|
36 | can call from their own Python script. No shell commands should be needed. | |
|
37 | ||
|
38 | * This simple API should be configured using standard .ini files. | |
|
39 | ||
|
40 | * The system should make it possible to start processes using a number of different | |
|
41 | approaches: SSH, PBS/Torque, Xgrid, Windows Server, mpirun, etc. | |
|
42 | ||
|
43 | * The controller and engine processes should each have a daemon for monitoring, | |
|
44 | signaling and clean up. | |
|
45 | ||
|
46 | * The system should be secure. | |
|
47 | ||
|
48 | * The system should work under all the major operating systems, including | |
|
49 | Windows. | |
|
45 | 50 | |
|
46 | 51 | Initial work has begun on the daemon infrastructure, and some of the needed logic is contained in the ipcluster script. |
|
47 | 52 | |
|
48 | 53 | Ease of use/high-level approaches to parallelism |
|
49 | 54 | ------------------------------------------------ |
|
50 | 55 | |
|
51 | 56 | While our current API for clients is well designed, we can still do a lot better in designing a user-facing API that is super simple. The main goal here is that it should take *almost no extra code* for users to get their code running in parallel. For this to be possible, we need to tie into Python's standard idioms that enable efficient coding. The biggest ones we are looking at are using context managers (i.e., Python 2.5's ``with`` statement) and decorators. Initial work on this front has begun, but more work is needed. |
|
52 | 57 | |
|
53 | 58 | We also need to think about new models for expressing parallelism. This is fun work as most of the foundation has already been established. |
|
54 | 59 | |
|
55 | 60 | Security |
|
56 | 61 | -------- |
|
57 | 62 | |
|
58 | 63 | Currently, IPython has no built in security or security model. Because we would like IPython to be usable on public computer systems and over wide area networks, we need to come up with a robust solution for security. Here are some of the specific things that need to be included: |
|
59 | 64 | |
|
60 |
|
|
|
61 | * Optional TSL/SSL based encryption of all communication channels. | |
|
62 | * A good way of picking network ports so multiple users on the same system can | |
|
63 | run their own controller and engines without interfering with those of others. | |
|
64 | * A clear model for security that enables users to evaluate the security risks | |
|
65 | associated with using IPython in various manners. | |
|
65 | * User authentication between all processes (engines, controller and clients). | |
|
66 | ||
|
67 | * Optional TSL/SSL based encryption of all communication channels. | |
|
68 | ||
|
69 | * A good way of picking network ports so multiple users on the same system can | |
|
70 | run their own controller and engines without interfering with those of others. | |
|
71 | ||
|
72 | * A clear model for security that enables users to evaluate the security risks | |
|
73 | associated with using IPython in various manners. | |
|
66 | 74 | |
|
67 | 75 | For the implementation of this, we plan on using Twisted's support for SSL and authentication. One things that we really should look at is the `Foolscap`_ network protocol, which provides many of these things out of the box. |
|
68 | 76 | |
|
69 | 77 | .. _Foolscap: http://foolscap.lothar.com/trac |
|
70 | 78 | |
|
71 | 79 | The security work needs to be done in conjunction with other network protocol stuff. |
|
72 | 80 | |
|
81 | As of the 0.9 release of IPython, we are using Foolscap and we have implemented | |
|
82 | a full security model. | |
|
83 | ||
|
73 | 84 | Latent performance issues |
|
74 | 85 | ------------------------- |
|
75 | 86 | |
|
76 | 87 | Currently, we have a number of performance issues that are waiting to bite users: |
|
77 | 88 | |
|
78 | 89 | * The controller store a large amount of state in Python dictionaries. Under heavy |
|
79 | 90 | usage, these dicts with get very large, causing memory usage problems. We need to |
|
80 | 91 | develop more scalable solutions to this problem, such as using a sqlite database |
|
81 | 92 | to store this state. This will also help the controller to be more fault tolerant. |
|
82 | 93 | * Currently, the client to controller connections are done through XML-RPC using |
|
83 | 94 | HTTP 1.0. This is very inefficient as XML-RPC is a very verbose protocol and |
|
84 | 95 | each request must be handled with a new connection. We need to move these network |
|
85 | connections over to PB or Foolscap. | |
|
96 | connections over to PB or Foolscap. Done! | |
|
86 | 97 | * We currently don't have a good way of handling large objects in the controller. |
|
87 | 98 | The biggest problem is that because we don't have any way of streaming objects, |
|
88 | 99 | we get lots of temporary copies in the low-level buffers. We need to implement |
|
89 | 100 | a better serialization approach and true streaming support. |
|
90 | 101 | * The controller currently unpickles and repickles objects. We need to use the |
|
91 | 102 | [push|pull]_serialized methods instead. |
|
92 | 103 | * Currently the controller is a bottleneck. We need the ability to scale the |
|
93 | 104 | controller by aggregating multiple controllers into one effective controller. |
|
94 | 105 | |
|
95 | 106 | |
|
96 | 107 |
@@ -1,93 +1,105 b'' | |||
|
1 | 1 | .. _faq: |
|
2 | 2 | |
|
3 | 3 | ======================================== |
|
4 | 4 | Frequently asked questions |
|
5 | 5 | ======================================== |
|
6 | 6 | |
|
7 | 7 | General questions |
|
8 | 8 | ================= |
|
9 | 9 | |
|
10 | 10 | Questions about parallel computing with IPython |
|
11 | 11 | ================================================ |
|
12 | 12 | |
|
13 | 13 | Will IPython speed my Python code up? |
|
14 | 14 | -------------------------------------- |
|
15 | 15 | |
|
16 | 16 | Yes and no. When converting a serial code to run in parallel, there often many |
|
17 | 17 | difficulty questions that need to be answered, such as: |
|
18 | 18 | |
|
19 |
|
|
|
20 | * What are the data movement patterns? | |
|
21 | * Can the algorithm be structured to minimize data movement? | |
|
22 | * Is dynamic load balancing important? | |
|
19 | * How should data be decomposed onto the set of processors? | |
|
20 | ||
|
21 | * What are the data movement patterns? | |
|
22 | ||
|
23 | * Can the algorithm be structured to minimize data movement? | |
|
24 | ||
|
25 | * Is dynamic load balancing important? | |
|
23 | 26 | |
|
24 | 27 | We can't answer such questions for you. This is the hard (but fun) work of parallel |
|
25 | 28 | computing. But, once you understand these things IPython will make it easier for you to |
|
26 | 29 | implement a good solution quickly. Most importantly, you will be able to use the |
|
27 | 30 | resulting parallel code interactively. |
|
28 | 31 | |
|
29 | 32 | With that said, if your problem is trivial to parallelize, IPython has a number of |
|
30 | 33 | different interfaces that will enable you to parallelize things is almost no time at |
|
31 |
all. A good place to start is the ``map`` method of our |
|
|
32 | ||
|
33 | .. _multiengine interface: ./parallel_multiengine | |
|
34 | all. A good place to start is the ``map`` method of our :class:`MultiEngineClient`. | |
|
34 | 35 | |
|
35 | 36 | What is the best way to use MPI from Python? |
|
36 | 37 | -------------------------------------------- |
|
37 | 38 | |
|
38 | 39 | What about all the other parallel computing packages in Python? |
|
39 | 40 | --------------------------------------------------------------- |
|
40 | 41 | |
|
41 | 42 | Some of the unique characteristic of IPython are: |
|
42 | 43 | |
|
43 |
|
|
|
44 |
|
|
|
45 |
|
|
|
46 |
|
|
|
47 | * IPython is asynchronous from the ground up (we use `Twisted`_). | |
|
48 | * IPython's architecture is designed to avoid subtle problems | |
|
49 | that emerge because of Python's global interpreter lock (GIL). | |
|
50 |
|
|
|
51 | of novel parallel computing models, it is fully interoperable with | |
|
52 | traditional MPI applications. | |
|
53 | * IPython has been used and tested extensively on modern supercomputers. | |
|
54 | * IPython's networking layers are completely modular. Thus, is | |
|
55 | straightforward to replace our existing network protocols with | |
|
56 | high performance alternatives (ones based upon Myranet/Infiniband). | |
|
57 | * IPython is designed from the ground up to support collaborative | |
|
58 | parallel computing. This enables multiple users to actively develop | |
|
59 | and run the *same* parallel computation. | |
|
60 | * Interactivity is a central goal for us. While IPython does not have | |
|
61 | to be used interactivly, is can be. | |
|
62 |
|
|
|
44 | * IPython is the only architecture that abstracts out the notion of a | |
|
45 | parallel computation in such a way that new models of parallel computing | |
|
46 | can be explored quickly and easily. If you don't like the models we | |
|
47 | provide, you can simply create your own using the capabilities we provide. | |
|
48 | ||
|
49 | * IPython is asynchronous from the ground up (we use `Twisted`_). | |
|
50 | ||
|
51 | * IPython's architecture is designed to avoid subtle problems | |
|
52 | that emerge because of Python's global interpreter lock (GIL). | |
|
53 | ||
|
54 | * While IPython's architecture is designed to support a wide range | |
|
55 | of novel parallel computing models, it is fully interoperable with | |
|
56 | traditional MPI applications. | |
|
57 | ||
|
58 | * IPython has been used and tested extensively on modern supercomputers. | |
|
59 | ||
|
60 | * IPython's networking layers are completely modular. Thus, is | |
|
61 | straightforward to replace our existing network protocols with | |
|
62 | high performance alternatives (ones based upon Myranet/Infiniband). | |
|
63 | ||
|
64 | * IPython is designed from the ground up to support collaborative | |
|
65 | parallel computing. This enables multiple users to actively develop | |
|
66 | and run the *same* parallel computation. | |
|
67 | ||
|
68 | * Interactivity is a central goal for us. While IPython does not have | |
|
69 | to be used interactivly, it can be. | |
|
70 | ||
|
63 | 71 | .. _Twisted: http://www.twistedmatrix.com |
|
64 | 72 | |
|
65 | 73 | Why The IPython controller a bottleneck in my parallel calculation? |
|
66 | 74 | ------------------------------------------------------------------- |
|
67 | 75 | |
|
68 | 76 | A golden rule in parallel computing is that you should only move data around if you |
|
69 | 77 | absolutely need to. The main reason that the controller becomes a bottleneck is that |
|
70 | 78 | too much data is being pushed and pulled to and from the engines. If your algorithm |
|
71 | 79 | is structured in this way, you really should think about alternative ways of |
|
72 | 80 | handling the data movement. Here are some ideas: |
|
73 | 81 | |
|
74 |
|
|
|
75 | 2. Have the engines write data to files on a file system that is shared by | |
|
76 | the engines. | |
|
77 | 3. Have the engines write data to a database that is shared by the engines. | |
|
78 | 4. Simply keep data in the persistent memory of the engines and move the | |
|
79 | computation to the data (rather than the data to the computation). | |
|
80 | 5. See if you can pass data directly between engines using MPI. | |
|
82 | 1. Have the engines write data to files on the locals disks of the engines. | |
|
83 | ||
|
84 | 2. Have the engines write data to files on a file system that is shared by | |
|
85 | the engines. | |
|
86 | ||
|
87 | 3. Have the engines write data to a database that is shared by the engines. | |
|
88 | ||
|
89 | 4. Simply keep data in the persistent memory of the engines and move the | |
|
90 | computation to the data (rather than the data to the computation). | |
|
91 | ||
|
92 | 5. See if you can pass data directly between engines using MPI. | |
|
81 | 93 | |
|
82 | 94 | Isn't Python slow to be used for high-performance parallel computing? |
|
83 | 95 | --------------------------------------------------------------------- |
|
84 | 96 | |
|
85 | 97 | |
|
86 | 98 | |
|
87 | 99 | |
|
88 | 100 | |
|
89 | 101 | |
|
90 | 102 | |
|
91 | 103 | |
|
92 | 104 | |
|
93 | 105 |
@@ -1,56 +1,38 b'' | |||
|
1 | 1 | .. _history: |
|
2 | 2 | |
|
3 | 3 | ======= |
|
4 | 4 | History |
|
5 | 5 | ======= |
|
6 | 6 | |
|
7 | 7 | Origins |
|
8 | 8 | ======= |
|
9 | 9 | |
|
10 | The current IPython system grew out of the following three projects: | |
|
11 | ||
|
12 | * [ipython] by Fernando Pérez. I was working on adding | |
|
13 | Mathematica-type prompts and a flexible configuration system | |
|
14 | (something better than $PYTHONSTARTUP) to the standard Python | |
|
15 | interactive interpreter. | |
|
16 | * [IPP] by Janko Hauser. Very well organized, great usability. Had | |
|
17 | an old help system. IPP was used as the 'container' code into | |
|
18 | which I added the functionality from ipython and LazyPython. | |
|
19 | * [LazyPython] by Nathan Gray. Simple but very powerful. The quick | |
|
20 | syntax (auto parens, auto quotes) and verbose/colored tracebacks | |
|
21 | were all taken from here. | |
|
22 | ||
|
23 | When I found out about IPP and LazyPython I tried to join all three | |
|
24 | into a unified system. I thought this could provide a very nice | |
|
25 | working environment, both for regular programming and scientific | |
|
26 | computing: shell-like features, IDL/Matlab numerics, Mathematica-type | |
|
27 | prompt history and great object introspection and help facilities. I | |
|
28 | think it worked reasonably well, though it was a lot more work than I | |
|
29 | had initially planned. | |
|
30 | ||
|
31 | ||
|
32 | Current status | |
|
33 | ============== | |
|
34 | ||
|
35 | The above listed features work, and quite well for the most part. But | |
|
36 | until a major internal restructuring is done (see below), only bug | |
|
37 | fixing will be done, no other features will be added (unless very minor | |
|
38 | and well localized in the cleaner parts of the code). | |
|
39 | ||
|
40 | IPython consists of some 18000 lines of pure python code, of which | |
|
41 | roughly two thirds is reasonably clean. The rest is, messy code which | |
|
42 | needs a massive restructuring before any further major work is done. | |
|
43 | Even the messy code is fairly well documented though, and most of the | |
|
44 | problems in the (non-existent) class design are well pointed to by a | |
|
45 | PyChecker run. So the rewriting work isn't that bad, it will just be | |
|
46 | time-consuming. | |
|
47 | ||
|
48 | ||
|
49 | Future | |
|
50 | ------ | |
|
51 | ||
|
52 | See the separate new_design document for details. Ultimately, I would | |
|
53 | like to see IPython become part of the standard Python distribution as a | |
|
54 | 'big brother with batteries' to the standard Python interactive | |
|
55 | interpreter. But that will never happen with the current state of the | |
|
56 | code, so all contributions are welcome. No newline at end of file | |
|
10 | IPython was starting in 2001 by Fernando Perez. IPython as we know it | |
|
11 | today grew out of the following three projects: | |
|
12 | ||
|
13 | * ipython by Fernando Pérez. I was working on adding | |
|
14 | Mathematica-type prompts and a flexible configuration system | |
|
15 | (something better than $PYTHONSTARTUP) to the standard Python | |
|
16 | interactive interpreter. | |
|
17 | * IPP by Janko Hauser. Very well organized, great usability. Had | |
|
18 | an old help system. IPP was used as the 'container' code into | |
|
19 | which I added the functionality from ipython and LazyPython. | |
|
20 | * LazyPython by Nathan Gray. Simple but very powerful. The quick | |
|
21 | syntax (auto parens, auto quotes) and verbose/colored tracebacks | |
|
22 | were all taken from here. | |
|
23 | ||
|
24 | Here is how Fernando describes it: | |
|
25 | ||
|
26 | When I found out about IPP and LazyPython I tried to join all three | |
|
27 | into a unified system. I thought this could provide a very nice | |
|
28 | working environment, both for regular programming and scientific | |
|
29 | computing: shell-like features, IDL/Matlab numerics, Mathematica-type | |
|
30 | prompt history and great object introspection and help facilities. I | |
|
31 | think it worked reasonably well, though it was a lot more work than I | |
|
32 | had initially planned. | |
|
33 | ||
|
34 | Today and how we got here | |
|
35 | ========================= | |
|
36 | ||
|
37 | This needs to be filled in. | |
|
38 |
@@ -1,28 +1,32 b'' | |||
|
1 | 1 | ===================== |
|
2 | 2 | IPython Documentation |
|
3 | 3 | ===================== |
|
4 | 4 | |
|
5 | Contents | |
|
6 | ======== | |
|
5 | .. htmlonly:: | |
|
6 | ||
|
7 | :Release: |version| | |
|
8 | :Date: |today| | |
|
9 | ||
|
10 | Contents: | |
|
7 | 11 | |
|
8 | 12 | .. toctree:: |
|
9 |
:maxdepth: |
|
|
13 | :maxdepth: 2 | |
|
10 | 14 | |
|
11 | 15 | overview.txt |
|
12 | 16 | install/index.txt |
|
13 | 17 | interactive/index.txt |
|
14 | 18 | parallel/index.txt |
|
15 | 19 | config/index.txt |
|
16 | 20 | changes.txt |
|
17 | 21 | development/index.txt |
|
18 | 22 | faq.txt |
|
19 | 23 | history.txt |
|
20 | 24 | license_and_copyright.txt |
|
21 | 25 | credits.txt |
|
22 | 26 | |
|
23 | Indices and tables | |
|
24 | ================== | |
|
25 | 27 | |
|
26 | * :ref:`genindex` | |
|
27 | * :ref:`modindex` | |
|
28 | * :ref:`search` No newline at end of file | |
|
28 | .. htmlonly:: | |
|
29 | ||
|
30 | * :ref:`genindex` | |
|
31 | * :ref:`modindex` | |
|
32 | * :ref:`search` |
@@ -1,11 +1,10 b'' | |||
|
1 | 1 | .. _install_index: |
|
2 | 2 | |
|
3 | 3 | ================== |
|
4 | 4 | Installation |
|
5 | 5 | ================== |
|
6 | 6 | |
|
7 | 7 | .. toctree:: |
|
8 | 8 | :maxdepth: 2 |
|
9 | 9 | |
|
10 |
|
|
|
11 | advanced.txt | |
|
10 | install.txt |
@@ -1,3163 +1,3162 b'' | |||
|
1 | 1 | .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008. |
|
2 | 2 | You can adapt this file completely to your liking, but it should at least |
|
3 | 3 | contain the root 'toctree' directive. |
|
4 | 4 | |
|
5 | 5 | ================= |
|
6 | 6 | IPython reference |
|
7 | 7 | ================= |
|
8 | 8 | |
|
9 | 9 | .. contents:: |
|
10 | 10 | |
|
11 |
.. _ |
|
|
11 | .. _command_line_options: | |
|
12 | 12 | |
|
13 | 13 | Command-line usage |
|
14 | 14 | ================== |
|
15 | 15 | |
|
16 | 16 | You start IPython with the command:: |
|
17 | 17 | |
|
18 | 18 | $ ipython [options] files |
|
19 | 19 | |
|
20 | 20 | If invoked with no options, it executes all the files listed in sequence |
|
21 | 21 | and drops you into the interpreter while still acknowledging any options |
|
22 | 22 | you may have set in your ipythonrc file. This behavior is different from |
|
23 | 23 | standard Python, which when called as python -i will only execute one |
|
24 | 24 | file and ignore your configuration setup. |
|
25 | 25 | |
|
26 | 26 | Please note that some of the configuration options are not available at |
|
27 | 27 | the command line, simply because they are not practical here. Look into |
|
28 | 28 | your ipythonrc configuration file for details on those. This file |
|
29 | 29 | typically installed in the $HOME/.ipython directory. For Windows users, |
|
30 | 30 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most |
|
31 | 31 | instances. In the rest of this text, we will refer to this directory as |
|
32 | 32 | IPYTHONDIR. |
|
33 | 33 | |
|
34 | 34 | .. _Threading options: |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | Special Threading Options |
|
38 | 38 | ------------------------- |
|
39 | 39 | |
|
40 | 40 | The following special options are ONLY valid at the beginning of the |
|
41 | 41 | command line, and not later. This is because they control the initial- |
|
42 | 42 | ization of ipython itself, before the normal option-handling mechanism |
|
43 | 43 | is active. |
|
44 | 44 | |
|
45 | 45 | -gthread, -qthread, -q4thread, -wthread, -pylab: |
|
46 | 46 | Only one of these can be given, and it can only be given as |
|
47 | 47 | the first option passed to IPython (it will have no effect in |
|
48 | 48 | any other position). They provide threading support for the |
|
49 | 49 | GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the |
|
50 | 50 | matplotlib library. |
|
51 | 51 | |
|
52 | 52 | With any of the first four options, IPython starts running a |
|
53 | 53 | separate thread for the graphical toolkit's operation, so that |
|
54 | 54 | you can open and control graphical elements from within an |
|
55 | 55 | IPython command line, without blocking. All four provide |
|
56 | 56 | essentially the same functionality, respectively for GTK, Qt3, |
|
57 | 57 | Qt4 and WXWidgets (via their Python interfaces). |
|
58 | 58 | |
|
59 | 59 | Note that with -wthread, you can additionally use the |
|
60 | 60 | -wxversion option to request a specific version of wx to be |
|
61 | 61 | used. This requires that you have the wxversion Python module |
|
62 | 62 | installed, which is part of recent wxPython distributions. |
|
63 | 63 | |
|
64 | 64 | If -pylab is given, IPython loads special support for the mat |
|
65 | 65 | plotlib library (http://matplotlib.sourceforge.net), allowing |
|
66 | 66 | interactive usage of any of its backends as defined in the |
|
67 | 67 | user's ~/.matplotlib/matplotlibrc file. It automatically |
|
68 | 68 | activates GTK, Qt or WX threading for IPyhton if the choice of |
|
69 | 69 | matplotlib backend requires it. It also modifies the %run |
|
70 | 70 | command to correctly execute (without blocking) any |
|
71 | 71 | matplotlib-based script which calls show() at the end. |
|
72 | 72 | |
|
73 | 73 | -tk |
|
74 | 74 | The -g/q/q4/wthread options, and -pylab (if matplotlib is |
|
75 | 75 | configured to use GTK, Qt3, Qt4 or WX), will normally block Tk |
|
76 | 76 | graphical interfaces. This means that when either GTK, Qt or WX |
|
77 | 77 | threading is active, any attempt to open a Tk GUI will result in a |
|
78 | 78 | dead window, and possibly cause the Python interpreter to crash. |
|
79 | 79 | An extra option, -tk, is available to address this issue. It can |
|
80 | 80 | only be given as a second option after any of the above (-gthread, |
|
81 | 81 | -wthread or -pylab). |
|
82 | 82 | |
|
83 | 83 | If -tk is given, IPython will try to coordinate Tk threading |
|
84 | 84 | with GTK, Qt or WX. This is however potentially unreliable, and |
|
85 | 85 | you will have to test on your platform and Python configuration to |
|
86 | 86 | determine whether it works for you. Debian users have reported |
|
87 | 87 | success, apparently due to the fact that Debian builds all of Tcl, |
|
88 | 88 | Tk, Tkinter and Python with pthreads support. Under other Linux |
|
89 | 89 | environments (such as Fedora Core 2/3), this option has caused |
|
90 | 90 | random crashes and lockups of the Python interpreter. Under other |
|
91 | 91 | operating systems (Mac OSX and Windows), you'll need to try it to |
|
92 | 92 | find out, since currently no user reports are available. |
|
93 | 93 | |
|
94 | 94 | There is unfortunately no way for IPython to determine at run time |
|
95 | 95 | whether -tk will work reliably or not, so you will need to do some |
|
96 | 96 | experiments before relying on it for regular work. |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | |
|
100 | 100 | Regular Options |
|
101 | 101 | --------------- |
|
102 | 102 | |
|
103 | 103 | After the above threading options have been given, regular options can |
|
104 | 104 | follow in any order. All options can be abbreviated to their shortest |
|
105 | 105 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
106 | 106 | used. Some options have an alternate short form, indicated after a ``|``. |
|
107 | 107 | |
|
108 | 108 | Most options can also be set from your ipythonrc configuration file. See |
|
109 | 109 | the provided example for more details on what the options do. Options |
|
110 | 110 | given at the command line override the values set in the ipythonrc file. |
|
111 | 111 | |
|
112 | 112 | All options with a [no] prepended can be specified in negated form |
|
113 | 113 | (-nooption instead of -option) to turn the feature off. |
|
114 | 114 | |
|
115 | 115 | -help print a help message and exit. |
|
116 | 116 | |
|
117 | 117 | -pylab |
|
118 | 118 | this can only be given as the first option passed to IPython |
|
119 | 119 | (it will have no effect in any other position). It adds |
|
120 | 120 | special support for the matplotlib library |
|
121 | 121 | (http://matplotlib.sourceforge.ne), allowing interactive usage |
|
122 | 122 | of any of its backends as defined in the user's .matplotlibrc |
|
123 | 123 | file. It automatically activates GTK or WX threading for |
|
124 | 124 | IPyhton if the choice of matplotlib backend requires it. It |
|
125 | 125 | also modifies the %run command to correctly execute (without |
|
126 | 126 | blocking) any matplotlib-based script which calls show() at |
|
127 | 127 | the end. See `Matplotlib support`_ for more details. |
|
128 | 128 | |
|
129 | 129 | -autocall <val> |
|
130 | 130 | Make IPython automatically call any callable object even if you |
|
131 | 131 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
132 | 132 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
133 | 133 | '1' for smart autocall, where it is not applied if there are no more |
|
134 | 134 | arguments on the line, and '2' for full autocall, where all callable |
|
135 | 135 | objects are automatically called (even if no arguments are |
|
136 | 136 | present). The default is '1'. |
|
137 | 137 | |
|
138 | 138 | -[no]autoindent |
|
139 | 139 | Turn automatic indentation on/off. |
|
140 | 140 | |
|
141 | 141 | -[no]automagic |
|
142 | 142 | make magic commands automatic (without needing their first character |
|
143 | 143 | to be %). Type %magic at the IPython prompt for more information. |
|
144 | 144 | |
|
145 | 145 | -[no]autoedit_syntax |
|
146 | 146 | When a syntax error occurs after editing a file, automatically |
|
147 | 147 | open the file to the trouble causing line for convenient |
|
148 | 148 | fixing. |
|
149 | 149 | |
|
150 | 150 | -[no]banner Print the initial information banner (default on). |
|
151 | 151 | |
|
152 | 152 | -c <command> |
|
153 | 153 | execute the given command string. This is similar to the -c |
|
154 | 154 | option in the normal Python interpreter. |
|
155 | 155 | |
|
156 | 156 | -cache_size, cs <n> |
|
157 | 157 | size of the output cache (maximum number of entries to hold in |
|
158 | 158 | memory). The default is 1000, you can change it permanently in your |
|
159 | 159 | config file. Setting it to 0 completely disables the caching system, |
|
160 | 160 | and the minimum value accepted is 20 (if you provide a value less than |
|
161 | 161 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
162 | 162 | because otherwise you'll spend more time re-flushing a too small cache |
|
163 | 163 | than working. |
|
164 | 164 | |
|
165 | 165 | -classic, cl |
|
166 | 166 | Gives IPython a similar feel to the classic Python |
|
167 | 167 | prompt. |
|
168 | 168 | |
|
169 | 169 | -colors <scheme> |
|
170 | 170 | Color scheme for prompts and exception reporting. Currently |
|
171 | 171 | implemented: NoColor, Linux and LightBG. |
|
172 | 172 | |
|
173 | 173 | -[no]color_info |
|
174 | 174 | IPython can display information about objects via a set of functions, |
|
175 | 175 | and optionally can use colors for this, syntax highlighting source |
|
176 | 176 | code and various other elements. However, because this information is |
|
177 | 177 | passed through a pager (like 'less') and many pagers get confused with |
|
178 | 178 | color codes, this option is off by default. You can test it and turn |
|
179 | 179 | it on permanently in your ipythonrc file if it works for you. As a |
|
180 | 180 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
181 | 181 | that in RedHat 7.2 doesn't. |
|
182 | 182 | |
|
183 | 183 | Test it and turn it on permanently if it works with your |
|
184 | 184 | system. The magic function %color_info allows you to toggle this |
|
185 | 185 | interactively for testing. |
|
186 | 186 | |
|
187 | 187 | -[no]debug |
|
188 | 188 | Show information about the loading process. Very useful to pin down |
|
189 | 189 | problems with your configuration files or to get details about |
|
190 | 190 | session restores. |
|
191 | 191 | |
|
192 | 192 | -[no]deep_reload: |
|
193 | 193 | IPython can use the deep_reload module which reloads changes in |
|
194 | 194 | modules recursively (it replaces the reload() function, so you don't |
|
195 | 195 | need to change anything to use it). deep_reload() forces a full |
|
196 | 196 | reload of modules whose code may have changed, which the default |
|
197 | 197 | reload() function does not. |
|
198 | 198 | |
|
199 | 199 | When deep_reload is off, IPython will use the normal reload(), |
|
200 | 200 | but deep_reload will still be available as dreload(). This |
|
201 | 201 | feature is off by default [which means that you have both |
|
202 | 202 | normal reload() and dreload()]. |
|
203 | 203 | |
|
204 | 204 | -editor <name> |
|
205 | 205 | Which editor to use with the %edit command. By default, |
|
206 | 206 | IPython will honor your EDITOR environment variable (if not |
|
207 | 207 | set, vi is the Unix default and notepad the Windows one). |
|
208 | 208 | Since this editor is invoked on the fly by IPython and is |
|
209 | 209 | meant for editing small code snippets, you may want to use a |
|
210 | 210 | small, lightweight editor here (in case your default EDITOR is |
|
211 | 211 | something like Emacs). |
|
212 | 212 | |
|
213 | 213 | -ipythondir <name> |
|
214 | 214 | name of your IPython configuration directory IPYTHONDIR. This |
|
215 | 215 | can also be specified through the environment variable |
|
216 | 216 | IPYTHONDIR. |
|
217 | 217 | |
|
218 | 218 | -log, l |
|
219 | 219 | generate a log file of all input. The file is named |
|
220 | 220 | ipython_log.py in your current directory (which prevents logs |
|
221 | 221 | from multiple IPython sessions from trampling each other). You |
|
222 | 222 | can use this to later restore a session by loading your |
|
223 | 223 | logfile as a file to be executed with option -logplay (see |
|
224 | 224 | below). |
|
225 | 225 | |
|
226 | 226 | -logfile, lf <name> specify the name of your logfile. |
|
227 | 227 | |
|
228 | 228 | -logplay, lp <name> |
|
229 | 229 | |
|
230 | 230 | you can replay a previous log. For restoring a session as close as |
|
231 | 231 | possible to the state you left it in, use this option (don't just run |
|
232 | 232 | the logfile). With -logplay, IPython will try to reconstruct the |
|
233 | 233 | previous working environment in full, not just execute the commands in |
|
234 | 234 | the logfile. |
|
235 | 235 | |
|
236 | 236 | When a session is restored, logging is automatically turned on |
|
237 | 237 | again with the name of the logfile it was invoked with (it is |
|
238 | 238 | read from the log header). So once you've turned logging on for |
|
239 | 239 | a session, you can quit IPython and reload it as many times as |
|
240 | 240 | you want and it will continue to log its history and restore |
|
241 | 241 | from the beginning every time. |
|
242 | 242 | |
|
243 | 243 | Caveats: there are limitations in this option. The history |
|
244 | 244 | variables _i*,_* and _dh don't get restored properly. In the |
|
245 | 245 | future we will try to implement full session saving by writing |
|
246 | 246 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
247 | 247 | our first attempts failed because of inherent limitations of |
|
248 | 248 | Python's Pickle module, so this may have to wait. |
|
249 | 249 | |
|
250 | 250 | -[no]messages |
|
251 | 251 | Print messages which IPython collects about its startup |
|
252 | 252 | process (default on). |
|
253 | 253 | |
|
254 | 254 | -[no]pdb |
|
255 | 255 | Automatically call the pdb debugger after every uncaught |
|
256 | 256 | exception. If you are used to debugging using pdb, this puts |
|
257 | 257 | you automatically inside of it after any call (either in |
|
258 | 258 | IPython or in code called by it) which triggers an exception |
|
259 | 259 | which goes uncaught. |
|
260 | 260 | |
|
261 | 261 | -pydb |
|
262 | 262 | Makes IPython use the third party "pydb" package as debugger, |
|
263 | 263 | instead of pdb. Requires that pydb is installed. |
|
264 | 264 | |
|
265 | 265 | -[no]pprint |
|
266 | 266 | ipython can optionally use the pprint (pretty printer) module |
|
267 | 267 | for displaying results. pprint tends to give a nicer display |
|
268 | 268 | of nested data structures. If you like it, you can turn it on |
|
269 | 269 | permanently in your config file (default off). |
|
270 | 270 | |
|
271 | 271 | -profile, p <name> |
|
272 | 272 | |
|
273 | 273 | assume that your config file is ipythonrc-<name> or |
|
274 | 274 | ipy_profile_<name>.py (looks in current dir first, then in |
|
275 | 275 | IPYTHONDIR). This is a quick way to keep and load multiple |
|
276 | 276 | config files for different tasks, especially if you use the |
|
277 | 277 | include option of config files. You can keep a basic |
|
278 | 278 | IPYTHONDIR/ipythonrc file and then have other 'profiles' which |
|
279 | 279 | include this one and load extra things for particular |
|
280 | 280 | tasks. For example: |
|
281 | 281 | |
|
282 | 282 | 1. $HOME/.ipython/ipythonrc : load basic things you always want. |
|
283 | 283 | 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules. |
|
284 | 284 | 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules. |
|
285 | 285 | |
|
286 | 286 | Since it is possible to create an endless loop by having |
|
287 | 287 | circular file inclusions, IPython will stop if it reaches 15 |
|
288 | 288 | recursive inclusions. |
|
289 | 289 | |
|
290 | 290 | -prompt_in1, pi1 <string> |
|
291 | Specify the string used for input prompts. Note that if you | |
|
292 | are using numbered prompts, the number is represented with a | |
|
293 | '\#' in the string. Don't forget to quote strings with spaces | |
|
294 | embedded in them. Default: 'In [\#]:'. Sec. Prompts_ | |
|
295 | discusses in detail all the available escapes to customize | |
|
296 | your prompts. | |
|
291 | ||
|
292 | Specify the string used for input prompts. Note that if you are using | |
|
293 | numbered prompts, the number is represented with a '\#' in the | |
|
294 | string. Don't forget to quote strings with spaces embedded in | |
|
295 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` | |
|
296 | discusses in detail all the available escapes to customize your | |
|
297 | prompts. | |
|
297 | 298 | |
|
298 | 299 | -prompt_in2, pi2 <string> |
|
299 | 300 | Similar to the previous option, but used for the continuation |
|
300 | 301 | prompts. The special sequence '\D' is similar to '\#', but |
|
301 | 302 | with all digits replaced dots (so you can have your |
|
302 | 303 | continuation prompt aligned with your input prompt). Default: |
|
303 | 304 | ' .\D.:' (note three spaces at the start for alignment with |
|
304 | 305 | 'In [\#]'). |
|
305 | 306 | |
|
306 | 307 | -prompt_out,po <string> |
|
307 | 308 | String used for output prompts, also uses numbers like |
|
308 | 309 | prompt_in1. Default: 'Out[\#]:' |
|
309 | 310 | |
|
310 | 311 | -quick start in bare bones mode (no config file loaded). |
|
311 | 312 | |
|
312 | 313 | -rcfile <name> |
|
313 | 314 | name of your IPython resource configuration file. Normally |
|
314 | 315 | IPython loads ipythonrc (from current directory) or |
|
315 | 316 | IPYTHONDIR/ipythonrc. |
|
316 | 317 | |
|
317 | 318 | If the loading of your config file fails, IPython starts with |
|
318 | 319 | a bare bones configuration (no modules loaded at all). |
|
319 | 320 | |
|
320 | 321 | -[no]readline |
|
321 | 322 | use the readline library, which is needed to support name |
|
322 | 323 | completion and command history, among other things. It is |
|
323 | 324 | enabled by default, but may cause problems for users of |
|
324 | 325 | X/Emacs in Python comint or shell buffers. |
|
325 | 326 | |
|
326 | 327 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
327 | 328 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
328 | 329 | shell and C-c !) buffers do not. |
|
329 | 330 | |
|
330 | 331 | -screen_length, sl <n> |
|
331 | 332 | number of lines of your screen. This is used to control |
|
332 | 333 | printing of very long strings. Strings longer than this number |
|
333 | 334 | of lines will be sent through a pager instead of directly |
|
334 | 335 | printed. |
|
335 | 336 | |
|
336 | 337 | The default value for this is 0, which means IPython will |
|
337 | 338 | auto-detect your screen size every time it needs to print certain |
|
338 | 339 | potentially long strings (this doesn't change the behavior of the |
|
339 | 340 | 'print' keyword, it's only triggered internally). If for some |
|
340 | 341 | reason this isn't working well (it needs curses support), specify |
|
341 | 342 | it yourself. Otherwise don't change the default. |
|
342 | 343 | |
|
343 | 344 | -separate_in, si <string> |
|
344 | 345 | |
|
345 | 346 | separator before input prompts. |
|
346 | 347 | Default: '\n' |
|
347 | 348 | |
|
348 | 349 | -separate_out, so <string> |
|
349 | 350 | separator before output prompts. |
|
350 | 351 | Default: nothing. |
|
351 | 352 | |
|
352 | 353 | -separate_out2, so2 |
|
353 | 354 | separator after output prompts. |
|
354 | 355 | Default: nothing. |
|
355 | 356 | For these three options, use the value 0 to specify no separator. |
|
356 | 357 | |
|
357 | 358 | -nosep |
|
358 | 359 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 |
|
359 | 360 | 0'. Simply removes all input/output separators. |
|
360 | 361 | |
|
361 | 362 | -upgrade |
|
362 | 363 | allows you to upgrade your IPYTHONDIR configuration when you |
|
363 | 364 | install a new version of IPython. Since new versions may |
|
364 | 365 | include new command line options or example files, this copies |
|
365 | 366 | updated ipythonrc-type files. However, it backs up (with a |
|
366 | 367 | .old extension) all files which it overwrites so that you can |
|
367 | 368 | merge back any customizations you might have in your personal |
|
368 | 369 | files. Note that you should probably use %upgrade instead, |
|
369 | 370 | it's a safer alternative. |
|
370 | 371 | |
|
371 | 372 | |
|
372 | 373 | -Version print version information and exit. |
|
373 | 374 | |
|
374 | 375 | -wxversion <string> |
|
375 | 376 | Select a specific version of wxPython (used in conjunction |
|
376 | 377 | with -wthread). Requires the wxversion module, part of recent |
|
377 | 378 | wxPython distributions |
|
378 | 379 | |
|
379 | 380 | -xmode <modename> |
|
380 | 381 | |
|
381 | 382 | Mode for exception reporting. |
|
382 | 383 | |
|
383 | 384 | Valid modes: Plain, Context and Verbose. |
|
384 | 385 | |
|
385 | 386 | * Plain: similar to python's normal traceback printing. |
|
386 | 387 | * Context: prints 5 lines of context source code around each |
|
387 | 388 | line in the traceback. |
|
388 | 389 | * Verbose: similar to Context, but additionally prints the |
|
389 | 390 | variables currently visible where the exception happened |
|
390 | 391 | (shortening their strings if too long). This can potentially be |
|
391 | 392 | very slow, if you happen to have a huge data structure whose |
|
392 | 393 | string representation is complex to compute. Your computer may |
|
393 | 394 | appear to freeze for a while with cpu usage at 100%. If this |
|
394 | 395 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
395 | 396 | more than once). |
|
396 | 397 | |
|
397 | 398 | Interactive use |
|
398 | 399 | =============== |
|
399 | 400 | |
|
400 | 401 | Warning: IPython relies on the existence of a global variable called |
|
401 | 402 | _ip which controls the shell itself. If you redefine _ip to anything, |
|
402 | 403 | bizarre behavior will quickly occur. |
|
403 | 404 | |
|
404 | 405 | Other than the above warning, IPython is meant to work as a drop-in |
|
405 | 406 | replacement for the standard interactive interpreter. As such, any code |
|
406 | 407 | which is valid python should execute normally under IPython (cases where |
|
407 | 408 | this is not true should be reported as bugs). It does, however, offer |
|
408 | 409 | many features which are not available at a standard python prompt. What |
|
409 | 410 | follows is a list of these. |
|
410 | 411 | |
|
411 | 412 | |
|
412 | 413 | Caution for Windows users |
|
413 | 414 | ------------------------- |
|
414 | 415 | |
|
415 | 416 | Windows, unfortunately, uses the '\' character as a path |
|
416 | 417 | separator. This is a terrible choice, because '\' also represents the |
|
417 | 418 | escape character in most modern programming languages, including |
|
418 | 419 | Python. For this reason, using '/' character is recommended if you |
|
419 | 420 | have problems with ``\``. However, in Windows commands '/' flags |
|
420 | 421 | options, so you can not use it for the root directory. This means that |
|
421 | 422 | paths beginning at the root must be typed in a contrived manner like: |
|
422 | 423 | ``%copy \opt/foo/bar.txt \tmp`` |
|
423 | 424 | |
|
424 | 425 | .. _magic: |
|
425 | 426 | |
|
426 | 427 | Magic command system |
|
427 | 428 | -------------------- |
|
428 | 429 | |
|
429 | 430 | IPython will treat any line whose first character is a % as a special |
|
430 | 431 | call to a 'magic' function. These allow you to control the behavior of |
|
431 | 432 | IPython itself, plus a lot of system-type features. They are all |
|
432 | 433 | prefixed with a % character, but parameters are given without |
|
433 | 434 | parentheses or quotes. |
|
434 | 435 | |
|
435 | 436 | Example: typing '%cd mydir' (without the quotes) changes you working |
|
436 | 437 | directory to 'mydir', if it exists. |
|
437 | 438 | |
|
438 | 439 | If you have 'automagic' enabled (in your ipythonrc file, via the command |
|
439 | 440 | line option -automagic or with the %automagic function), you don't need |
|
440 | 441 | to type in the % explicitly. IPython will scan its internal list of |
|
441 | 442 | magic functions and call one if it exists. With automagic on you can |
|
442 | 443 | then just type 'cd mydir' to go to directory 'mydir'. The automagic |
|
443 | 444 | system has the lowest possible precedence in name searches, so defining |
|
444 | 445 | an identifier with the same name as an existing magic function will |
|
445 | 446 | shadow it for automagic use. You can still access the shadowed magic |
|
446 | 447 | function by explicitly using the % character at the beginning of the line. |
|
447 | 448 | |
|
448 | 449 | An example (with automagic on) should clarify all this:: |
|
449 | 450 | |
|
450 | 451 | In [1]: cd ipython # %cd is called by automagic |
|
451 | 452 | |
|
452 | 453 | /home/fperez/ipython |
|
453 | 454 | |
|
454 | 455 | In [2]: cd=1 # now cd is just a variable |
|
455 | 456 | |
|
456 | 457 | In [3]: cd .. # and doesn't work as a function anymore |
|
457 | 458 | |
|
458 | 459 | ------------------------------ |
|
459 | 460 | |
|
460 | 461 | File "<console>", line 1 |
|
461 | 462 | |
|
462 | 463 | cd .. |
|
463 | 464 | |
|
464 | 465 | ^ |
|
465 | 466 | |
|
466 | 467 | SyntaxError: invalid syntax |
|
467 | 468 | |
|
468 | 469 | In [4]: %cd .. # but %cd always works |
|
469 | 470 | |
|
470 | 471 | /home/fperez |
|
471 | 472 | |
|
472 | 473 | In [5]: del cd # if you remove the cd variable |
|
473 | 474 | |
|
474 | 475 | In [6]: cd ipython # automagic can work again |
|
475 | 476 | |
|
476 | 477 | /home/fperez/ipython |
|
477 | 478 | |
|
478 | 479 | You can define your own magic functions to extend the system. The |
|
479 | 480 | following example defines a new magic command, %impall:: |
|
480 | 481 | |
|
481 | 482 | import IPython.ipapi |
|
482 | 483 | |
|
483 | 484 | ip = IPython.ipapi.get() |
|
484 | 485 | |
|
485 | 486 | def doimp(self, arg): |
|
486 | 487 | |
|
487 | 488 | ip = self.api |
|
488 | 489 | |
|
489 | 490 | ip.ex("import %s; reload(%s); from %s import *" % ( |
|
490 | 491 | |
|
491 | 492 | arg,arg,arg) |
|
492 | 493 | |
|
493 | 494 | ) |
|
494 | 495 | |
|
495 | 496 | ip.expose_magic('impall', doimp) |
|
496 | 497 | |
|
497 | 498 | You can also define your own aliased names for magic functions. In your |
|
498 | 499 | ipythonrc file, placing a line like: |
|
499 | 500 | |
|
500 | 501 | execute __IP.magic_cl = __IP.magic_clear |
|
501 | 502 | |
|
502 | 503 | will define %cl as a new name for %clear. |
|
503 | 504 | |
|
504 | 505 | Type %magic for more information, including a list of all available |
|
505 | 506 | magic functions at any time and their docstrings. You can also type |
|
506 | 507 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for |
|
507 | 508 | information on the '?' system) to get information about any particular |
|
508 | 509 | magic function you are interested in. |
|
509 | 510 | |
|
510 | 511 | |
|
511 | 512 | Magic commands |
|
512 | 513 | -------------- |
|
513 | 514 | |
|
514 | 515 | The rest of this section is automatically generated for each release |
|
515 | 516 | from the docstrings in the IPython code. Therefore the formatting is |
|
516 | 517 | somewhat minimal, but this method has the advantage of having |
|
517 | 518 | information always in sync with the code. |
|
518 | 519 | |
|
519 | 520 | A list of all the magic commands available in IPython's default |
|
520 | 521 | installation follows. This is similar to what you'll see by simply |
|
521 | 522 | typing %magic at the prompt, but that will also give you information |
|
522 | 523 | about magic commands you may have added as part of your personal |
|
523 | 524 | customizations. |
|
524 | 525 | |
|
525 | 526 | .. magic_start |
|
526 | 527 | |
|
527 | 528 | **%Exit**:: |
|
528 | 529 | |
|
529 | 530 | Exit IPython without confirmation. |
|
530 | 531 | |
|
531 | 532 | **%Pprint**:: |
|
532 | 533 | |
|
533 | 534 | Toggle pretty printing on/off. |
|
534 | 535 | |
|
535 | 536 | **%alias**:: |
|
536 | 537 | |
|
537 | 538 | Define an alias for a system command. |
|
538 | 539 | |
|
539 | 540 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
540 | 541 | |
|
541 | 542 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
542 | 543 | params' (from your underlying operating system). |
|
543 | 544 | |
|
544 | 545 | Aliases have lower precedence than magic functions and Python normal |
|
545 | 546 | variables, so if 'foo' is both a Python variable and an alias, the |
|
546 | 547 | alias can not be executed until 'del foo' removes the Python variable. |
|
547 | 548 | |
|
548 | 549 | You can use the %l specifier in an alias definition to represent the |
|
549 | 550 | whole line when the alias is called. For example: |
|
550 | 551 | |
|
551 | 552 | In [2]: alias all echo "Input in brackets: <%l>"\ |
|
552 | 553 | In [3]: all hello world\ |
|
553 | 554 | Input in brackets: <hello world> |
|
554 | 555 | |
|
555 | 556 | You can also define aliases with parameters using %s specifiers (one |
|
556 | 557 | per parameter): |
|
557 | 558 | |
|
558 | 559 | In [1]: alias parts echo first %s second %s\ |
|
559 | 560 | In [2]: %parts A B\ |
|
560 | 561 | first A second B\ |
|
561 | 562 | In [3]: %parts A\ |
|
562 | 563 | Incorrect number of arguments: 2 expected.\ |
|
563 | 564 | parts is an alias to: 'echo first %s second %s' |
|
564 | 565 | |
|
565 | 566 | Note that %l and %s are mutually exclusive. You can only use one or |
|
566 | 567 | the other in your aliases. |
|
567 | 568 | |
|
568 | 569 | Aliases expand Python variables just like system calls using ! or !! |
|
569 | 570 | do: all expressions prefixed with '$' get expanded. For details of |
|
570 | 571 | the semantic rules, see PEP-215: |
|
571 | 572 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
572 | 573 | IPython for variable expansion. If you want to access a true shell |
|
573 | 574 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
574 | 575 | |
|
575 | 576 | In [6]: alias show echo\ |
|
576 | 577 | In [7]: PATH='A Python string'\ |
|
577 | 578 | In [8]: show $PATH\ |
|
578 | 579 | A Python string\ |
|
579 | 580 | In [9]: show $$PATH\ |
|
580 | 581 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
581 | 582 | |
|
582 | 583 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
583 | 584 | and %rehashx functions, which automatically create aliases for the |
|
584 | 585 | contents of your $PATH. |
|
585 | 586 | |
|
586 | 587 | If called with no parameters, %alias prints the current alias table. |
|
587 | 588 | |
|
588 | 589 | **%autocall**:: |
|
589 | 590 | |
|
590 | 591 | Make functions callable without having to type parentheses. |
|
591 | 592 | |
|
592 | 593 | Usage: |
|
593 | 594 | |
|
594 | 595 | %autocall [mode] |
|
595 | 596 | |
|
596 | 597 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
597 | 598 | value is toggled on and off (remembering the previous state). |
|
598 | 599 | |
|
599 | 600 | In more detail, these values mean: |
|
600 | 601 | |
|
601 | 602 | 0 -> fully disabled |
|
602 | 603 | |
|
603 | 604 | 1 -> active, but do not apply if there are no arguments on the line. |
|
604 | 605 | |
|
605 | 606 | In this mode, you get: |
|
606 | 607 | |
|
607 | 608 | In [1]: callable |
|
608 | 609 | Out[1]: <built-in function callable> |
|
609 | 610 | |
|
610 | 611 | In [2]: callable 'hello' |
|
611 | 612 | ------> callable('hello') |
|
612 | 613 | Out[2]: False |
|
613 | 614 | |
|
614 | 615 | 2 -> Active always. Even if no arguments are present, the callable |
|
615 | 616 | object is called: |
|
616 | 617 | |
|
617 | 618 | In [4]: callable |
|
618 | 619 | ------> callable() |
|
619 | 620 | |
|
620 | 621 | Note that even with autocall off, you can still use '/' at the start of |
|
621 | 622 | a line to treat the first argument on the command line as a function |
|
622 | 623 | and add parentheses to it: |
|
623 | 624 | |
|
624 | 625 | In [8]: /str 43 |
|
625 | 626 | ------> str(43) |
|
626 | 627 | Out[8]: '43' |
|
627 | 628 | |
|
628 | 629 | **%autoindent**:: |
|
629 | 630 | |
|
630 | 631 | Toggle autoindent on/off (if available). |
|
631 | 632 | |
|
632 | 633 | **%automagic**:: |
|
633 | 634 | |
|
634 | 635 | Make magic functions callable without having to type the initial %. |
|
635 | 636 | |
|
636 | 637 | Without argumentsl toggles on/off (when off, you must call it as |
|
637 | 638 | %automagic, of course). With arguments it sets the value, and you can |
|
638 | 639 | use any of (case insensitive): |
|
639 | 640 | |
|
640 | 641 | - on,1,True: to activate |
|
641 | 642 | |
|
642 | 643 | - off,0,False: to deactivate. |
|
643 | 644 | |
|
644 | 645 | Note that magic functions have lowest priority, so if there's a |
|
645 | 646 | variable whose name collides with that of a magic fn, automagic won't |
|
646 | 647 | work for that function (you get the variable instead). However, if you |
|
647 | 648 | delete the variable (del var), the previously shadowed magic function |
|
648 | 649 | becomes visible to automagic again. |
|
649 | 650 | |
|
650 | 651 | **%bg**:: |
|
651 | 652 | |
|
652 | 653 | Run a job in the background, in a separate thread. |
|
653 | 654 | |
|
654 | 655 | For example, |
|
655 | 656 | |
|
656 | 657 | %bg myfunc(x,y,z=1) |
|
657 | 658 | |
|
658 | 659 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
659 | 660 | execution starts, a message will be printed indicating the job |
|
660 | 661 | number. If your job number is 5, you can use |
|
661 | 662 | |
|
662 | 663 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
663 | 664 | |
|
664 | 665 | to assign this result to variable 'myvar'. |
|
665 | 666 | |
|
666 | 667 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
667 | 668 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
668 | 669 | its attributes. All attributes not starting with an underscore are |
|
669 | 670 | meant for public use. |
|
670 | 671 | |
|
671 | 672 | In particular, look at the jobs.new() method, which is used to create |
|
672 | 673 | new jobs. This magic %bg function is just a convenience wrapper |
|
673 | 674 | around jobs.new(), for expression-based jobs. If you want to create a |
|
674 | 675 | new job with an explicit function object and arguments, you must call |
|
675 | 676 | jobs.new() directly. |
|
676 | 677 | |
|
677 | 678 | The jobs.new docstring also describes in detail several important |
|
678 | 679 | caveats associated with a thread-based model for background job |
|
679 | 680 | execution. Type jobs.new? for details. |
|
680 | 681 | |
|
681 | 682 | You can check the status of all jobs with jobs.status(). |
|
682 | 683 | |
|
683 | 684 | The jobs variable is set by IPython into the Python builtin namespace. |
|
684 | 685 | If you ever declare a variable named 'jobs', you will shadow this |
|
685 | 686 | name. You can either delete your global jobs variable to regain |
|
686 | 687 | access to the job manager, or make a new name and assign it manually |
|
687 | 688 | to the manager (stored in IPython's namespace). For example, to |
|
688 | 689 | assign the job manager to the Jobs name, use: |
|
689 | 690 | |
|
690 | 691 | Jobs = __builtins__.jobs |
|
691 | 692 | |
|
692 | 693 | **%bookmark**:: |
|
693 | 694 | |
|
694 | 695 | Manage IPython's bookmark system. |
|
695 | 696 | |
|
696 | 697 | %bookmark <name> - set bookmark to current dir |
|
697 | 698 | %bookmark <name> <dir> - set bookmark to <dir> |
|
698 | 699 | %bookmark -l - list all bookmarks |
|
699 | 700 | %bookmark -d <name> - remove bookmark |
|
700 | 701 | %bookmark -r - remove all bookmarks |
|
701 | 702 | |
|
702 | 703 | You can later on access a bookmarked folder with: |
|
703 | 704 | %cd -b <name> |
|
704 | 705 | or simply '%cd <name>' if there is no directory called <name> AND |
|
705 | 706 | there is such a bookmark defined. |
|
706 | 707 | |
|
707 | 708 | Your bookmarks persist through IPython sessions, but they are |
|
708 | 709 | associated with each profile. |
|
709 | 710 | |
|
710 | 711 | **%cd**:: |
|
711 | 712 | |
|
712 | 713 | Change the current working directory. |
|
713 | 714 | |
|
714 | 715 | This command automatically maintains an internal list of directories |
|
715 | 716 | you visit during your IPython session, in the variable _dh. The |
|
716 | 717 | command %dhist shows this history nicely formatted. You can also |
|
717 | 718 | do 'cd -<tab>' to see directory history conveniently. |
|
718 | 719 | |
|
719 | 720 | Usage: |
|
720 | 721 | |
|
721 | 722 | cd 'dir': changes to directory 'dir'. |
|
722 | 723 | |
|
723 | 724 | cd -: changes to the last visited directory. |
|
724 | 725 | |
|
725 | 726 | cd -<n>: changes to the n-th directory in the directory history. |
|
726 | 727 | |
|
727 | 728 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
728 | 729 | (note: cd <bookmark_name> is enough if there is no |
|
729 | 730 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
730 | 731 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
731 | 732 | |
|
732 | 733 | Options: |
|
733 | 734 | |
|
734 | 735 | -q: quiet. Do not print the working directory after the cd command is |
|
735 | 736 | executed. By default IPython's cd command does print this directory, |
|
736 | 737 | since the default prompts do not display path information. |
|
737 | 738 | |
|
738 | 739 | Note that !cd doesn't work for this purpose because the shell where |
|
739 | 740 | !command runs is immediately discarded after executing 'command'. |
|
740 | 741 | |
|
741 | 742 | **%clear**:: |
|
742 | 743 | |
|
743 | 744 | Clear various data (e.g. stored history data) |
|
744 | 745 | |
|
745 | 746 | %clear out - clear output history |
|
746 | 747 | %clear in - clear input history |
|
747 | 748 | %clear shadow_compress - Compresses shadow history (to speed up ipython) |
|
748 | 749 | %clear shadow_nuke - permanently erase all entries in shadow history |
|
749 | 750 | %clear dhist - clear dir history |
|
750 | 751 | |
|
751 | 752 | **%color_info**:: |
|
752 | 753 | |
|
753 | 754 | Toggle color_info. |
|
754 | 755 | |
|
755 | 756 | The color_info configuration parameter controls whether colors are |
|
756 | 757 | used for displaying object details (by things like %psource, %pfile or |
|
757 | 758 | the '?' system). This function toggles this value with each call. |
|
758 | 759 | |
|
759 | 760 | Note that unless you have a fairly recent pager (less works better |
|
760 | 761 | than more) in your system, using colored object information displays |
|
761 | 762 | will not work properly. Test it and see. |
|
762 | 763 | |
|
763 | 764 | **%colors**:: |
|
764 | 765 | |
|
765 | 766 | Switch color scheme for prompts, info system and exception handlers. |
|
766 | 767 | |
|
767 | 768 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
768 | 769 | |
|
769 | 770 | Color scheme names are not case-sensitive. |
|
770 | 771 | |
|
771 | 772 | **%cpaste**:: |
|
772 | 773 | |
|
773 | 774 | Allows you to paste & execute a pre-formatted code block from clipboard |
|
774 | 775 | |
|
775 | 776 | You must terminate the block with '--' (two minus-signs) alone on the |
|
776 | 777 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
777 | 778 | is the new sentinel for this operation) |
|
778 | 779 | |
|
779 | 780 | The block is dedented prior to execution to enable execution of method |
|
780 | 781 | definitions. '>' and '+' characters at the beginning of a line are |
|
781 | 782 | ignored, to allow pasting directly from e-mails or diff files. The |
|
782 | 783 | executed block is also assigned to variable named 'pasted_block' for |
|
783 | 784 | later editing with '%edit pasted_block'. |
|
784 | 785 | |
|
785 | 786 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
786 | 787 | This assigns the pasted block to variable 'foo' as string, without |
|
787 | 788 | dedenting or executing it. |
|
788 | 789 | |
|
789 | 790 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
790 | 791 | Just press enter and type -- (and press enter again) and the block |
|
791 | 792 | will be what was just pasted. |
|
792 | 793 | |
|
793 | 794 | IPython statements (magics, shell escapes) are not supported (yet). |
|
794 | 795 | |
|
795 | 796 | **%debug**:: |
|
796 | 797 | |
|
797 | 798 | Activate the interactive debugger in post-mortem mode. |
|
798 | 799 | |
|
799 | 800 | If an exception has just occurred, this lets you inspect its stack |
|
800 | 801 | frames interactively. Note that this will always work only on the last |
|
801 | 802 | traceback that occurred, so you must call this quickly after an |
|
802 | 803 | exception that you wish to inspect has fired, because if another one |
|
803 | 804 | occurs, it clobbers the previous one. |
|
804 | 805 | |
|
805 | 806 | If you want IPython to automatically do this on every exception, see |
|
806 | 807 | the %pdb magic for more details. |
|
807 | 808 | |
|
808 | 809 | **%dhist**:: |
|
809 | 810 | |
|
810 | 811 | Print your history of visited directories. |
|
811 | 812 | |
|
812 | 813 | %dhist -> print full history\ |
|
813 | 814 | %dhist n -> print last n entries only\ |
|
814 | 815 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\ |
|
815 | 816 | |
|
816 | 817 | This history is automatically maintained by the %cd command, and |
|
817 | 818 | always available as the global list variable _dh. You can use %cd -<n> |
|
818 | 819 | to go to directory number <n>. |
|
819 | 820 | |
|
820 | 821 | Note that most of time, you should view directory history by entering |
|
821 | 822 | cd -<TAB>. |
|
822 | 823 | |
|
823 | 824 | **%dirs**:: |
|
824 | 825 | |
|
825 | 826 | Return the current directory stack. |
|
826 | 827 | |
|
827 | 828 | **%doctest_mode**:: |
|
828 | 829 | |
|
829 | 830 | Toggle doctest mode on and off. |
|
830 | 831 | |
|
831 | 832 | This mode allows you to toggle the prompt behavior between normal |
|
832 | 833 | IPython prompts and ones that are as similar to the default IPython |
|
833 | 834 | interpreter as possible. |
|
834 | 835 | |
|
835 | 836 | It also supports the pasting of code snippets that have leading '>>>' |
|
836 | 837 | and '...' prompts in them. This means that you can paste doctests from |
|
837 | 838 | files or docstrings (even if they have leading whitespace), and the |
|
838 | 839 | code will execute correctly. You can then use '%history -tn' to see |
|
839 | 840 | the translated history without line numbers; this will give you the |
|
840 | 841 | input after removal of all the leading prompts and whitespace, which |
|
841 | 842 | can be pasted back into an editor. |
|
842 | 843 | |
|
843 | 844 | With these features, you can switch into this mode easily whenever you |
|
844 | 845 | need to do testing and changes to doctests, without having to leave |
|
845 | 846 | your existing IPython session. |
|
846 | 847 | |
|
847 | 848 | **%ed**:: |
|
848 | 849 | |
|
849 | 850 | Alias to %edit. |
|
850 | 851 | |
|
851 | 852 | **%edit**:: |
|
852 | 853 | |
|
853 | 854 | Bring up an editor and execute the resulting code. |
|
854 | 855 | |
|
855 | 856 | Usage: |
|
856 | 857 | %edit [options] [args] |
|
857 | 858 | |
|
858 | 859 | %edit runs IPython's editor hook. The default version of this hook is |
|
859 | 860 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
860 | 861 | environment variable $EDITOR. If this isn't found, it will default to |
|
861 | 862 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
862 | 863 | docstring for how to change the editor hook. |
|
863 | 864 | |
|
864 | 865 | You can also set the value of this editor via the command line option |
|
865 | 866 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
866 | 867 | specifically for IPython an editor different from your typical default |
|
867 | 868 | (and for Windows users who typically don't set environment variables). |
|
868 | 869 | |
|
869 | 870 | This command allows you to conveniently edit multi-line code right in |
|
870 | 871 | your IPython session. |
|
871 | 872 | |
|
872 | 873 | If called without arguments, %edit opens up an empty editor with a |
|
873 | 874 | temporary file and will execute the contents of this file when you |
|
874 | 875 | close it (don't forget to save it!). |
|
875 | 876 | |
|
876 | 877 | |
|
877 | 878 | Options: |
|
878 | 879 | |
|
879 | 880 | -n <number>: open the editor at a specified line number. By default, |
|
880 | 881 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
881 | 882 | you can configure this by providing your own modified hook if your |
|
882 | 883 | favorite editor supports line-number specifications with a different |
|
883 | 884 | syntax. |
|
884 | 885 | |
|
885 | 886 | -p: this will call the editor with the same data as the previous time |
|
886 | 887 | it was used, regardless of how long ago (in your current session) it |
|
887 | 888 | was. |
|
888 | 889 | |
|
889 | 890 | -r: use 'raw' input. This option only applies to input taken from the |
|
890 | 891 | user's history. By default, the 'processed' history is used, so that |
|
891 | 892 | magics are loaded in their transformed version to valid Python. If |
|
892 | 893 | this option is given, the raw input as typed as the command line is |
|
893 | 894 | used instead. When you exit the editor, it will be executed by |
|
894 | 895 | IPython's own processor. |
|
895 | 896 | |
|
896 | 897 | -x: do not execute the edited code immediately upon exit. This is |
|
897 | 898 | mainly useful if you are editing programs which need to be called with |
|
898 | 899 | command line arguments, which you can then do using %run. |
|
899 | 900 | |
|
900 | 901 | |
|
901 | 902 | Arguments: |
|
902 | 903 | |
|
903 | 904 | If arguments are given, the following possibilites exist: |
|
904 | 905 | |
|
905 | 906 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
906 | 907 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
907 | 908 | loaded into the editor. The syntax is the same of the %macro command. |
|
908 | 909 | |
|
909 | 910 | - If the argument doesn't start with a number, it is evaluated as a |
|
910 | 911 | variable and its contents loaded into the editor. You can thus edit |
|
911 | 912 | any string which contains python code (including the result of |
|
912 | 913 | previous edits). |
|
913 | 914 | |
|
914 | 915 | - If the argument is the name of an object (other than a string), |
|
915 | 916 | IPython will try to locate the file where it was defined and open the |
|
916 | 917 | editor at the point where it is defined. You can use `%edit function` |
|
917 | 918 | to load an editor exactly at the point where 'function' is defined, |
|
918 | 919 | edit it and have the file be executed automatically. |
|
919 | 920 | |
|
920 | 921 | If the object is a macro (see %macro for details), this opens up your |
|
921 | 922 | specified editor with a temporary file containing the macro's data. |
|
922 | 923 | Upon exit, the macro is reloaded with the contents of the file. |
|
923 | 924 | |
|
924 | 925 | Note: opening at an exact line is only supported under Unix, and some |
|
925 | 926 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
926 | 927 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
927 | 928 | (X)Emacs, vi, jed, pico and joe all do. |
|
928 | 929 | |
|
929 | 930 | - If the argument is not found as a variable, IPython will look for a |
|
930 | 931 | file with that name (adding .py if necessary) and load it into the |
|
931 | 932 | editor. It will execute its contents with execfile() when you exit, |
|
932 | 933 | loading any code in the file into your interactive namespace. |
|
933 | 934 | |
|
934 | 935 | After executing your code, %edit will return as output the code you |
|
935 | 936 | typed in the editor (except when it was an existing file). This way |
|
936 | 937 | you can reload the code in further invocations of %edit as a variable, |
|
937 | 938 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
938 | 939 | the output. |
|
939 | 940 | |
|
940 | 941 | Note that %edit is also available through the alias %ed. |
|
941 | 942 | |
|
942 | 943 | This is an example of creating a simple function inside the editor and |
|
943 | 944 | then modifying it. First, start up the editor: |
|
944 | 945 | |
|
945 | 946 | In [1]: ed\ |
|
946 | 947 | Editing... done. Executing edited code...\ |
|
947 | 948 | Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n' |
|
948 | 949 | |
|
949 | 950 | We can then call the function foo(): |
|
950 | 951 | |
|
951 | 952 | In [2]: foo()\ |
|
952 | 953 | foo() was defined in an editing session |
|
953 | 954 | |
|
954 | 955 | Now we edit foo. IPython automatically loads the editor with the |
|
955 | 956 | (temporary) file where foo() was previously defined: |
|
956 | 957 | |
|
957 | 958 | In [3]: ed foo\ |
|
958 | 959 | Editing... done. Executing edited code... |
|
959 | 960 | |
|
960 | 961 | And if we call foo() again we get the modified version: |
|
961 | 962 | |
|
962 | 963 | In [4]: foo()\ |
|
963 | 964 | foo() has now been changed! |
|
964 | 965 | |
|
965 | 966 | Here is an example of how to edit a code snippet successive |
|
966 | 967 | times. First we call the editor: |
|
967 | 968 | |
|
968 | 969 | In [8]: ed\ |
|
969 | 970 | Editing... done. Executing edited code...\ |
|
970 | 971 | hello\ |
|
971 | 972 | Out[8]: "print 'hello'\n" |
|
972 | 973 | |
|
973 | 974 | Now we call it again with the previous output (stored in _): |
|
974 | 975 | |
|
975 | 976 | In [9]: ed _\ |
|
976 | 977 | Editing... done. Executing edited code...\ |
|
977 | 978 | hello world\ |
|
978 | 979 | Out[9]: "print 'hello world'\n" |
|
979 | 980 | |
|
980 | 981 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
981 | 982 | |
|
982 | 983 | In [10]: ed _8\ |
|
983 | 984 | Editing... done. Executing edited code...\ |
|
984 | 985 | hello again\ |
|
985 | 986 | Out[10]: "print 'hello again'\n" |
|
986 | 987 | |
|
987 | 988 | |
|
988 | 989 | Changing the default editor hook: |
|
989 | 990 | |
|
990 | 991 | If you wish to write your own editor hook, you can put it in a |
|
991 | 992 | configuration file which you load at startup time. The default hook |
|
992 | 993 | is defined in the IPython.hooks module, and you can use that as a |
|
993 | 994 | starting example for further modifications. That file also has |
|
994 | 995 | general instructions on how to set a new hook for use once you've |
|
995 | 996 | defined it. |
|
996 | 997 | |
|
997 | 998 | **%env**:: |
|
998 | 999 | |
|
999 | 1000 | List environment variables. |
|
1000 | 1001 | |
|
1001 | 1002 | **%exit**:: |
|
1002 | 1003 | |
|
1003 | 1004 | Exit IPython, confirming if configured to do so. |
|
1004 | 1005 | |
|
1005 | 1006 | You can configure whether IPython asks for confirmation upon exit by |
|
1006 | 1007 | setting the confirm_exit flag in the ipythonrc file. |
|
1007 | 1008 | |
|
1008 | 1009 | **%hist**:: |
|
1009 | 1010 | |
|
1010 | 1011 | Alternate name for %history. |
|
1011 | 1012 | |
|
1012 | 1013 | **%history**:: |
|
1013 | 1014 | |
|
1014 | 1015 | Print input history (_i<n> variables), with most recent last. |
|
1015 | 1016 | |
|
1016 | 1017 | %history -> print at most 40 inputs (some may be multi-line)\ |
|
1017 | 1018 | %history n -> print at most n inputs\ |
|
1018 | 1019 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\ |
|
1019 | 1020 | |
|
1020 | 1021 | Each input's number <n> is shown, and is accessible as the |
|
1021 | 1022 | automatically generated variable _i<n>. Multi-line statements are |
|
1022 | 1023 | printed starting at a new line for easy copy/paste. |
|
1023 | 1024 | |
|
1024 | 1025 | |
|
1025 | 1026 | Options: |
|
1026 | 1027 | |
|
1027 | 1028 | -n: do NOT print line numbers. This is useful if you want to get a |
|
1028 | 1029 | printout of many lines which can be directly pasted into a text |
|
1029 | 1030 | editor. |
|
1030 | 1031 | |
|
1031 | 1032 | This feature is only available if numbered prompts are in use. |
|
1032 | 1033 | |
|
1033 | 1034 | -t: (default) print the 'translated' history, as IPython understands it. |
|
1034 | 1035 | IPython filters your input and converts it all into valid Python source |
|
1035 | 1036 | before executing it (things like magics or aliases are turned into |
|
1036 | 1037 | function calls, for example). With this option, you'll see the native |
|
1037 | 1038 | history instead of the user-entered version: '%cd /' will be seen as |
|
1038 | 1039 | '_ip.magic("%cd /")' instead of '%cd /'. |
|
1039 | 1040 | |
|
1040 | 1041 | -r: print the 'raw' history, i.e. the actual commands you typed. |
|
1041 | 1042 | |
|
1042 | 1043 | -g: treat the arg as a pattern to grep for in (full) history. |
|
1043 | 1044 | This includes the "shadow history" (almost all commands ever written). |
|
1044 | 1045 | Use '%hist -g' to show full shadow history (may be very long). |
|
1045 | 1046 | In shadow history, every index nuwber starts with 0. |
|
1046 | 1047 | |
|
1047 | 1048 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
1048 | 1049 | the given file. The file is always overwritten, though IPython asks for |
|
1049 | 1050 | confirmation first if it already exists. |
|
1050 | 1051 | |
|
1051 | 1052 | **%logoff**:: |
|
1052 | 1053 | |
|
1053 | 1054 | Temporarily stop logging. |
|
1054 | 1055 | |
|
1055 | 1056 | You must have previously started logging. |
|
1056 | 1057 | |
|
1057 | 1058 | **%logon**:: |
|
1058 | 1059 | |
|
1059 | 1060 | Restart logging. |
|
1060 | 1061 | |
|
1061 | 1062 | This function is for restarting logging which you've temporarily |
|
1062 | 1063 | stopped with %logoff. For starting logging for the first time, you |
|
1063 | 1064 | must use the %logstart function, which allows you to specify an |
|
1064 | 1065 | optional log filename. |
|
1065 | 1066 | |
|
1066 | 1067 | **%logstart**:: |
|
1067 | 1068 | |
|
1068 | 1069 | Start logging anywhere in a session. |
|
1069 | 1070 | |
|
1070 | 1071 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1071 | 1072 | |
|
1072 | 1073 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1073 | 1074 | current directory, in 'rotate' mode (see below). |
|
1074 | 1075 | |
|
1075 | 1076 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1076 | 1077 | history up to that point and then continues logging. |
|
1077 | 1078 | |
|
1078 | 1079 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1079 | 1080 | of (note that the modes are given unquoted):\ |
|
1080 | 1081 | append: well, that says it.\ |
|
1081 | 1082 | backup: rename (if exists) to name~ and start name.\ |
|
1082 | 1083 | global: single logfile in your home dir, appended to.\ |
|
1083 | 1084 | over : overwrite existing log.\ |
|
1084 | 1085 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1085 | 1086 | |
|
1086 | 1087 | Options: |
|
1087 | 1088 | |
|
1088 | 1089 | -o: log also IPython's output. In this mode, all commands which |
|
1089 | 1090 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1090 | 1091 | their corresponding input line. The output lines are always |
|
1091 | 1092 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1092 | 1093 | Python code. |
|
1093 | 1094 | |
|
1094 | 1095 | Since this marker is always the same, filtering only the output from |
|
1095 | 1096 | a log is very easy, using for example a simple awk call: |
|
1096 | 1097 | |
|
1097 | 1098 | awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1098 | 1099 | |
|
1099 | 1100 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1100 | 1101 | input, so that user lines are logged in their final form, converted |
|
1101 | 1102 | into valid Python. For example, %Exit is logged as |
|
1102 | 1103 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1103 | 1104 | exactly as typed, with no transformations applied. |
|
1104 | 1105 | |
|
1105 | 1106 | -t: put timestamps before each input line logged (these are put in |
|
1106 | 1107 | comments). |
|
1107 | 1108 | |
|
1108 | 1109 | **%logstate**:: |
|
1109 | 1110 | |
|
1110 | 1111 | Print the status of the logging system. |
|
1111 | 1112 | |
|
1112 | 1113 | **%logstop**:: |
|
1113 | 1114 | |
|
1114 | 1115 | Fully stop logging and close log file. |
|
1115 | 1116 | |
|
1116 | 1117 | In order to start logging again, a new %logstart call needs to be made, |
|
1117 | 1118 | possibly (though not necessarily) with a new filename, mode and other |
|
1118 | 1119 | options. |
|
1119 | 1120 | |
|
1120 | 1121 | **%lsmagic**:: |
|
1121 | 1122 | |
|
1122 | 1123 | List currently available magic functions. |
|
1123 | 1124 | |
|
1124 | 1125 | **%macro**:: |
|
1125 | 1126 | |
|
1126 | 1127 | Define a set of input lines as a macro for future re-execution. |
|
1127 | 1128 | |
|
1128 | 1129 | Usage:\ |
|
1129 | 1130 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1130 | 1131 | |
|
1131 | 1132 | Options: |
|
1132 | 1133 | |
|
1133 | 1134 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1134 | 1135 | so that magics are loaded in their transformed version to valid |
|
1135 | 1136 | Python. If this option is given, the raw input as typed as the |
|
1136 | 1137 | command line is used instead. |
|
1137 | 1138 | |
|
1138 | 1139 | This will define a global variable called `name` which is a string |
|
1139 | 1140 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1140 | 1141 | above) from your input history into a single string. This variable |
|
1141 | 1142 | acts like an automatic function which re-executes those lines as if |
|
1142 | 1143 | you had typed them. You just type 'name' at the prompt and the code |
|
1143 | 1144 | executes. |
|
1144 | 1145 | |
|
1145 | 1146 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1146 | 1147 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1147 | 1148 | using the lines numbered 5,6 and 7. |
|
1148 | 1149 | |
|
1149 | 1150 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1150 | 1151 | notation, where N:M means numbers N through M-1. |
|
1151 | 1152 | |
|
1152 | 1153 | For example, if your history contains (%hist prints it): |
|
1153 | 1154 | |
|
1154 | 1155 | 44: x=1\ |
|
1155 | 1156 | 45: y=3\ |
|
1156 | 1157 | 46: z=x+y\ |
|
1157 | 1158 | 47: print x\ |
|
1158 | 1159 | 48: a=5\ |
|
1159 | 1160 | 49: print 'x',x,'y',y\ |
|
1160 | 1161 | |
|
1161 | 1162 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1162 | 1163 | called my_macro with: |
|
1163 | 1164 | |
|
1164 | 1165 | In [51]: %macro my_macro 44-47 49 |
|
1165 | 1166 | |
|
1166 | 1167 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1167 | 1168 | in one pass. |
|
1168 | 1169 | |
|
1169 | 1170 | You don't need to give the line-numbers in order, and any given line |
|
1170 | 1171 | number can appear multiple times. You can assemble macros with any |
|
1171 | 1172 | lines from your input history in any order. |
|
1172 | 1173 | |
|
1173 | 1174 | The macro is a simple object which holds its value in an attribute, |
|
1174 | 1175 | but IPython's display system checks for macros and executes them as |
|
1175 | 1176 | code instead of printing them when you type their name. |
|
1176 | 1177 | |
|
1177 | 1178 | You can view a macro's contents by explicitly printing it with: |
|
1178 | 1179 | |
|
1179 | 1180 | 'print macro_name'. |
|
1180 | 1181 | |
|
1181 | 1182 | For one-off cases which DON'T contain magic function calls in them you |
|
1182 | 1183 | can obtain similar results by explicitly executing slices from your |
|
1183 | 1184 | input history with: |
|
1184 | 1185 | |
|
1185 | 1186 | In [60]: exec In[44:48]+In[49] |
|
1186 | 1187 | |
|
1187 | 1188 | **%magic**:: |
|
1188 | 1189 | |
|
1189 | 1190 | Print information about the magic function system. |
|
1190 | 1191 | |
|
1191 | 1192 | **%mglob**:: |
|
1192 | 1193 | |
|
1193 | 1194 | This program allows specifying filenames with "mglob" mechanism. |
|
1194 | 1195 | Supported syntax in globs (wilcard matching patterns):: |
|
1195 | 1196 | |
|
1196 | 1197 | *.cpp ?ellowo* |
|
1197 | 1198 | - obvious. Differs from normal glob in that dirs are not included. |
|
1198 | 1199 | Unix users might want to write this as: "*.cpp" "?ellowo*" |
|
1199 | 1200 | rec:/usr/share=*.txt,*.doc |
|
1200 | 1201 | - get all *.txt and *.doc under /usr/share, |
|
1201 | 1202 | recursively |
|
1202 | 1203 | rec:/usr/share |
|
1203 | 1204 | - All files under /usr/share, recursively |
|
1204 | 1205 | rec:*.py |
|
1205 | 1206 | - All .py files under current working dir, recursively |
|
1206 | 1207 | foo |
|
1207 | 1208 | - File or dir foo |
|
1208 | 1209 | !*.bak readme* |
|
1209 | 1210 | - readme*, exclude files ending with .bak |
|
1210 | 1211 | !.svn/ !.hg/ !*_Data/ rec:. |
|
1211 | 1212 | - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. |
|
1212 | 1213 | Trailing / is the key, \ does not work! |
|
1213 | 1214 | dir:foo |
|
1214 | 1215 | - the directory foo if it exists (not files in foo) |
|
1215 | 1216 | dir:* |
|
1216 | 1217 | - all directories in current folder |
|
1217 | 1218 | foo.py bar.* !h* rec:*.py |
|
1218 | 1219 | - Obvious. !h* exclusion only applies for rec:*.py. |
|
1219 | 1220 | foo.py is *not* included twice. |
|
1220 | 1221 | @filelist.txt |
|
1221 | 1222 | - All files listed in 'filelist.txt' file, on separate lines. |
|
1222 | 1223 | |
|
1223 | 1224 | **%page**:: |
|
1224 | 1225 | |
|
1225 | 1226 | Pretty print the object and display it through a pager. |
|
1226 | 1227 | |
|
1227 | 1228 | %page [options] OBJECT |
|
1228 | 1229 | |
|
1229 | 1230 | If no object is given, use _ (last output). |
|
1230 | 1231 | |
|
1231 | 1232 | Options: |
|
1232 | 1233 | |
|
1233 | 1234 | -r: page str(object), don't pretty-print it. |
|
1234 | 1235 | |
|
1235 | 1236 | **%pdb**:: |
|
1236 | 1237 | |
|
1237 | 1238 | Control the automatic calling of the pdb interactive debugger. |
|
1238 | 1239 | |
|
1239 | 1240 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1240 | 1241 | argument it works as a toggle. |
|
1241 | 1242 | |
|
1242 | 1243 | When an exception is triggered, IPython can optionally call the |
|
1243 | 1244 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1244 | 1245 | this feature on and off. |
|
1245 | 1246 | |
|
1246 | 1247 | The initial state of this feature is set in your ipythonrc |
|
1247 | 1248 | configuration file (the variable is called 'pdb'). |
|
1248 | 1249 | |
|
1249 | 1250 | If you want to just activate the debugger AFTER an exception has fired, |
|
1250 | 1251 | without having to type '%pdb on' and rerunning your code, you can use |
|
1251 | 1252 | the %debug magic. |
|
1252 | 1253 | |
|
1253 | 1254 | **%pdef**:: |
|
1254 | 1255 | |
|
1255 | 1256 | Print the definition header for any callable object. |
|
1256 | 1257 | |
|
1257 | 1258 | If the object is a class, print the constructor information. |
|
1258 | 1259 | |
|
1259 | 1260 | **%pdoc**:: |
|
1260 | 1261 | |
|
1261 | 1262 | Print the docstring for an object. |
|
1262 | 1263 | |
|
1263 | 1264 | If the given object is a class, it will print both the class and the |
|
1264 | 1265 | constructor docstrings. |
|
1265 | 1266 | |
|
1266 | 1267 | **%pfile**:: |
|
1267 | 1268 | |
|
1268 | 1269 | Print (or run through pager) the file where an object is defined. |
|
1269 | 1270 | |
|
1270 | 1271 | The file opens at the line where the object definition begins. IPython |
|
1271 | 1272 | will honor the environment variable PAGER if set, and otherwise will |
|
1272 | 1273 | do its best to print the file in a convenient form. |
|
1273 | 1274 | |
|
1274 | 1275 | If the given argument is not an object currently defined, IPython will |
|
1275 | 1276 | try to interpret it as a filename (automatically adding a .py extension |
|
1276 | 1277 | if needed). You can thus use %pfile as a syntax highlighting code |
|
1277 | 1278 | viewer. |
|
1278 | 1279 | |
|
1279 | 1280 | **%pinfo**:: |
|
1280 | 1281 | |
|
1281 | 1282 | Provide detailed information about an object. |
|
1282 | 1283 | |
|
1283 | 1284 | '%pinfo object' is just a synonym for object? or ?object. |
|
1284 | 1285 | |
|
1285 | 1286 | **%popd**:: |
|
1286 | 1287 | |
|
1287 | 1288 | Change to directory popped off the top of the stack. |
|
1288 | 1289 | |
|
1289 | 1290 | **%profile**:: |
|
1290 | 1291 | |
|
1291 | 1292 | Print your currently active IPyhton profile. |
|
1292 | 1293 | |
|
1293 | 1294 | **%prun**:: |
|
1294 | 1295 | |
|
1295 | 1296 | Run a statement through the python code profiler. |
|
1296 | 1297 | |
|
1297 | 1298 | Usage:\ |
|
1298 | 1299 | %prun [options] statement |
|
1299 | 1300 | |
|
1300 | 1301 | The given statement (which doesn't require quote marks) is run via the |
|
1301 | 1302 | python profiler in a manner similar to the profile.run() function. |
|
1302 | 1303 | Namespaces are internally managed to work correctly; profile.run |
|
1303 | 1304 | cannot be used in IPython because it makes certain assumptions about |
|
1304 | 1305 | namespaces which do not hold under IPython. |
|
1305 | 1306 | |
|
1306 | 1307 | Options: |
|
1307 | 1308 | |
|
1308 | 1309 | -l <limit>: you can place restrictions on what or how much of the |
|
1309 | 1310 | profile gets printed. The limit value can be: |
|
1310 | 1311 | |
|
1311 | 1312 | * A string: only information for function names containing this string |
|
1312 | 1313 | is printed. |
|
1313 | 1314 | |
|
1314 | 1315 | * An integer: only these many lines are printed. |
|
1315 | 1316 | |
|
1316 | 1317 | * A float (between 0 and 1): this fraction of the report is printed |
|
1317 | 1318 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1318 | 1319 | |
|
1319 | 1320 | You can combine several limits with repeated use of the option. For |
|
1320 | 1321 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1321 | 1322 | information about class constructors. |
|
1322 | 1323 | |
|
1323 | 1324 | -r: return the pstats.Stats object generated by the profiling. This |
|
1324 | 1325 | object has all the information about the profile in it, and you can |
|
1325 | 1326 | later use it for further analysis or in other functions. |
|
1326 | 1327 | |
|
1327 | 1328 | -s <key>: sort profile by given key. You can provide more than one key |
|
1328 | 1329 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1329 | 1330 | default sorting key is 'time'. |
|
1330 | 1331 | |
|
1331 | 1332 | The following is copied verbatim from the profile documentation |
|
1332 | 1333 | referenced below: |
|
1333 | 1334 | |
|
1334 | 1335 | When more than one key is provided, additional keys are used as |
|
1335 | 1336 | secondary criteria when the there is equality in all keys selected |
|
1336 | 1337 | before them. |
|
1337 | 1338 | |
|
1338 | 1339 | Abbreviations can be used for any key names, as long as the |
|
1339 | 1340 | abbreviation is unambiguous. The following are the keys currently |
|
1340 | 1341 | defined: |
|
1341 | 1342 | |
|
1342 | 1343 | Valid Arg Meaning\ |
|
1343 | 1344 | "calls" call count\ |
|
1344 | 1345 | "cumulative" cumulative time\ |
|
1345 | 1346 | "file" file name\ |
|
1346 | 1347 | "module" file name\ |
|
1347 | 1348 | "pcalls" primitive call count\ |
|
1348 | 1349 | "line" line number\ |
|
1349 | 1350 | "name" function name\ |
|
1350 | 1351 | "nfl" name/file/line\ |
|
1351 | 1352 | "stdname" standard name\ |
|
1352 | 1353 | "time" internal time |
|
1353 | 1354 | |
|
1354 | 1355 | Note that all sorts on statistics are in descending order (placing |
|
1355 | 1356 | most time consuming items first), where as name, file, and line number |
|
1356 | 1357 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1357 | 1358 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1358 | 1359 | sort of the name as printed, which means that the embedded line |
|
1359 | 1360 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1360 | 1361 | would (if the file names were the same) appear in the string order |
|
1361 | 1362 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1362 | 1363 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1363 | 1364 | sort_stats("name", "file", "line"). |
|
1364 | 1365 | |
|
1365 | 1366 | -T <filename>: save profile results as shown on screen to a text |
|
1366 | 1367 | file. The profile is still shown on screen. |
|
1367 | 1368 | |
|
1368 | 1369 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1369 | 1370 | filename. This data is in a format understod by the pstats module, and |
|
1370 | 1371 | is generated by a call to the dump_stats() method of profile |
|
1371 | 1372 | objects. The profile is still shown on screen. |
|
1372 | 1373 | |
|
1373 | 1374 | If you want to run complete programs under the profiler's control, use |
|
1374 | 1375 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1375 | 1376 | contains profiler specific options as described here. |
|
1376 | 1377 | |
|
1377 | 1378 | You can read the complete documentation for the profile module with:\ |
|
1378 | 1379 | In [1]: import profile; profile.help() |
|
1379 | 1380 | |
|
1380 | 1381 | **%psearch**:: |
|
1381 | 1382 | |
|
1382 | 1383 | Search for object in namespaces by wildcard. |
|
1383 | 1384 | |
|
1384 | 1385 | %psearch [options] PATTERN [OBJECT TYPE] |
|
1385 | 1386 | |
|
1386 | 1387 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
1387 | 1388 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
1388 | 1389 | rest of the command line must be unchanged (options come first), so |
|
1389 | 1390 | for example the following forms are equivalent |
|
1390 | 1391 | |
|
1391 | 1392 | %psearch -i a* function |
|
1392 | 1393 | -i a* function? |
|
1393 | 1394 | ?-i a* function |
|
1394 | 1395 | |
|
1395 | 1396 | Arguments: |
|
1396 | 1397 | |
|
1397 | 1398 | PATTERN |
|
1398 | 1399 | |
|
1399 | 1400 | where PATTERN is a string containing * as a wildcard similar to its |
|
1400 | 1401 | use in a shell. The pattern is matched in all namespaces on the |
|
1401 | 1402 | search path. By default objects starting with a single _ are not |
|
1402 | 1403 | matched, many IPython generated objects have a single |
|
1403 | 1404 | underscore. The default is case insensitive matching. Matching is |
|
1404 | 1405 | also done on the attributes of objects and not only on the objects |
|
1405 | 1406 | in a module. |
|
1406 | 1407 | |
|
1407 | 1408 | [OBJECT TYPE] |
|
1408 | 1409 | |
|
1409 | 1410 | Is the name of a python type from the types module. The name is |
|
1410 | 1411 | given in lowercase without the ending type, ex. StringType is |
|
1411 | 1412 | written string. By adding a type here only objects matching the |
|
1412 | 1413 | given type are matched. Using all here makes the pattern match all |
|
1413 | 1414 | types (this is the default). |
|
1414 | 1415 | |
|
1415 | 1416 | Options: |
|
1416 | 1417 | |
|
1417 | 1418 | -a: makes the pattern match even objects whose names start with a |
|
1418 | 1419 | single underscore. These names are normally ommitted from the |
|
1419 | 1420 | search. |
|
1420 | 1421 | |
|
1421 | 1422 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
1422 | 1423 | these options is given, the default is read from your ipythonrc |
|
1423 | 1424 | file. The option name which sets this value is |
|
1424 | 1425 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
1425 | 1426 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
1426 | 1427 | search. |
|
1427 | 1428 | |
|
1428 | 1429 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
1429 | 1430 | specifiy can be searched in any of the following namespaces: |
|
1430 | 1431 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
1431 | 1432 | 'builtin' and 'user' are the search defaults. Note that you should |
|
1432 | 1433 | not use quotes when specifying namespaces. |
|
1433 | 1434 | |
|
1434 | 1435 | 'Builtin' contains the python module builtin, 'user' contains all |
|
1435 | 1436 | user data, 'alias' only contain the shell aliases and no python |
|
1436 | 1437 | objects, 'internal' contains objects used by IPython. The |
|
1437 | 1438 | 'user_global' namespace is only used by embedded IPython instances, |
|
1438 | 1439 | and it contains module-level globals. You can add namespaces to the |
|
1439 | 1440 | search with -s or exclude them with -e (these options can be given |
|
1440 | 1441 | more than once). |
|
1441 | 1442 | |
|
1442 | 1443 | Examples: |
|
1443 | 1444 | |
|
1444 | 1445 | %psearch a* -> objects beginning with an a |
|
1445 | 1446 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
1446 | 1447 | %psearch a* function -> all functions beginning with an a |
|
1447 | 1448 | %psearch re.e* -> objects beginning with an e in module re |
|
1448 | 1449 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
1449 | 1450 | %psearch r*.* string -> all strings in modules beginning with r |
|
1450 | 1451 | |
|
1451 | 1452 | Case sensitve search: |
|
1452 | 1453 | |
|
1453 | 1454 | %psearch -c a* list all object beginning with lower case a |
|
1454 | 1455 | |
|
1455 | 1456 | Show objects beginning with a single _: |
|
1456 | 1457 | |
|
1457 | 1458 | %psearch -a _* list objects beginning with a single underscore |
|
1458 | 1459 | |
|
1459 | 1460 | **%psource**:: |
|
1460 | 1461 | |
|
1461 | 1462 | Print (or run through pager) the source code for an object. |
|
1462 | 1463 | |
|
1463 | 1464 | **%pushd**:: |
|
1464 | 1465 | |
|
1465 | 1466 | Place the current dir on stack and change directory. |
|
1466 | 1467 | |
|
1467 | 1468 | Usage:\ |
|
1468 | 1469 | %pushd ['dirname'] |
|
1469 | 1470 | |
|
1470 | 1471 | **%pwd**:: |
|
1471 | 1472 | |
|
1472 | 1473 | Return the current working directory path. |
|
1473 | 1474 | |
|
1474 | 1475 | **%pycat**:: |
|
1475 | 1476 | |
|
1476 | 1477 | Show a syntax-highlighted file through a pager. |
|
1477 | 1478 | |
|
1478 | 1479 | This magic is similar to the cat utility, but it will assume the file |
|
1479 | 1480 | to be Python source and will show it with syntax highlighting. |
|
1480 | 1481 | |
|
1481 | 1482 | **%quickref**:: |
|
1482 | 1483 | |
|
1483 | 1484 | Show a quick reference sheet |
|
1484 | 1485 | |
|
1485 | 1486 | **%quit**:: |
|
1486 | 1487 | |
|
1487 | 1488 | Exit IPython, confirming if configured to do so (like %exit) |
|
1488 | 1489 | |
|
1489 | 1490 | **%r**:: |
|
1490 | 1491 | |
|
1491 | 1492 | Repeat previous input. |
|
1492 | 1493 | |
|
1493 | 1494 | Note: Consider using the more powerfull %rep instead! |
|
1494 | 1495 | |
|
1495 | 1496 | If given an argument, repeats the previous command which starts with |
|
1496 | 1497 | the same string, otherwise it just repeats the previous input. |
|
1497 | 1498 | |
|
1498 | 1499 | Shell escaped commands (with ! as first character) are not recognized |
|
1499 | 1500 | by this system, only pure python code and magic commands. |
|
1500 | 1501 | |
|
1501 | 1502 | **%rehashdir**:: |
|
1502 | 1503 | |
|
1503 | 1504 | Add executables in all specified dirs to alias table |
|
1504 | 1505 | |
|
1505 | 1506 | Usage: |
|
1506 | 1507 | |
|
1507 | 1508 | %rehashdir c:/bin;c:/tools |
|
1508 | 1509 | - Add all executables under c:/bin and c:/tools to alias table, in |
|
1509 | 1510 | order to make them directly executable from any directory. |
|
1510 | 1511 | |
|
1511 | 1512 | Without arguments, add all executables in current directory. |
|
1512 | 1513 | |
|
1513 | 1514 | **%rehashx**:: |
|
1514 | 1515 | |
|
1515 | 1516 | Update the alias table with all executable files in $PATH. |
|
1516 | 1517 | |
|
1517 | 1518 | This version explicitly checks that every entry in $PATH is a file |
|
1518 | 1519 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
1519 | 1520 | |
|
1520 | 1521 | Under Windows, it checks executability as a match agains a |
|
1521 | 1522 | '|'-separated string of extensions, stored in the IPython config |
|
1522 | 1523 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
1523 | 1524 | |
|
1524 | 1525 | This function also resets the root module cache of module completer, |
|
1525 | 1526 | used on slow filesystems. |
|
1526 | 1527 | |
|
1527 | 1528 | **%rep**:: |
|
1528 | 1529 | |
|
1529 | 1530 | Repeat a command, or get command to input line for editing |
|
1530 | 1531 | |
|
1531 | 1532 | - %rep (no arguments): |
|
1532 | 1533 | |
|
1533 | 1534 | Place a string version of last computation result (stored in the special '_' |
|
1534 | 1535 | variable) to the next input prompt. Allows you to create elaborate command |
|
1535 | 1536 | lines without using copy-paste:: |
|
1536 | 1537 | |
|
1537 | 1538 | $ l = ["hei", "vaan"] |
|
1538 | 1539 | $ "".join(l) |
|
1539 | 1540 | ==> heivaan |
|
1540 | 1541 | $ %rep |
|
1541 | 1542 | $ heivaan_ <== cursor blinking |
|
1542 | 1543 | |
|
1543 | 1544 | %rep 45 |
|
1544 | 1545 | |
|
1545 | 1546 | Place history line 45 to next input prompt. Use %hist to find out the |
|
1546 | 1547 | number. |
|
1547 | 1548 | |
|
1548 | 1549 | %rep 1-4 6-7 3 |
|
1549 | 1550 | |
|
1550 | 1551 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
1551 | 1552 | in %macro and %save. |
|
1552 | 1553 | |
|
1553 | 1554 | %rep foo |
|
1554 | 1555 | |
|
1555 | 1556 | Place the most recent line that has the substring "foo" to next input. |
|
1556 | 1557 | (e.g. 'svn ci -m foobar'). |
|
1557 | 1558 | |
|
1558 | 1559 | **%reset**:: |
|
1559 | 1560 | |
|
1560 | 1561 | Resets the namespace by removing all names defined by the user. |
|
1561 | 1562 | |
|
1562 | 1563 | Input/Output history are left around in case you need them. |
|
1563 | 1564 | |
|
1564 | 1565 | **%run**:: |
|
1565 | 1566 | |
|
1566 | 1567 | Run the named file inside IPython as a program. |
|
1567 | 1568 | |
|
1568 | 1569 | Usage:\ |
|
1569 | 1570 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1570 | 1571 | |
|
1571 | 1572 | Parameters after the filename are passed as command-line arguments to |
|
1572 | 1573 | the program (put in sys.argv). Then, control returns to IPython's |
|
1573 | 1574 | prompt. |
|
1574 | 1575 | |
|
1575 | 1576 | This is similar to running at a system prompt:\ |
|
1576 | 1577 | $ python file args\ |
|
1577 | 1578 | but with the advantage of giving you IPython's tracebacks, and of |
|
1578 | 1579 | loading all variables into your interactive namespace for further use |
|
1579 | 1580 | (unless -p is used, see below). |
|
1580 | 1581 | |
|
1581 | 1582 | The file is executed in a namespace initially consisting only of |
|
1582 | 1583 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1583 | 1584 | sees its environment as if it were being run as a stand-alone program |
|
1584 | 1585 | (except for sharing global objects such as previously imported |
|
1585 | 1586 | modules). But after execution, the IPython interactive namespace gets |
|
1586 | 1587 | updated with all variables defined in the program (except for __name__ |
|
1587 | 1588 | and sys.argv). This allows for very convenient loading of code for |
|
1588 | 1589 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1589 | 1590 | |
|
1590 | 1591 | Options: |
|
1591 | 1592 | |
|
1592 | 1593 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1593 | 1594 | without extension (as python does under import). This allows running |
|
1594 | 1595 | scripts and reloading the definitions in them without calling code |
|
1595 | 1596 | protected by an ' if __name__ == "__main__" ' clause. |
|
1596 | 1597 | |
|
1597 | 1598 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1598 | 1599 | is useful if you are experimenting with code written in a text editor |
|
1599 | 1600 | which depends on variables defined interactively. |
|
1600 | 1601 | |
|
1601 | 1602 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1602 | 1603 | being run. This is particularly useful if IPython is being used to |
|
1603 | 1604 | run unittests, which always exit with a sys.exit() call. In such |
|
1604 | 1605 | cases you are interested in the output of the test results, not in |
|
1605 | 1606 | seeing a traceback of the unittest module. |
|
1606 | 1607 | |
|
1607 | 1608 | -t: print timing information at the end of the run. IPython will give |
|
1608 | 1609 | you an estimated CPU time consumption for your script, which under |
|
1609 | 1610 | Unix uses the resource module to avoid the wraparound problems of |
|
1610 | 1611 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1611 | 1612 | is also given (for Windows platforms this is reported as 0.0). |
|
1612 | 1613 | |
|
1613 | 1614 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1614 | 1615 | must be an integer indicating how many times you want the script to |
|
1615 | 1616 | run. The final timing report will include total and per run results. |
|
1616 | 1617 | |
|
1617 | 1618 | For example (testing the script uniq_stable.py): |
|
1618 | 1619 | |
|
1619 | 1620 | In [1]: run -t uniq_stable |
|
1620 | 1621 | |
|
1621 | 1622 | IPython CPU timings (estimated):\ |
|
1622 | 1623 | User : 0.19597 s.\ |
|
1623 | 1624 | System: 0.0 s.\ |
|
1624 | 1625 | |
|
1625 | 1626 | In [2]: run -t -N5 uniq_stable |
|
1626 | 1627 | |
|
1627 | 1628 | IPython CPU timings (estimated):\ |
|
1628 | 1629 | Total runs performed: 5\ |
|
1629 | 1630 | Times : Total Per run\ |
|
1630 | 1631 | User : 0.910862 s, 0.1821724 s.\ |
|
1631 | 1632 | System: 0.0 s, 0.0 s. |
|
1632 | 1633 | |
|
1633 | 1634 | -d: run your program under the control of pdb, the Python debugger. |
|
1634 | 1635 | This allows you to execute your program step by step, watch variables, |
|
1635 | 1636 | etc. Internally, what IPython does is similar to calling: |
|
1636 | 1637 | |
|
1637 | 1638 | pdb.run('execfile("YOURFILENAME")') |
|
1638 | 1639 | |
|
1639 | 1640 | with a breakpoint set on line 1 of your file. You can change the line |
|
1640 | 1641 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1641 | 1642 | (where N must be an integer). For example: |
|
1642 | 1643 | |
|
1643 | 1644 | %run -d -b40 myscript |
|
1644 | 1645 | |
|
1645 | 1646 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1646 | 1647 | the first breakpoint must be set on a line which actually does |
|
1647 | 1648 | something (not a comment or docstring) for it to stop execution. |
|
1648 | 1649 | |
|
1649 | 1650 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1650 | 1651 | first enter 'c' (without qoutes) to start execution up to the first |
|
1651 | 1652 | breakpoint. |
|
1652 | 1653 | |
|
1653 | 1654 | Entering 'help' gives information about the use of the debugger. You |
|
1654 | 1655 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1655 | 1656 | at a prompt. |
|
1656 | 1657 | |
|
1657 | 1658 | -p: run program under the control of the Python profiler module (which |
|
1658 | 1659 | prints a detailed report of execution times, function calls, etc). |
|
1659 | 1660 | |
|
1660 | 1661 | You can pass other options after -p which affect the behavior of the |
|
1661 | 1662 | profiler itself. See the docs for %prun for details. |
|
1662 | 1663 | |
|
1663 | 1664 | In this mode, the program's variables do NOT propagate back to the |
|
1664 | 1665 | IPython interactive namespace (because they remain in the namespace |
|
1665 | 1666 | where the profiler executes them). |
|
1666 | 1667 | |
|
1667 | 1668 | Internally this triggers a call to %prun, see its documentation for |
|
1668 | 1669 | details on the options available specifically for profiling. |
|
1669 | 1670 | |
|
1670 | 1671 | There is one special usage for which the text above doesn't apply: |
|
1671 | 1672 | if the filename ends with .ipy, the file is run as ipython script, |
|
1672 | 1673 | just as if the commands were written on IPython prompt. |
|
1673 | 1674 | |
|
1674 | 1675 | **%runlog**:: |
|
1675 | 1676 | |
|
1676 | 1677 | Run files as logs. |
|
1677 | 1678 | |
|
1678 | 1679 | Usage:\ |
|
1679 | 1680 | %runlog file1 file2 ... |
|
1680 | 1681 | |
|
1681 | 1682 | Run the named files (treating them as log files) in sequence inside |
|
1682 | 1683 | the interpreter, and return to the prompt. This is much slower than |
|
1683 | 1684 | %run because each line is executed in a try/except block, but it |
|
1684 | 1685 | allows running files with syntax errors in them. |
|
1685 | 1686 | |
|
1686 | 1687 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1687 | 1688 | you can typically use %run even for logs. This shorthand allows you to |
|
1688 | 1689 | force any file to be treated as a log file. |
|
1689 | 1690 | |
|
1690 | 1691 | **%save**:: |
|
1691 | 1692 | |
|
1692 | 1693 | Save a set of lines to a given filename. |
|
1693 | 1694 | |
|
1694 | 1695 | Usage:\ |
|
1695 | 1696 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1696 | 1697 | |
|
1697 | 1698 | Options: |
|
1698 | 1699 | |
|
1699 | 1700 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1700 | 1701 | so that magics are loaded in their transformed version to valid |
|
1701 | 1702 | Python. If this option is given, the raw input as typed as the |
|
1702 | 1703 | command line is used instead. |
|
1703 | 1704 | |
|
1704 | 1705 | This function uses the same syntax as %macro for line extraction, but |
|
1705 | 1706 | instead of creating a macro it saves the resulting string to the |
|
1706 | 1707 | filename you specify. |
|
1707 | 1708 | |
|
1708 | 1709 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1709 | 1710 | it asks for confirmation before overwriting existing files. |
|
1710 | 1711 | |
|
1711 | 1712 | **%sc**:: |
|
1712 | 1713 | |
|
1713 | 1714 | Shell capture - execute a shell command and capture its output. |
|
1714 | 1715 | |
|
1715 | 1716 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
1716 | 1717 | |
|
1717 | 1718 | You should use the form 'var = !command' instead. Example: |
|
1718 | 1719 | |
|
1719 | 1720 | "%sc -l myfiles = ls ~" should now be written as |
|
1720 | 1721 | |
|
1721 | 1722 | "myfiles = !ls ~" |
|
1722 | 1723 | |
|
1723 | 1724 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
1724 | 1725 | below. |
|
1725 | 1726 | |
|
1726 | 1727 | -- |
|
1727 | 1728 | %sc [options] varname=command |
|
1728 | 1729 | |
|
1729 | 1730 | IPython will run the given command using commands.getoutput(), and |
|
1730 | 1731 | will then update the user's interactive namespace with a variable |
|
1731 | 1732 | called varname, containing the value of the call. Your command can |
|
1732 | 1733 | contain shell wildcards, pipes, etc. |
|
1733 | 1734 | |
|
1734 | 1735 | The '=' sign in the syntax is mandatory, and the variable name you |
|
1735 | 1736 | supply must follow Python's standard conventions for valid names. |
|
1736 | 1737 | |
|
1737 | 1738 | (A special format without variable name exists for internal use) |
|
1738 | 1739 | |
|
1739 | 1740 | Options: |
|
1740 | 1741 | |
|
1741 | 1742 | -l: list output. Split the output on newlines into a list before |
|
1742 | 1743 | assigning it to the given variable. By default the output is stored |
|
1743 | 1744 | as a single string. |
|
1744 | 1745 | |
|
1745 | 1746 | -v: verbose. Print the contents of the variable. |
|
1746 | 1747 | |
|
1747 | 1748 | In most cases you should not need to split as a list, because the |
|
1748 | 1749 | returned value is a special type of string which can automatically |
|
1749 | 1750 | provide its contents either as a list (split on newlines) or as a |
|
1750 | 1751 | space-separated string. These are convenient, respectively, either |
|
1751 | 1752 | for sequential processing or to be passed to a shell command. |
|
1752 | 1753 | |
|
1753 | 1754 | For example: |
|
1754 | 1755 | |
|
1755 | 1756 | # Capture into variable a |
|
1756 | 1757 | In [9]: sc a=ls *py |
|
1757 | 1758 | |
|
1758 | 1759 | # a is a string with embedded newlines |
|
1759 | 1760 | In [10]: a |
|
1760 | 1761 | Out[10]: 'setup.py win32_manual_post_install.py' |
|
1761 | 1762 | |
|
1762 | 1763 | # which can be seen as a list: |
|
1763 | 1764 | In [11]: a.l |
|
1764 | 1765 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
1765 | 1766 | |
|
1766 | 1767 | # or as a whitespace-separated string: |
|
1767 | 1768 | In [12]: a.s |
|
1768 | 1769 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
1769 | 1770 | |
|
1770 | 1771 | # a.s is useful to pass as a single command line: |
|
1771 | 1772 | In [13]: !wc -l $a.s |
|
1772 | 1773 | 146 setup.py |
|
1773 | 1774 | 130 win32_manual_post_install.py |
|
1774 | 1775 | 276 total |
|
1775 | 1776 | |
|
1776 | 1777 | # while the list form is useful to loop over: |
|
1777 | 1778 | In [14]: for f in a.l: |
|
1778 | 1779 | ....: !wc -l $f |
|
1779 | 1780 | ....: |
|
1780 | 1781 | 146 setup.py |
|
1781 | 1782 | 130 win32_manual_post_install.py |
|
1782 | 1783 | |
|
1783 | 1784 | Similiarly, the lists returned by the -l option are also special, in |
|
1784 | 1785 | the sense that you can equally invoke the .s attribute on them to |
|
1785 | 1786 | automatically get a whitespace-separated string from their contents: |
|
1786 | 1787 | |
|
1787 | 1788 | In [1]: sc -l b=ls *py |
|
1788 | 1789 | |
|
1789 | 1790 | In [2]: b |
|
1790 | 1791 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
1791 | 1792 | |
|
1792 | 1793 | In [3]: b.s |
|
1793 | 1794 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
1794 | 1795 | |
|
1795 | 1796 | In summary, both the lists and strings used for ouptut capture have |
|
1796 | 1797 | the following special attributes: |
|
1797 | 1798 | |
|
1798 | 1799 | .l (or .list) : value as list. |
|
1799 | 1800 | .n (or .nlstr): value as newline-separated string. |
|
1800 | 1801 | .s (or .spstr): value as space-separated string. |
|
1801 | 1802 | |
|
1802 | 1803 | **%store**:: |
|
1803 | 1804 | |
|
1804 | 1805 | Lightweight persistence for python variables. |
|
1805 | 1806 | |
|
1806 | 1807 | Example: |
|
1807 | 1808 | |
|
1808 | 1809 | ville@badger[~]|1> A = ['hello',10,'world']\ |
|
1809 | 1810 | ville@badger[~]|2> %store A\ |
|
1810 | 1811 | ville@badger[~]|3> Exit |
|
1811 | 1812 | |
|
1812 | 1813 | (IPython session is closed and started again...) |
|
1813 | 1814 | |
|
1814 | 1815 | ville@badger:~$ ipython -p pysh\ |
|
1815 | 1816 | ville@badger[~]|1> print A |
|
1816 | 1817 | |
|
1817 | 1818 | ['hello', 10, 'world'] |
|
1818 | 1819 | |
|
1819 | 1820 | Usage: |
|
1820 | 1821 | |
|
1821 | 1822 | %store - Show list of all variables and their current values\ |
|
1822 | 1823 | %store <var> - Store the *current* value of the variable to disk\ |
|
1823 | 1824 | %store -d <var> - Remove the variable and its value from storage\ |
|
1824 | 1825 | %store -z - Remove all variables from storage\ |
|
1825 | 1826 | %store -r - Refresh all variables from store (delete current vals)\ |
|
1826 | 1827 | %store foo >a.txt - Store value of foo to new file a.txt\ |
|
1827 | 1828 | %store foo >>a.txt - Append value of foo to file a.txt\ |
|
1828 | 1829 | |
|
1829 | 1830 | It should be noted that if you change the value of a variable, you |
|
1830 | 1831 | need to %store it again if you want to persist the new value. |
|
1831 | 1832 | |
|
1832 | 1833 | Note also that the variables will need to be pickleable; most basic |
|
1833 | 1834 | python types can be safely %stored. |
|
1834 | 1835 | |
|
1835 | 1836 | Also aliases can be %store'd across sessions. |
|
1836 | 1837 | |
|
1837 | 1838 | **%sx**:: |
|
1838 | 1839 | |
|
1839 | 1840 | Shell execute - run a shell command and capture its output. |
|
1840 | 1841 | |
|
1841 | 1842 | %sx command |
|
1842 | 1843 | |
|
1843 | 1844 | IPython will run the given command using commands.getoutput(), and |
|
1844 | 1845 | return the result formatted as a list (split on '\n'). Since the |
|
1845 | 1846 | output is _returned_, it will be stored in ipython's regular output |
|
1846 | 1847 | cache Out[N] and in the '_N' automatic variables. |
|
1847 | 1848 | |
|
1848 | 1849 | Notes: |
|
1849 | 1850 | |
|
1850 | 1851 | 1) If an input line begins with '!!', then %sx is automatically |
|
1851 | 1852 | invoked. That is, while: |
|
1852 | 1853 | !ls |
|
1853 | 1854 | causes ipython to simply issue system('ls'), typing |
|
1854 | 1855 | !!ls |
|
1855 | 1856 | is a shorthand equivalent to: |
|
1856 | 1857 | %sx ls |
|
1857 | 1858 | |
|
1858 | 1859 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
1859 | 1860 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
1860 | 1861 | to process line-oriented shell output via further python commands. |
|
1861 | 1862 | %sc is meant to provide much finer control, but requires more |
|
1862 | 1863 | typing. |
|
1863 | 1864 | |
|
1864 | 1865 | 3) Just like %sc -l, this is a list with special attributes: |
|
1865 | 1866 | |
|
1866 | 1867 | .l (or .list) : value as list. |
|
1867 | 1868 | .n (or .nlstr): value as newline-separated string. |
|
1868 | 1869 | .s (or .spstr): value as whitespace-separated string. |
|
1869 | 1870 | |
|
1870 | 1871 | This is very useful when trying to use such lists as arguments to |
|
1871 | 1872 | system commands. |
|
1872 | 1873 | |
|
1873 | 1874 | **%system_verbose**:: |
|
1874 | 1875 | |
|
1875 | 1876 | Set verbose printing of system calls. |
|
1876 | 1877 | |
|
1877 | 1878 | If called without an argument, act as a toggle |
|
1878 | 1879 | |
|
1879 | 1880 | **%time**:: |
|
1880 | 1881 | |
|
1881 | 1882 | Time execution of a Python statement or expression. |
|
1882 | 1883 | |
|
1883 | 1884 | The CPU and wall clock times are printed, and the value of the |
|
1884 | 1885 | expression (if any) is returned. Note that under Win32, system time |
|
1885 | 1886 | is always reported as 0, since it can not be measured. |
|
1886 | 1887 | |
|
1887 | 1888 | This function provides very basic timing functionality. In Python |
|
1888 | 1889 | 2.3, the timeit module offers more control and sophistication, so this |
|
1889 | 1890 | could be rewritten to use it (patches welcome). |
|
1890 | 1891 | |
|
1891 | 1892 | Some examples: |
|
1892 | 1893 | |
|
1893 | 1894 | In [1]: time 2**128 |
|
1894 | 1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1895 | 1896 | Wall time: 0.00 |
|
1896 | 1897 | Out[1]: 340282366920938463463374607431768211456L |
|
1897 | 1898 | |
|
1898 | 1899 | In [2]: n = 1000000 |
|
1899 | 1900 | |
|
1900 | 1901 | In [3]: time sum(range(n)) |
|
1901 | 1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1902 | 1903 | Wall time: 1.37 |
|
1903 | 1904 | Out[3]: 499999500000L |
|
1904 | 1905 | |
|
1905 | 1906 | In [4]: time print 'hello world' |
|
1906 | 1907 | hello world |
|
1907 | 1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1908 | 1909 | Wall time: 0.00 |
|
1909 | 1910 | |
|
1910 | 1911 | Note that the time needed by Python to compile the given expression |
|
1911 | 1912 | will be reported if it is more than 0.1s. In this example, the |
|
1912 | 1913 | actual exponentiation is done by Python at compilation time, so while |
|
1913 | 1914 | the expression can take a noticeable amount of time to compute, that |
|
1914 | 1915 | time is purely due to the compilation: |
|
1915 | 1916 | |
|
1916 | 1917 | In [5]: time 3**9999; |
|
1917 | 1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1918 | 1919 | Wall time: 0.00 s |
|
1919 | 1920 | |
|
1920 | 1921 | In [6]: time 3**999999; |
|
1921 | 1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1922 | 1923 | Wall time: 0.00 s |
|
1923 | 1924 | Compiler : 0.78 s |
|
1924 | 1925 | |
|
1925 | 1926 | **%timeit**:: |
|
1926 | 1927 | |
|
1927 | 1928 | Time execution of a Python statement or expression |
|
1928 | 1929 | |
|
1929 | 1930 | Usage:\ |
|
1930 | 1931 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1931 | 1932 | |
|
1932 | 1933 | Time execution of a Python statement or expression using the timeit |
|
1933 | 1934 | module. |
|
1934 | 1935 | |
|
1935 | 1936 | Options: |
|
1936 | 1937 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1937 | 1938 | is not given, a fitting value is chosen. |
|
1938 | 1939 | |
|
1939 | 1940 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1940 | 1941 | Default: 3 |
|
1941 | 1942 | |
|
1942 | 1943 | -t: use time.time to measure the time, which is the default on Unix. |
|
1943 | 1944 | This function measures wall time. |
|
1944 | 1945 | |
|
1945 | 1946 | -c: use time.clock to measure the time, which is the default on |
|
1946 | 1947 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1947 | 1948 | instead and returns the CPU user time. |
|
1948 | 1949 | |
|
1949 | 1950 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1950 | 1951 | Default: 3 |
|
1951 | 1952 | |
|
1952 | 1953 | |
|
1953 | 1954 | Examples:\ |
|
1954 | 1955 | In [1]: %timeit pass |
|
1955 | 1956 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1956 | 1957 | |
|
1957 | 1958 | In [2]: u = None |
|
1958 | 1959 | |
|
1959 | 1960 | In [3]: %timeit u is None |
|
1960 | 1961 | 10000000 loops, best of 3: 184 ns per loop |
|
1961 | 1962 | |
|
1962 | 1963 | In [4]: %timeit -r 4 u == None |
|
1963 | 1964 | 1000000 loops, best of 4: 242 ns per loop |
|
1964 | 1965 | |
|
1965 | 1966 | In [5]: import time |
|
1966 | 1967 | |
|
1967 | 1968 | In [6]: %timeit -n1 time.sleep(2) |
|
1968 | 1969 | 1 loops, best of 3: 2 s per loop |
|
1969 | 1970 | |
|
1970 | 1971 | |
|
1971 | 1972 | The times reported by %timeit will be slightly higher than those |
|
1972 | 1973 | reported by the timeit.py script when variables are accessed. This is |
|
1973 | 1974 | due to the fact that %timeit executes the statement in the namespace |
|
1974 | 1975 | of the shell, compared with timeit.py, which uses a single setup |
|
1975 | 1976 | statement to import function or create variables. Generally, the bias |
|
1976 | 1977 | does not matter as long as results from timeit.py are not mixed with |
|
1977 | 1978 | those from %timeit. |
|
1978 | 1979 | |
|
1979 | 1980 | **%unalias**:: |
|
1980 | 1981 | |
|
1981 | 1982 | Remove an alias |
|
1982 | 1983 | |
|
1983 | 1984 | **%upgrade**:: |
|
1984 | 1985 | |
|
1985 | 1986 | Upgrade your IPython installation |
|
1986 | 1987 | |
|
1987 | 1988 | This will copy the config files that don't yet exist in your |
|
1988 | 1989 | ipython dir from the system config dir. Use this after upgrading |
|
1989 | 1990 | IPython if you don't wish to delete your .ipython dir. |
|
1990 | 1991 | |
|
1991 | 1992 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
1992 | 1993 | new users) |
|
1993 | 1994 | |
|
1994 | 1995 | **%which**:: |
|
1995 | 1996 | |
|
1996 | 1997 | %which <cmd> => search PATH for files matching cmd. Also scans aliases. |
|
1997 | 1998 | |
|
1998 | 1999 | Traverses PATH and prints all files (not just executables!) that match the |
|
1999 | 2000 | pattern on command line. Probably more useful in finding stuff |
|
2000 | 2001 | interactively than 'which', which only prints the first matching item. |
|
2001 | 2002 | |
|
2002 | 2003 | Also discovers and expands aliases, so you'll see what will be executed |
|
2003 | 2004 | when you call an alias. |
|
2004 | 2005 | |
|
2005 | 2006 | Example: |
|
2006 | 2007 | |
|
2007 | 2008 | [~]|62> %which d |
|
2008 | 2009 | d -> ls -F --color=auto |
|
2009 | 2010 | == c:\cygwin\bin\ls.exe |
|
2010 | 2011 | c:\cygwin\bin\d.exe |
|
2011 | 2012 | |
|
2012 | 2013 | [~]|64> %which diff* |
|
2013 | 2014 | diff3 -> diff3 |
|
2014 | 2015 | == c:\cygwin\bin\diff3.exe |
|
2015 | 2016 | diff -> diff |
|
2016 | 2017 | == c:\cygwin\bin\diff.exe |
|
2017 | 2018 | c:\cygwin\bin\diff.exe |
|
2018 | 2019 | c:\cygwin\bin\diff3.exe |
|
2019 | 2020 | |
|
2020 | 2021 | **%who**:: |
|
2021 | 2022 | |
|
2022 | 2023 | Print all interactive variables, with some minimal formatting. |
|
2023 | 2024 | |
|
2024 | 2025 | If any arguments are given, only variables whose type matches one of |
|
2025 | 2026 | these are printed. For example: |
|
2026 | 2027 | |
|
2027 | 2028 | %who function str |
|
2028 | 2029 | |
|
2029 | 2030 | will only list functions and strings, excluding all other types of |
|
2030 | 2031 | variables. To find the proper type names, simply use type(var) at a |
|
2031 | 2032 | command line to see how python prints type names. For example: |
|
2032 | 2033 | |
|
2033 | 2034 | In [1]: type('hello')\ |
|
2034 | 2035 | Out[1]: <type 'str'> |
|
2035 | 2036 | |
|
2036 | 2037 | indicates that the type name for strings is 'str'. |
|
2037 | 2038 | |
|
2038 | 2039 | %who always excludes executed names loaded through your configuration |
|
2039 | 2040 | file and things which are internal to IPython. |
|
2040 | 2041 | |
|
2041 | 2042 | This is deliberate, as typically you may load many modules and the |
|
2042 | 2043 | purpose of %who is to show you only what you've manually defined. |
|
2043 | 2044 | |
|
2044 | 2045 | **%who_ls**:: |
|
2045 | 2046 | |
|
2046 | 2047 | Return a sorted list of all interactive variables. |
|
2047 | 2048 | |
|
2048 | 2049 | If arguments are given, only variables of types matching these |
|
2049 | 2050 | arguments are returned. |
|
2050 | 2051 | |
|
2051 | 2052 | **%whos**:: |
|
2052 | 2053 | |
|
2053 | 2054 | Like %who, but gives some extra information about each variable. |
|
2054 | 2055 | |
|
2055 | 2056 | The same type filtering of %who can be applied here. |
|
2056 | 2057 | |
|
2057 | 2058 | For all variables, the type is printed. Additionally it prints: |
|
2058 | 2059 | |
|
2059 | 2060 | - For {},[],(): their length. |
|
2060 | 2061 | |
|
2061 | 2062 | - For numpy and Numeric arrays, a summary with shape, number of |
|
2062 | 2063 | elements, typecode and size in memory. |
|
2063 | 2064 | |
|
2064 | 2065 | - Everything else: a string representation, snipping their middle if |
|
2065 | 2066 | too long. |
|
2066 | 2067 | |
|
2067 | 2068 | **%xmode**:: |
|
2068 | 2069 | |
|
2069 | 2070 | Switch modes for the exception handlers. |
|
2070 | 2071 | |
|
2071 | 2072 | Valid modes: Plain, Context and Verbose. |
|
2072 | 2073 | |
|
2073 | 2074 | If called without arguments, acts as a toggle. |
|
2074 | 2075 | |
|
2075 | 2076 | .. magic_end |
|
2076 | 2077 | |
|
2077 | 2078 | Access to the standard Python help |
|
2078 | 2079 | ---------------------------------- |
|
2079 | 2080 | |
|
2080 | As of Python 2.1, a help system is available with access to object | |
|
2081 |
|
|
|
2082 |
|
|
|
2083 |
|
|
|
2084 |
|
|
|
2085 |
|
|
|
2081 | As of Python 2.1, a help system is available with access to object docstrings | |
|
2082 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can | |
|
2083 | also type help(object) to obtain information about a given object, and | |
|
2084 | help('keyword') for information on a keyword. As noted :ref:`here | |
|
2085 | <accessing_help>`, you need to properly configure your environment variable | |
|
2086 | PYTHONDOCS for this feature to work correctly. | |
|
2086 | 2087 | |
|
2088 | .. _dynamic_object_info: | |
|
2087 | 2089 | |
|
2088 | 2090 | Dynamic object information |
|
2089 | 2091 | -------------------------- |
|
2090 | 2092 | |
|
2091 | 2093 | Typing ?word or word? prints detailed information about an object. If |
|
2092 | 2094 | certain strings in the object are too long (docstrings, code, etc.) they |
|
2093 | 2095 | get snipped in the center for brevity. This system gives access variable |
|
2094 | 2096 | types and values, full source code for any object (if available), |
|
2095 | 2097 | function prototypes and other useful information. |
|
2096 | 2098 | |
|
2097 | 2099 | Typing ??word or word?? gives access to the full information without |
|
2098 | 2100 | snipping long strings. Long strings are sent to the screen through the |
|
2099 | 2101 | less pager if longer than the screen and printed otherwise. On systems |
|
2100 | 2102 | lacking the less command, IPython uses a very basic internal pager. |
|
2101 | 2103 | |
|
2102 | 2104 | The following magic functions are particularly useful for gathering |
|
2103 | 2105 | information about your working environment. You can get more details by |
|
2104 | 2106 | typing %magic or querying them individually (use %function_name? with or |
|
2105 | 2107 | without the %), this is just a summary: |
|
2106 | 2108 | |
|
2107 | 2109 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
2108 | 2110 | docstring for an object. If the given object is a class, it will |
|
2109 | 2111 | print both the class and the constructor docstrings. |
|
2110 | 2112 | * **%pdef <object>**: Print the definition header for any callable |
|
2111 | 2113 | object. If the object is a class, print the constructor information. |
|
2112 | 2114 | * **%psource <object>**: Print (or run through a pager if too long) |
|
2113 | 2115 | the source code for an object. |
|
2114 | 2116 | * **%pfile <object>**: Show the entire source file where an object was |
|
2115 | 2117 | defined via a pager, opening it at the line where the object |
|
2116 | 2118 | definition begins. |
|
2117 | 2119 | * **%who/%whos**: These functions give information about identifiers |
|
2118 | 2120 | you have defined interactively (not things you loaded or defined |
|
2119 | 2121 | in your configuration files). %who just prints a list of |
|
2120 | 2122 | identifiers and %whos prints a table with some basic details about |
|
2121 | 2123 | each identifier. |
|
2122 | 2124 | |
|
2123 | 2125 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, |
|
2124 | 2126 | %pdef, %psource) give you access to documentation even on things which |
|
2125 | 2127 | are not really defined as separate identifiers. Try for example typing |
|
2126 | 2128 | {}.get? or after doing import os, type os.path.abspath??. |
|
2127 | 2129 | |
|
2128 | 2130 | |
|
2129 |
.. _ |
|
|
2131 | .. _readline: | |
|
2130 | 2132 | |
|
2131 | 2133 | Readline-based features |
|
2132 | 2134 | ----------------------- |
|
2133 | 2135 | |
|
2134 | 2136 | These features require the GNU readline library, so they won't work if |
|
2135 | 2137 | your Python installation lacks readline support. We will first describe |
|
2136 | 2138 | the default behavior IPython uses, and then how to change it to suit |
|
2137 | 2139 | your preferences. |
|
2138 | 2140 | |
|
2139 | 2141 | |
|
2140 | 2142 | Command line completion |
|
2141 | 2143 | +++++++++++++++++++++++ |
|
2142 | 2144 | |
|
2143 | 2145 | At any time, hitting TAB will complete any available python commands or |
|
2144 | 2146 | variable names, and show you a list of the possible completions if |
|
2145 | 2147 | there's no unambiguous one. It will also complete filenames in the |
|
2146 | 2148 | current directory if no python names match what you've typed so far. |
|
2147 | 2149 | |
|
2148 | 2150 | |
|
2149 | 2151 | Search command history |
|
2150 | 2152 | ++++++++++++++++++++++ |
|
2151 | 2153 | |
|
2152 | 2154 | IPython provides two ways for searching through previous input and thus |
|
2153 | 2155 | reduce the need for repetitive typing: |
|
2154 | 2156 | |
|
2155 | 2157 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
2156 | 2158 | (next,down) to search through only the history items that match |
|
2157 | 2159 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
2158 | 2160 | prompt, they just behave like normal arrow keys. |
|
2159 | 2161 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
2160 | 2162 | searches your history for lines that contain what you've typed so |
|
2161 | 2163 | far, completing as much as it can. |
|
2162 | 2164 | |
|
2163 | 2165 | |
|
2164 | 2166 | Persistent command history across sessions |
|
2165 | 2167 | ++++++++++++++++++++++++++++++++++++++++++ |
|
2166 | 2168 | |
|
2167 | 2169 | IPython will save your input history when it leaves and reload it next |
|
2168 | 2170 | time you restart it. By default, the history file is named |
|
2169 | 2171 | $IPYTHONDIR/history, but if you've loaded a named profile, |
|
2170 | 2172 | '-PROFILE_NAME' is appended to the name. This allows you to keep |
|
2171 | 2173 | separate histories related to various tasks: commands related to |
|
2172 | 2174 | numerical work will not be clobbered by a system shell history, for |
|
2173 | 2175 | example. |
|
2174 | 2176 | |
|
2175 | 2177 | |
|
2176 | 2178 | Autoindent |
|
2177 | 2179 | ++++++++++ |
|
2178 | 2180 | |
|
2179 | 2181 | IPython can recognize lines ending in ':' and indent the next line, |
|
2180 | 2182 | while also un-indenting automatically after 'raise' or 'return'. |
|
2181 | 2183 | |
|
2182 | 2184 | This feature uses the readline library, so it will honor your ~/.inputrc |
|
2183 | 2185 | configuration (or whatever file your INPUTRC variable points to). Adding |
|
2184 | 2186 | the following lines to your .inputrc file can make indenting/unindenting |
|
2185 | 2187 | more convenient (M-i indents, M-u unindents):: |
|
2186 | 2188 | |
|
2187 | 2189 | $if Python |
|
2188 | 2190 | "\M-i": " " |
|
2189 | 2191 | "\M-u": "\d\d\d\d" |
|
2190 | 2192 | $endif |
|
2191 | 2193 | |
|
2192 | 2194 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
2193 | 2195 | |
|
2194 | 2196 | Warning: this feature is ON by default, but it can cause problems with |
|
2195 | 2197 | the pasting of multi-line indented code (the pasted code gets |
|
2196 | 2198 | re-indented on each line). A magic function %autoindent allows you to |
|
2197 | 2199 | toggle it on/off at runtime. You can also disable it permanently on in |
|
2198 | 2200 | your ipythonrc file (set autoindent 0). |
|
2199 | 2201 | |
|
2200 | 2202 | |
|
2201 | 2203 | Customizing readline behavior |
|
2202 | 2204 | +++++++++++++++++++++++++++++ |
|
2203 | 2205 | |
|
2204 | 2206 | All these features are based on the GNU readline library, which has an |
|
2205 | 2207 | extremely customizable interface. Normally, readline is configured via a |
|
2206 | 2208 | file which defines the behavior of the library; the details of the |
|
2207 | 2209 | syntax for this can be found in the readline documentation available |
|
2208 | 2210 | with your system or on the Internet. IPython doesn't read this file (if |
|
2209 | 2211 | it exists) directly, but it does support passing to readline valid |
|
2210 | 2212 | options via a simple interface. In brief, you can customize readline by |
|
2211 | 2213 | setting the following options in your ipythonrc configuration file (note |
|
2212 | 2214 | that these options can not be specified at the command line): |
|
2213 | 2215 | |
|
2214 | 2216 | * **readline_parse_and_bind**: this option can appear as many times as |
|
2215 | 2217 | you want, each time defining a string to be executed via a |
|
2216 | 2218 | readline.parse_and_bind() command. The syntax for valid commands |
|
2217 | 2219 | of this kind can be found by reading the documentation for the GNU |
|
2218 | 2220 | readline library, as these commands are of the kind which readline |
|
2219 | 2221 | accepts in its configuration file. |
|
2220 | 2222 | * **readline_remove_delims**: a string of characters to be removed |
|
2221 | 2223 | from the default word-delimiters list used by readline, so that |
|
2222 | 2224 | completions may be performed on strings which contain them. Do not |
|
2223 | 2225 | change the default value unless you know what you're doing. |
|
2224 | 2226 | * **readline_omit__names**: when tab-completion is enabled, hitting |
|
2225 | 2227 | <tab> after a '.' in a name will complete all attributes of an |
|
2226 | 2228 | object, including all the special methods whose names include |
|
2227 | 2229 | double underscores (like __getitem__ or __class__). If you'd |
|
2228 | 2230 | rather not see these names by default, you can set this option to |
|
2229 | 2231 | 1. Note that even when this option is set, you can still see those |
|
2230 | 2232 | names by explicitly typing a _ after the period and hitting <tab>: |
|
2231 | 2233 | 'name._<tab>' will always complete attribute names starting with '_'. |
|
2232 | 2234 | |
|
2233 | 2235 | This option is off by default so that new users see all |
|
2234 | 2236 | attributes of any objects they are dealing with. |
|
2235 | 2237 | |
|
2236 | 2238 | You will find the default values along with a corresponding detailed |
|
2237 | 2239 | explanation in your ipythonrc file. |
|
2238 | 2240 | |
|
2239 | 2241 | |
|
2240 | 2242 | Session logging and restoring |
|
2241 | 2243 | ----------------------------- |
|
2242 | 2244 | |
|
2243 | You can log all input from a session either by starting IPython with | |
|
2244 |
|
|
|
2245 |
|
|
|
2246 | function %logstart. | |
|
2245 | You can log all input from a session either by starting IPython with the | |
|
2246 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) | |
|
2247 | or by activating the logging at any moment with the magic function %logstart. | |
|
2247 | 2248 | |
|
2248 | 2249 | Log files can later be reloaded with the -logplay option and IPython |
|
2249 | 2250 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
2250 | 2251 | restoring the state of a previous session. This feature is not quite |
|
2251 | 2252 | perfect, but can still be useful in many cases. |
|
2252 | 2253 | |
|
2253 | 2254 | The log files can also be used as a way to have a permanent record of |
|
2254 | 2255 | any code you wrote while experimenting. Log files are regular text files |
|
2255 | 2256 | which you can later open in your favorite text editor to extract code or |
|
2256 | 2257 | to 'clean them up' before using them to replay a session. |
|
2257 | 2258 | |
|
2258 | 2259 | The %logstart function for activating logging in mid-session is used as |
|
2259 | 2260 | follows: |
|
2260 | 2261 | |
|
2261 | 2262 | %logstart [log_name [log_mode]] |
|
2262 | 2263 | |
|
2263 | 2264 | If no name is given, it defaults to a file named 'log' in your |
|
2264 | 2265 | IPYTHONDIR directory, in 'rotate' mode (see below). |
|
2265 | 2266 | |
|
2266 | 2267 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
2267 | 2268 | history up to that point and then continues logging. |
|
2268 | 2269 | |
|
2269 | 2270 | %logstart takes a second optional parameter: logging mode. This can be |
|
2270 | 2271 | one of (note that the modes are given unquoted): |
|
2271 | 2272 | |
|
2272 | 2273 | * [over:] overwrite existing log_name. |
|
2273 | 2274 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
2274 | 2275 | * [append:] well, that says it. |
|
2275 | 2276 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
2276 | 2277 | |
|
2277 | 2278 | The %logoff and %logon functions allow you to temporarily stop and |
|
2278 | 2279 | resume logging to a file which had previously been started with |
|
2279 | 2280 | %logstart. They will fail (with an explanation) if you try to use them |
|
2280 | 2281 | before logging has been started. |
|
2281 | 2282 | |
|
2283 | .. _system_shell_access: | |
|
2284 | ||
|
2282 | 2285 | System shell access |
|
2283 | 2286 | ------------------- |
|
2284 | 2287 | |
|
2285 | 2288 | Any input line beginning with a ! character is passed verbatim (minus |
|
2286 | 2289 | the !, of course) to the underlying operating system. For example, |
|
2287 | 2290 | typing !ls will run 'ls' in the current directory. |
|
2288 | 2291 | |
|
2289 | 2292 | Manual capture of command output |
|
2290 | 2293 | -------------------------------- |
|
2291 | 2294 | |
|
2292 | 2295 | If the input line begins with two exclamation marks, !!, the command is |
|
2293 | 2296 | executed but its output is captured and returned as a python list, split |
|
2294 | 2297 | on newlines. Any output sent by the subprocess to standard error is |
|
2295 | 2298 | printed separately, so that the resulting list only captures standard |
|
2296 | 2299 | output. The !! syntax is a shorthand for the %sx magic command. |
|
2297 | 2300 | |
|
2298 | 2301 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, |
|
2299 | 2302 | but allowing more fine-grained control of the capture details, and |
|
2300 | 2303 | storing the result directly into a named variable. The direct use of |
|
2301 | 2304 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax |
|
2302 | 2305 | instead. |
|
2303 | 2306 | |
|
2304 | 2307 | IPython also allows you to expand the value of python variables when |
|
2305 | 2308 | making system calls. Any python variable or expression which you prepend |
|
2306 | 2309 | with $ will get expanded before the system call is made:: |
|
2307 | 2310 | |
|
2308 | 2311 | In [1]: pyvar='Hello world' |
|
2309 | 2312 | In [2]: !echo "A python variable: $pyvar" |
|
2310 | 2313 | A python variable: Hello world |
|
2311 | 2314 | |
|
2312 | 2315 | If you want the shell to actually see a literal $, you need to type it |
|
2313 | 2316 | twice:: |
|
2314 | 2317 | |
|
2315 | 2318 | In [3]: !echo "A system variable: $$HOME" |
|
2316 | 2319 | A system variable: /home/fperez |
|
2317 | 2320 | |
|
2318 | 2321 | You can pass arbitrary expressions, though you'll need to delimit them |
|
2319 | 2322 | with {} if there is ambiguity as to the extent of the expression:: |
|
2320 | 2323 | |
|
2321 | 2324 | In [5]: x=10 |
|
2322 | 2325 | In [6]: y=20 |
|
2323 | 2326 | In [13]: !echo $x+y |
|
2324 | 2327 | 10+y |
|
2325 | 2328 | In [7]: !echo ${x+y} |
|
2326 | 2329 | 30 |
|
2327 | 2330 | |
|
2328 | 2331 | Even object attributes can be expanded:: |
|
2329 | 2332 | |
|
2330 | 2333 | In [12]: !echo $sys.argv |
|
2331 | 2334 | [/home/fperez/usr/bin/ipython] |
|
2332 | 2335 | |
|
2333 | 2336 | |
|
2334 | 2337 | System command aliases |
|
2335 | 2338 | ---------------------- |
|
2336 | 2339 | |
|
2337 | 2340 | The %alias magic function and the alias option in the ipythonrc |
|
2338 | 2341 | configuration file allow you to define magic functions which are in fact |
|
2339 | 2342 | system shell commands. These aliases can have parameters. |
|
2340 | 2343 | |
|
2341 | 2344 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2342 | 2345 | |
|
2343 | 2346 | Then, typing '%alias_name params' will execute the system command 'cmd |
|
2344 | 2347 | params' (from your underlying operating system). |
|
2345 | 2348 | |
|
2346 | 2349 | You can also define aliases with parameters using %s specifiers (one per |
|
2347 | 2350 | parameter). The following example defines the %parts function as an |
|
2348 | 2351 | alias to the command 'echo first %s second %s' where each %s will be |
|
2349 | 2352 | replaced by a positional parameter to the call to %parts:: |
|
2350 | 2353 | |
|
2351 | 2354 | In [1]: alias parts echo first %s second %s |
|
2352 | 2355 | In [2]: %parts A B |
|
2353 | 2356 | first A second B |
|
2354 | 2357 | In [3]: %parts A |
|
2355 | 2358 | Incorrect number of arguments: 2 expected. |
|
2356 | 2359 | parts is an alias to: 'echo first %s second %s' |
|
2357 | 2360 | |
|
2358 | 2361 | If called with no parameters, %alias prints the table of currently |
|
2359 | 2362 | defined aliases. |
|
2360 | 2363 | |
|
2361 | 2364 | The %rehash/rehashx magics allow you to load your entire $PATH as |
|
2362 | 2365 | ipython aliases. See their respective docstrings (or sec. 6.2 |
|
2363 | 2366 | <#sec:magic> for further details). |
|
2364 | 2367 | |
|
2365 | 2368 | |
|
2366 | 2369 | .. _dreload: |
|
2367 | 2370 | |
|
2368 | 2371 | Recursive reload |
|
2369 | 2372 | ---------------- |
|
2370 | 2373 | |
|
2371 | 2374 | The dreload function does a recursive reload of a module: changes made |
|
2372 | 2375 | to the module since you imported will actually be available without |
|
2373 | 2376 | having to exit. |
|
2374 | 2377 | |
|
2375 | 2378 | |
|
2376 | 2379 | Verbose and colored exception traceback printouts |
|
2377 | 2380 | ------------------------------------------------- |
|
2378 | 2381 | |
|
2379 | 2382 | IPython provides the option to see very detailed exception tracebacks, |
|
2380 | 2383 | which can be especially useful when debugging large programs. You can |
|
2381 | 2384 | run any Python file with the %run function to benefit from these |
|
2382 | 2385 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
2383 | 2386 | be colored (if your terminal supports it) which makes them much easier |
|
2384 | 2387 | to parse visually. |
|
2385 | 2388 | |
|
2386 | 2389 | See the magic xmode and colors functions for details (just type %magic). |
|
2387 | 2390 | |
|
2388 | 2391 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
2389 | 2392 | module, now part of the standard Python library. |
|
2390 | 2393 | |
|
2391 | 2394 | |
|
2392 |
.. _ |
|
|
2395 | .. _input_caching: | |
|
2393 | 2396 | |
|
2394 | 2397 | Input caching system |
|
2395 | 2398 | -------------------- |
|
2396 | 2399 | |
|
2397 | 2400 | IPython offers numbered prompts (In/Out) with input and output caching. |
|
2398 | 2401 | All input is saved and can be retrieved as variables (besides the usual |
|
2399 | 2402 | arrow key recall). |
|
2400 | 2403 | |
|
2401 | 2404 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2402 | 2405 | _i: stores previous input. _ii: next previous. _iii: next-next previous. |
|
2403 | 2406 | _ih : a list of all input _ih[n] is the input from line n and this list |
|
2404 | 2407 | is aliased to the global variable In. If you overwrite In with a |
|
2405 | 2408 | variable of your own, you can remake the assignment to the internal list |
|
2406 | 2409 | with a simple 'In=_ih'. |
|
2407 | 2410 | |
|
2408 | 2411 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
2409 | 2412 | being the prompt counter), such that |
|
2410 | 2413 | _i<n> == _ih[<n>] == In[<n>]. |
|
2411 | 2414 | |
|
2412 | 2415 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
2413 | 2416 | and In[14]. |
|
2414 | 2417 | |
|
2415 | 2418 | This allows you to easily cut and paste multi line interactive prompts |
|
2416 | 2419 | by printing them out: they print like a clean string, without prompt |
|
2417 | 2420 | characters. You can also manipulate them like regular variables (they |
|
2418 | 2421 | are strings), modify or exec them (typing 'exec _i9' will re-execute the |
|
2419 | 2422 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines |
|
2420 | 2423 | 9 through 13 and line 18). |
|
2421 | 2424 | |
|
2422 | 2425 | You can also re-execute multiple lines of input easily by using the |
|
2423 | 2426 | magic %macro function (which automates the process and allows |
|
2424 | 2427 | re-execution without having to type 'exec' every time). The macro system |
|
2425 | 2428 | also allows you to re-execute previous lines which include magic |
|
2426 | 2429 | function calls (which require special processing). Type %macro? or see |
|
2427 | 2430 | sec. 6.2 <#sec:magic> for more details on the macro system. |
|
2428 | 2431 | |
|
2429 | 2432 | A history function %hist allows you to see any part of your input |
|
2430 | 2433 | history by printing a range of the _i variables. |
|
2431 | 2434 | |
|
2432 |
.. _ |
|
|
2435 | .. _output_caching: | |
|
2433 | 2436 | |
|
2434 | 2437 | Output caching system |
|
2435 | 2438 | --------------------- |
|
2436 | 2439 | |
|
2437 | 2440 | For output that is returned from actions, a system similar to the input |
|
2438 | 2441 | cache exists but using _ instead of _i. Only actions that produce a |
|
2439 | 2442 | result (NOT assignments, for example) are cached. If you are familiar |
|
2440 | 2443 | with Mathematica, IPython's _ variables behave exactly like |
|
2441 | 2444 | Mathematica's % variables. |
|
2442 | 2445 | |
|
2443 | 2446 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2444 | 2447 | |
|
2445 | 2448 | * [_] (a single underscore) : stores previous output, like Python's |
|
2446 | 2449 | default interpreter. |
|
2447 | 2450 | * [__] (two underscores): next previous. |
|
2448 | 2451 | * [___] (three underscores): next-next previous. |
|
2449 | 2452 | |
|
2450 | 2453 | Additionally, global variables named _<n> are dynamically created (<n> |
|
2451 | 2454 | being the prompt counter), such that the result of output <n> is always |
|
2452 | 2455 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
2453 | 2456 | _21). |
|
2454 | 2457 | |
|
2455 | 2458 | These global variables are all stored in a global dictionary (not a |
|
2456 | 2459 | list, since it only has entries for lines which returned a result) |
|
2457 | 2460 | available under the names _oh and Out (similar to _ih and In). So the |
|
2458 | 2461 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
2459 | 2462 | accidentally overwrite the Out variable you can recover it by typing |
|
2460 | 2463 | 'Out=_oh' at the prompt. |
|
2461 | 2464 | |
|
2462 | 2465 | This system obviously can potentially put heavy memory demands on your |
|
2463 | 2466 | system, since it prevents Python's garbage collector from removing any |
|
2464 | 2467 | previously computed results. You can control how many results are kept |
|
2465 | 2468 | in memory with the option (at the command line or in your ipythonrc |
|
2466 | 2469 | file) cache_size. If you set it to 0, the whole system is completely |
|
2467 | 2470 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
2468 | 2471 | |
|
2469 | 2472 | |
|
2470 | 2473 | Directory history |
|
2471 | 2474 | ----------------- |
|
2472 | 2475 | |
|
2473 | 2476 | Your history of visited directories is kept in the global list _dh, and |
|
2474 | 2477 | the magic %cd command can be used to go to any entry in that list. The |
|
2475 | 2478 | %dhist command allows you to view this history. do ``cd -<TAB`` to |
|
2476 | 2479 | conventiently view the directory history. |
|
2477 | 2480 | |
|
2478 | 2481 | |
|
2479 | 2482 | Automatic parentheses and quotes |
|
2480 | 2483 | -------------------------------- |
|
2481 | 2484 | |
|
2482 | 2485 | These features were adapted from Nathan Gray's LazyPython. They are |
|
2483 | 2486 | meant to allow less typing for common situations. |
|
2484 | 2487 | |
|
2485 | 2488 | |
|
2486 | 2489 | Automatic parentheses |
|
2487 | 2490 | --------------------- |
|
2488 | 2491 | |
|
2489 | 2492 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
2490 | 2493 | (notice the commas between the arguments):: |
|
2491 | 2494 | |
|
2492 | 2495 | >>> callable_ob arg1, arg2, arg3 |
|
2493 | 2496 | |
|
2494 | 2497 | and the input will be translated to this:: |
|
2495 | 2498 | |
|
2496 | 2499 | -> callable_ob(arg1, arg2, arg3) |
|
2497 | 2500 | |
|
2498 | 2501 | You can force automatic parentheses by using '/' as the first character |
|
2499 | 2502 | of a line. For example:: |
|
2500 | 2503 | |
|
2501 | 2504 | >>> /globals # becomes 'globals()' |
|
2502 | 2505 | |
|
2503 | 2506 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
2504 | 2507 | |
|
2505 | 2508 | >>> print /globals # syntax error |
|
2506 | 2509 | |
|
2507 | 2510 | In most cases the automatic algorithm should work, so you should rarely |
|
2508 | 2511 | need to explicitly invoke /. One notable exception is if you are trying |
|
2509 | 2512 | to call a function with a list of tuples as arguments (the parenthesis |
|
2510 | 2513 | will confuse IPython):: |
|
2511 | 2514 | |
|
2512 | 2515 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
2513 | 2516 | |
|
2514 | 2517 | but this will work:: |
|
2515 | 2518 | |
|
2516 | 2519 | In [2]: /zip (1,2,3),(4,5,6) |
|
2517 | 2520 | ---> zip ((1,2,3),(4,5,6)) |
|
2518 | 2521 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
2519 | 2522 | |
|
2520 | 2523 | IPython tells you that it has altered your command line by displaying |
|
2521 | 2524 | the new command line preceded by ->. e.g.:: |
|
2522 | 2525 | |
|
2523 | 2526 | In [18]: callable list |
|
2524 | 2527 | ----> callable (list) |
|
2525 | 2528 | |
|
2526 | 2529 | |
|
2527 | 2530 | Automatic quoting |
|
2528 | 2531 | ----------------- |
|
2529 | 2532 | |
|
2530 | 2533 | You can force automatic quoting of a function's arguments by using ',' |
|
2531 | 2534 | or ';' as the first character of a line. For example:: |
|
2532 | 2535 | |
|
2533 | 2536 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
2534 | 2537 | |
|
2535 | 2538 | If you use ';' instead, the whole argument is quoted as a single string |
|
2536 | 2539 | (while ',' splits on whitespace):: |
|
2537 | 2540 | |
|
2538 | 2541 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
2539 | 2542 | |
|
2540 | 2543 | >>> ;my_function a b c # becomes my_function("a b c") |
|
2541 | 2544 | |
|
2542 | 2545 | Note that the ',' or ';' MUST be the first character on the line! This |
|
2543 | 2546 | won't work:: |
|
2544 | 2547 | |
|
2545 | 2548 | >>> x = ,my_function /home/me # syntax error |
|
2546 | 2549 | |
|
2547 | 2550 | IPython as your default Python environment |
|
2548 | 2551 | ========================================== |
|
2549 | 2552 | |
|
2550 | 2553 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
2551 | 2554 | startup the file referenced by this variable. If you put at the end of |
|
2552 | 2555 | this file the following two lines of code:: |
|
2553 | 2556 | |
|
2554 | 2557 | import IPython |
|
2555 | 2558 | IPython.Shell.IPShell().mainloop(sys_exit=1) |
|
2556 | 2559 | |
|
2557 | 2560 | then IPython will be your working environment anytime you start Python. |
|
2558 | 2561 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when |
|
2559 | 2562 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
2560 | 2563 | prompt. |
|
2561 | 2564 | |
|
2562 | 2565 | This is probably useful to developers who manage multiple Python |
|
2563 | 2566 | versions and don't want to have correspondingly multiple IPython |
|
2564 | 2567 | versions. Note that in this mode, there is no way to pass IPython any |
|
2565 | 2568 | command-line options, as those are trapped first by Python itself. |
|
2566 | 2569 | |
|
2567 | 2570 | .. _Embedding: |
|
2568 | 2571 | |
|
2569 | 2572 | Embedding IPython |
|
2570 | 2573 | ================= |
|
2571 | 2574 | |
|
2572 | 2575 | It is possible to start an IPython instance inside your own Python |
|
2573 | 2576 | programs. This allows you to evaluate dynamically the state of your |
|
2574 | 2577 | code, operate with your variables, analyze them, etc. Note however that |
|
2575 | 2578 | any changes you make to values while in the shell do not propagate back |
|
2576 | 2579 | to the running code, so it is safe to modify your values because you |
|
2577 | 2580 | won't break your code in bizarre ways by doing so. |
|
2578 | 2581 | |
|
2579 | 2582 | This feature allows you to easily have a fully functional python |
|
2580 | 2583 | environment for doing object introspection anywhere in your code with a |
|
2581 | 2584 | simple function call. In some cases a simple print statement is enough, |
|
2582 | 2585 | but if you need to do more detailed analysis of a code fragment this |
|
2583 | 2586 | feature can be very valuable. |
|
2584 | 2587 | |
|
2585 | 2588 | It can also be useful in scientific computing situations where it is |
|
2586 | 2589 | common to need to do some automatic, computationally intensive part and |
|
2587 | 2590 | then stop to look at data, plots, etc. |
|
2588 | 2591 | Opening an IPython instance will give you full access to your data and |
|
2589 | 2592 | functions, and you can resume program execution once you are done with |
|
2590 | 2593 | the interactive part (perhaps to stop again later, as many times as |
|
2591 | 2594 | needed). |
|
2592 | 2595 | |
|
2593 | 2596 | The following code snippet is the bare minimum you need to include in |
|
2594 | 2597 | your Python programs for this to work (detailed examples follow later):: |
|
2595 | 2598 | |
|
2596 | 2599 | from IPython.Shell import IPShellEmbed |
|
2597 | 2600 | |
|
2598 | 2601 | ipshell = IPShellEmbed() |
|
2599 | 2602 | |
|
2600 | 2603 | ipshell() # this call anywhere in your program will start IPython |
|
2601 | 2604 | |
|
2602 | 2605 | You can run embedded instances even in code which is itself being run at |
|
2603 | 2606 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
2604 | 2607 | to get lost as to where you are (in your top-level IPython or in your |
|
2605 | 2608 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
2606 | 2609 | to something different for the embedded instances. The code examples |
|
2607 | 2610 | below illustrate this. |
|
2608 | 2611 | |
|
2609 | 2612 | You can also have multiple IPython instances in your program and open |
|
2610 | 2613 | them separately, for example with different options for data |
|
2611 | 2614 | presentation. If you close and open the same instance multiple times, |
|
2612 | 2615 | its prompt counters simply continue from each execution to the next. |
|
2613 | 2616 | |
|
2614 | 2617 | Please look at the docstrings in the Shell.py module for more details on |
|
2615 | 2618 | the use of this system. |
|
2616 | 2619 | |
|
2617 | 2620 | The following sample file illustrating how to use the embedding |
|
2618 | 2621 | functionality is provided in the examples directory as example-embed.py. |
|
2619 | 2622 | It should be fairly self-explanatory:: |
|
2620 | 2623 | |
|
2621 | 2624 | |
|
2622 | 2625 | #!/usr/bin/env python |
|
2623 | 2626 | |
|
2624 | 2627 | """An example of how to embed an IPython shell into a running program. |
|
2625 | 2628 | |
|
2626 | 2629 | Please see the documentation in the IPython.Shell module for more details. |
|
2627 | 2630 | |
|
2628 | 2631 | The accompanying file example-embed-short.py has quick code fragments for |
|
2629 | 2632 | embedding which you can cut and paste in your code once you understand how |
|
2630 | 2633 | things work. |
|
2631 | 2634 | |
|
2632 | 2635 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
2633 | 2636 | |
|
2634 | 2637 | # The basics to get you going: |
|
2635 | 2638 | |
|
2636 | 2639 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
2637 | 2640 | # copies running. |
|
2638 | 2641 | |
|
2639 | 2642 | # Try running this code both at the command line and from inside IPython (with |
|
2640 | 2643 | # %run example-embed.py) |
|
2641 | 2644 | try: |
|
2642 | 2645 | __IPYTHON__ |
|
2643 | 2646 | except NameError: |
|
2644 | 2647 | nested = 0 |
|
2645 | 2648 | args = [''] |
|
2646 | 2649 | else: |
|
2647 | 2650 | print "Running nested copies of IPython." |
|
2648 | 2651 | print "The prompts for the nested copy have been modified" |
|
2649 | 2652 | nested = 1 |
|
2650 | 2653 | # what the embedded instance will see as sys.argv: |
|
2651 | 2654 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', |
|
2652 | 2655 | '-po','Out<\\#>: ','-nosep'] |
|
2653 | 2656 | |
|
2654 | 2657 | # First import the embeddable shell class |
|
2655 | 2658 | from IPython.Shell import IPShellEmbed |
|
2656 | 2659 | |
|
2657 | 2660 | # Now create an instance of the embeddable shell. The first argument is a |
|
2658 | 2661 | # string with options exactly as you would type them if you were starting |
|
2659 | 2662 | # IPython at the system command line. Any parameters you want to define for |
|
2660 | 2663 | # configuration can thus be specified here. |
|
2661 | 2664 | ipshell = IPShellEmbed(args, |
|
2662 | 2665 | banner = 'Dropping into IPython', |
|
2663 | 2666 | exit_msg = 'Leaving Interpreter, back to program.') |
|
2664 | 2667 | |
|
2665 | 2668 | # Make a second instance, you can have as many as you want. |
|
2666 | 2669 | if nested: |
|
2667 | 2670 | args[1] = 'In2<\\#>' |
|
2668 | 2671 | else: |
|
2669 | 2672 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', |
|
2670 | 2673 | '-po','Out<\\#>: ','-nosep'] |
|
2671 | 2674 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') |
|
2672 | 2675 | |
|
2673 | 2676 | print '\nHello. This is printed from the main controller program.\n' |
|
2674 | 2677 | |
|
2675 | 2678 | # You can then call ipshell() anywhere you need it (with an optional |
|
2676 | 2679 | # message): |
|
2677 | 2680 | ipshell('***Called from top level. ' |
|
2678 | 2681 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
2679 | 2682 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
2680 | 2683 | 'This embedded instance so it will never turn on again') |
|
2681 | 2684 | |
|
2682 | 2685 | print '\nBack in caller program, moving along...\n' |
|
2683 | 2686 | |
|
2684 | 2687 | #--------------------------------------------------------------------------- |
|
2685 | 2688 | # More details: |
|
2686 | 2689 | |
|
2687 | 2690 | # IPShellEmbed instances don't print the standard system banner and |
|
2688 | 2691 | # messages. The IPython banner (which actually may contain initialization |
|
2689 | 2692 | # messages) is available as <instance>.IP.BANNER in case you want it. |
|
2690 | 2693 | |
|
2691 | 2694 | # IPShellEmbed instances print the following information everytime they |
|
2692 | 2695 | # start: |
|
2693 | 2696 | |
|
2694 | 2697 | # - A global startup banner. |
|
2695 | 2698 | |
|
2696 | 2699 | # - A call-specific header string, which you can use to indicate where in the |
|
2697 | 2700 | # execution flow the shell is starting. |
|
2698 | 2701 | |
|
2699 | 2702 | # They also print an exit message every time they exit. |
|
2700 | 2703 | |
|
2701 | 2704 | # Both the startup banner and the exit message default to None, and can be set |
|
2702 | 2705 | # either at the instance constructor or at any other time with the |
|
2703 | 2706 | # set_banner() and set_exit_msg() methods. |
|
2704 | 2707 | |
|
2705 | 2708 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
2706 | 2709 | # basis. This gives you fine control for debugging without having to change |
|
2707 | 2710 | # code all over the place. |
|
2708 | 2711 | |
|
2709 | 2712 | # The code below illustrates all this. |
|
2710 | 2713 | |
|
2711 | 2714 | |
|
2712 | 2715 | # This is how the global banner and exit_msg can be reset at any point |
|
2713 | 2716 | ipshell.set_banner('Entering interpreter - New Banner') |
|
2714 | 2717 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') |
|
2715 | 2718 | |
|
2716 | 2719 | def foo(m): |
|
2717 | 2720 | s = 'spam' |
|
2718 | 2721 | ipshell('***In foo(). Try @whos, or print s or m:') |
|
2719 | 2722 | print 'foo says m = ',m |
|
2720 | 2723 | |
|
2721 | 2724 | def bar(n): |
|
2722 | 2725 | s = 'eggs' |
|
2723 | 2726 | ipshell('***In bar(). Try @whos, or print s or n:') |
|
2724 | 2727 | print 'bar says n = ',n |
|
2725 | 2728 | |
|
2726 | 2729 | # Some calls to the above functions which will trigger IPython: |
|
2727 | 2730 | print 'Main program calling foo("eggs")\n' |
|
2728 | 2731 | foo('eggs') |
|
2729 | 2732 | |
|
2730 | 2733 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
2731 | 2734 | # allows you, for example, to globally turn off debugging for a program with a |
|
2732 | 2735 | # single call. |
|
2733 | 2736 | ipshell.set_dummy_mode(1) |
|
2734 | 2737 | print '\nTrying to call IPython which is now "dummy":' |
|
2735 | 2738 | ipshell() |
|
2736 | 2739 | print 'Nothing happened...' |
|
2737 | 2740 | # The global 'dummy' mode can still be overridden for a single call |
|
2738 | 2741 | print '\nOverriding dummy mode manually:' |
|
2739 | 2742 | ipshell(dummy=0) |
|
2740 | 2743 | |
|
2741 | 2744 | # Reactivate the IPython shell |
|
2742 | 2745 | ipshell.set_dummy_mode(0) |
|
2743 | 2746 | |
|
2744 | 2747 | print 'You can even have multiple embedded instances:' |
|
2745 | 2748 | ipshell2() |
|
2746 | 2749 | |
|
2747 | 2750 | print '\nMain program calling bar("spam")\n' |
|
2748 | 2751 | bar('spam') |
|
2749 | 2752 | |
|
2750 | 2753 | print 'Main program finished. Bye!' |
|
2751 | 2754 | |
|
2752 | 2755 | #********************** End of file <example-embed.py> *********************** |
|
2753 | 2756 | |
|
2754 | 2757 | Once you understand how the system functions, you can use the following |
|
2755 | 2758 | code fragments in your programs which are ready for cut and paste:: |
|
2756 | 2759 | |
|
2757 | 2760 | |
|
2758 | 2761 | """Quick code snippets for embedding IPython into other programs. |
|
2759 | 2762 | |
|
2760 | 2763 | See example-embed.py for full details, this file has the bare minimum code for |
|
2761 | 2764 | cut and paste use once you understand how to use the system.""" |
|
2762 | 2765 | |
|
2763 | 2766 | #--------------------------------------------------------------------------- |
|
2764 | 2767 | # This code loads IPython but modifies a few things if it detects it's running |
|
2765 | 2768 | # embedded in another IPython session (helps avoid confusion) |
|
2766 | 2769 | |
|
2767 | 2770 | try: |
|
2768 | 2771 | __IPYTHON__ |
|
2769 | 2772 | except NameError: |
|
2770 | 2773 | argv = [''] |
|
2771 | 2774 | banner = exit_msg = '' |
|
2772 | 2775 | else: |
|
2773 | 2776 | # Command-line options for IPython (a list like sys.argv) |
|
2774 | 2777 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] |
|
2775 | 2778 | banner = '*** Nested interpreter ***' |
|
2776 | 2779 | exit_msg = '*** Back in main IPython ***' |
|
2777 | 2780 | |
|
2778 | 2781 | # First import the embeddable shell class |
|
2779 | 2782 | from IPython.Shell import IPShellEmbed |
|
2780 | 2783 | # Now create the IPython shell instance. Put ipshell() anywhere in your code |
|
2781 | 2784 | # where you want it to open. |
|
2782 | 2785 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) |
|
2783 | 2786 | |
|
2784 | 2787 | #--------------------------------------------------------------------------- |
|
2785 | 2788 | # This code will load an embeddable IPython shell always with no changes for |
|
2786 | 2789 | # nested embededings. |
|
2787 | 2790 | |
|
2788 | 2791 | from IPython.Shell import IPShellEmbed |
|
2789 | 2792 | ipshell = IPShellEmbed() |
|
2790 | 2793 | # Now ipshell() will open IPython anywhere in the code. |
|
2791 | 2794 | |
|
2792 | 2795 | #--------------------------------------------------------------------------- |
|
2793 | 2796 | # This code loads an embeddable shell only if NOT running inside |
|
2794 | 2797 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a |
|
2795 | 2798 | # dummy function. |
|
2796 | 2799 | |
|
2797 | 2800 | try: |
|
2798 | 2801 | __IPYTHON__ |
|
2799 | 2802 | except NameError: |
|
2800 | 2803 | from IPython.Shell import IPShellEmbed |
|
2801 | 2804 | ipshell = IPShellEmbed() |
|
2802 | 2805 | # Now ipshell() will open IPython anywhere in the code |
|
2803 | 2806 | else: |
|
2804 | 2807 | # Define a dummy ipshell() so the same code doesn't crash inside an |
|
2805 | 2808 | # interactive IPython |
|
2806 | 2809 | def ipshell(): pass |
|
2807 | 2810 | |
|
2808 | 2811 | #******************* End of file <example-embed-short.py> ******************** |
|
2809 | 2812 | |
|
2810 | 2813 | Using the Python debugger (pdb) |
|
2811 | 2814 | =============================== |
|
2812 | 2815 | |
|
2813 | 2816 | Running entire programs via pdb |
|
2814 | 2817 | ------------------------------- |
|
2815 | 2818 | |
|
2816 | 2819 | pdb, the Python debugger, is a powerful interactive debugger which |
|
2817 | 2820 | allows you to step through code, set breakpoints, watch variables, |
|
2818 | 2821 | etc. IPython makes it very easy to start any script under the control |
|
2819 | 2822 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
2820 | 2823 | function or not. For this, simply type '%run -d myscript' at an |
|
2821 | 2824 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
2822 | 2825 | in Sec. magic_ for more details, including how to control where pdb |
|
2823 | 2826 | will stop execution first. |
|
2824 | 2827 | |
|
2825 | 2828 | For more information on the use of the pdb debugger, read the included |
|
2826 | 2829 | pdb.doc file (part of the standard Python distribution). On a stock |
|
2827 | 2830 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
2828 | 2831 | easiest way to read it is by using the help() function of the pdb module |
|
2829 | 2832 | as follows (in an IPython prompt): |
|
2830 | 2833 | |
|
2831 | 2834 | In [1]: import pdb |
|
2832 | 2835 | In [2]: pdb.help() |
|
2833 | 2836 | |
|
2834 | 2837 | This will load the pdb.doc document in a file viewer for you automatically. |
|
2835 | 2838 | |
|
2836 | 2839 | |
|
2837 | 2840 | Automatic invocation of pdb on exceptions |
|
2838 | 2841 | ----------------------------------------- |
|
2839 | 2842 | |
|
2840 | 2843 | IPython, if started with the -pdb option (or if the option is set in |
|
2841 | 2844 | your rc file) can call the Python pdb debugger every time your code |
|
2842 | 2845 | triggers an uncaught exception. This feature |
|
2843 | 2846 | can also be toggled at any time with the %pdb magic command. This can be |
|
2844 | 2847 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
2845 | 2848 | opens up at the point in your code which triggered the exception, and |
|
2846 | 2849 | while your program is at this point 'dead', all the data is still |
|
2847 | 2850 | available and you can walk up and down the stack frame and understand |
|
2848 | 2851 | the origin of the problem. |
|
2849 | 2852 | |
|
2850 | 2853 | Furthermore, you can use these debugging facilities both with the |
|
2851 | 2854 | embedded IPython mode and without IPython at all. For an embedded shell |
|
2852 | 2855 | (see sec. Embedding_), simply call the constructor with |
|
2853 | 2856 | '-pdb' in the argument string and automatically pdb will be called if an |
|
2854 | 2857 | uncaught exception is triggered by your code. |
|
2855 | 2858 | |
|
2856 | 2859 | For stand-alone use of the feature in your programs which do not use |
|
2857 | 2860 | IPython at all, put the following lines toward the top of your 'main' |
|
2858 | 2861 | routine:: |
|
2859 | 2862 | |
|
2860 | 2863 | import sys,IPython.ultraTB |
|
2861 | 2864 | sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose', |
|
2862 | 2865 | color_scheme='Linux', call_pdb=1) |
|
2863 | 2866 | |
|
2864 | 2867 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
2865 | 2868 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
2866 | 2869 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
2867 | 2870 | options which can be set in IPython with -colors and -xmode. |
|
2868 | 2871 | |
|
2869 | 2872 | This will give any of your programs detailed, colored tracebacks with |
|
2870 | 2873 | automatic invocation of pdb. |
|
2871 | 2874 | |
|
2872 | 2875 | |
|
2873 | 2876 | Extensions for syntax processing |
|
2874 | 2877 | ================================ |
|
2875 | 2878 | |
|
2876 | 2879 | This isn't for the faint of heart, because the potential for breaking |
|
2877 | 2880 | things is quite high. But it can be a very powerful and useful feature. |
|
2878 | 2881 | In a nutshell, you can redefine the way IPython processes the user input |
|
2879 | 2882 | line to accept new, special extensions to the syntax without needing to |
|
2880 | 2883 | change any of IPython's own code. |
|
2881 | 2884 | |
|
2882 | 2885 | In the IPython/Extensions directory you will find some examples |
|
2883 | 2886 | supplied, which we will briefly describe now. These can be used 'as is' |
|
2884 | 2887 | (and both provide very useful functionality), or you can use them as a |
|
2885 | 2888 | starting point for writing your own extensions. |
|
2886 | 2889 | |
|
2887 | 2890 | |
|
2888 | 2891 | Pasting of code starting with '>>> ' or '... ' |
|
2889 | 2892 | ---------------------------------------------- |
|
2890 | 2893 | |
|
2891 | 2894 | In the python tutorial it is common to find code examples which have |
|
2892 | 2895 | been taken from real python sessions. The problem with those is that all |
|
2893 | 2896 | the lines begin with either '>>> ' or '... ', which makes it impossible |
|
2894 | 2897 | to paste them all at once. One must instead do a line by line manual |
|
2895 | 2898 | copying, carefully removing the leading extraneous characters. |
|
2896 | 2899 | |
|
2897 | 2900 | This extension identifies those starting characters and removes them |
|
2898 | 2901 | from the input automatically, so that one can paste multi-line examples |
|
2899 | 2902 | directly into IPython, saving a lot of time. Please look at the file |
|
2900 | 2903 | InterpreterPasteInput.py in the IPython/Extensions directory for details |
|
2901 | 2904 | on how this is done. |
|
2902 | 2905 | |
|
2903 | 2906 | IPython comes with a special profile enabling this feature, called |
|
2904 | 2907 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature |
|
2905 | 2908 | will be available. In a normal IPython session you can activate the |
|
2906 | 2909 | feature by importing the corresponding module with: |
|
2907 | 2910 | In [1]: import IPython.Extensions.InterpreterPasteInput |
|
2908 | 2911 | |
|
2909 | 2912 | The following is a 'screenshot' of how things work when this extension |
|
2910 | 2913 | is on, copying an example from the standard tutorial:: |
|
2911 | 2914 | |
|
2912 | 2915 | IPython profile: tutorial |
|
2913 | 2916 | |
|
2914 | 2917 | *** Pasting of code with ">>>" or "..." has been enabled. |
|
2915 | 2918 | |
|
2916 | 2919 | In [1]: >>> def fib2(n): # return Fibonacci series up to n |
|
2917 | 2920 | ...: ... """Return a list containing the Fibonacci series up to |
|
2918 | 2921 | n.""" |
|
2919 | 2922 | ...: ... result = [] |
|
2920 | 2923 | ...: ... a, b = 0, 1 |
|
2921 | 2924 | ...: ... while b < n: |
|
2922 | 2925 | ...: ... result.append(b) # see below |
|
2923 | 2926 | ...: ... a, b = b, a+b |
|
2924 | 2927 | ...: ... return result |
|
2925 | 2928 | ...: |
|
2926 | 2929 | |
|
2927 | 2930 | In [2]: fib2(10) |
|
2928 | 2931 | Out[2]: [1, 1, 2, 3, 5, 8] |
|
2929 | 2932 | |
|
2930 | 2933 | Note that as currently written, this extension does not recognize |
|
2931 | 2934 | IPython's prompts for pasting. Those are more complicated, since the |
|
2932 | 2935 | user can change them very easily, they involve numbers and can vary in |
|
2933 | 2936 | length. One could however extract all the relevant information from the |
|
2934 | 2937 | IPython instance and build an appropriate regular expression. This is |
|
2935 | 2938 | left as an exercise for the reader. |
|
2936 | 2939 | |
|
2937 | 2940 | |
|
2938 | 2941 | Input of physical quantities with units |
|
2939 | 2942 | --------------------------------------- |
|
2940 | 2943 | |
|
2941 | 2944 | The module PhysicalQInput allows a simplified form of input for physical |
|
2942 | 2945 | quantities with units. This file is meant to be used in conjunction with |
|
2943 | 2946 | the PhysicalQInteractive module (in the same directory) and |
|
2944 | 2947 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython |
|
2945 | 2948 | (http://dirac.cnrs-orleans.fr/ScientificPython/). |
|
2946 | 2949 | |
|
2947 | 2950 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, |
|
2948 | 2951 | but these must be declared as instances of a class. For example, to |
|
2949 | 2952 | define v as a velocity of 3 m/s, normally you would write:: |
|
2950 | 2953 | |
|
2951 | 2954 | In [1]: v = PhysicalQuantity(3,'m/s') |
|
2952 | 2955 | |
|
2953 | 2956 | Using the PhysicalQ_Input extension this can be input instead as: |
|
2954 | 2957 | In [1]: v = 3 m/s |
|
2955 | 2958 | which is much more convenient for interactive use (even though it is |
|
2956 | 2959 | blatantly invalid Python syntax). |
|
2957 | 2960 | |
|
2958 | 2961 | The physics profile supplied with IPython (enabled via 'ipython -p |
|
2959 | 2962 | physics') uses these extensions, which you can also activate with: |
|
2960 | 2963 | |
|
2961 | 2964 | from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
2962 | 2965 | from IPython.Extensions.PhysicalQInteractive import * |
|
2963 | 2966 | import IPython.Extensions.PhysicalQInput |
|
2964 | 2967 | |
|
2965 | 2968 | |
|
2966 | 2969 | Threading support |
|
2967 | 2970 | ================= |
|
2968 | 2971 | |
|
2969 | 2972 | WARNING: The threading support is still somewhat experimental, and it |
|
2970 | 2973 | has only seen reasonable testing under Linux. Threaded code is |
|
2971 | 2974 | particularly tricky to debug, and it tends to show extremely |
|
2972 | 2975 | platform-dependent behavior. Since I only have access to Linux machines, |
|
2973 | 2976 | I will have to rely on user's experiences and assistance for this area |
|
2974 | 2977 | of IPython to improve under other platforms. |
|
2975 | 2978 | |
|
2976 | 2979 | IPython, via the -gthread , -qthread, -q4thread and -wthread options |
|
2977 | 2980 | (described in Sec. `Threading options`_), can run in |
|
2978 | 2981 | multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications |
|
2979 | 2982 | respectively. These GUI toolkits need to control the python main loop of |
|
2980 | 2983 | execution, so under a normal Python interpreter, starting a pyGTK, Qt3, |
|
2981 | 2984 | Qt4 or WXPython application will immediately freeze the shell. |
|
2982 | 2985 | |
|
2983 | 2986 | IPython, with one of these options (you can only use one at a time), |
|
2984 | 2987 | separates the graphical loop and IPython's code execution run into |
|
2985 | 2988 | different threads. This allows you to test interactively (with %run, for |
|
2986 | 2989 | example) your GUI code without blocking. |
|
2987 | 2990 | |
|
2988 | 2991 | A nice mini-tutorial on using IPython along with the Qt Designer |
|
2989 | 2992 | application is available at the SciPy wiki: |
|
2990 | 2993 | http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer. |
|
2991 | 2994 | |
|
2992 | 2995 | |
|
2993 | 2996 | Tk issues |
|
2994 | 2997 | --------- |
|
2995 | 2998 | |
|
2996 | 2999 | As indicated in Sec. `Threading options`_, a special -tk option is |
|
2997 | 3000 | provided to try and allow Tk graphical applications to coexist |
|
2998 | 3001 | interactively with WX, Qt or GTK ones. Whether this works at all, |
|
2999 | 3002 | however, is very platform and configuration dependent. Please |
|
3000 | 3003 | experiment with simple test cases before committing to using this |
|
3001 | 3004 | combination of Tk and GTK/Qt/WX threading in a production environment. |
|
3002 | 3005 | |
|
3003 | 3006 | |
|
3004 | 3007 | I/O pitfalls |
|
3005 | 3008 | ------------ |
|
3006 | 3009 | |
|
3007 | 3010 | Be mindful that the Python interpreter switches between threads every |
|
3008 | 3011 | $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This |
|
3009 | 3012 | value can be read by using the sys.getcheckinterval() function, and it |
|
3010 | 3013 | can be reset via sys.setcheckinterval(N). This switching of threads can |
|
3011 | 3014 | cause subtly confusing effects if one of your threads is doing file I/O. |
|
3012 | 3015 | In text mode, most systems only flush file buffers when they encounter a |
|
3013 | 3016 | '\n'. An instruction as simple as:: |
|
3014 | 3017 | |
|
3015 | 3018 | print >> filehandle, ''hello world'' |
|
3016 | 3019 | |
|
3017 | 3020 | actually consists of several bytecodes, so it is possible that the |
|
3018 | 3021 | newline does not reach your file before the next thread switch. |
|
3019 | 3022 | Similarly, if you are writing to a file in binary mode, the file won't |
|
3020 | 3023 | be flushed until the buffer fills, and your other thread may see |
|
3021 | 3024 | apparently truncated files. |
|
3022 | 3025 | |
|
3023 | 3026 | For this reason, if you are using IPython's thread support and have (for |
|
3024 | 3027 | example) a GUI application which will read data generated by files |
|
3025 | 3028 | written to from the IPython thread, the safest approach is to open all |
|
3026 | 3029 | of your files in unbuffered mode (the third argument to the file/open |
|
3027 | 3030 | function is the buffering value):: |
|
3028 | 3031 | |
|
3029 | 3032 | filehandle = open(filename,mode,0) |
|
3030 | 3033 | |
|
3031 | 3034 | This is obviously a brute force way of avoiding race conditions with the |
|
3032 | 3035 | file buffering. If you want to do it cleanly, and you have a resource |
|
3033 | 3036 | which is being shared by the interactive IPython loop and your GUI |
|
3034 | 3037 | thread, you should really handle it with thread locking and |
|
3035 | 3038 | syncrhonization properties. The Python documentation discusses these. |
|
3036 | 3039 | |
|
3037 |
.. _ |
|
|
3040 | .. _interactive_demos: | |
|
3038 | 3041 | |
|
3039 | 3042 | Interactive demos with IPython |
|
3040 | 3043 | ============================== |
|
3041 | 3044 | |
|
3042 | 3045 | IPython ships with a basic system for running scripts interactively in |
|
3043 | 3046 | sections, useful when presenting code to audiences. A few tags embedded |
|
3044 | 3047 | in comments (so that the script remains valid Python code) divide a file |
|
3045 | 3048 | into separate blocks, and the demo can be run one block at a time, with |
|
3046 | 3049 | IPython printing (with syntax highlighting) the block before executing |
|
3047 | 3050 | it, and returning to the interactive prompt after each block. The |
|
3048 | 3051 | interactive namespace is updated after each block is run with the |
|
3049 | 3052 | contents of the demo's namespace. |
|
3050 | 3053 | |
|
3051 | 3054 | This allows you to show a piece of code, run it and then execute |
|
3052 | 3055 | interactively commands based on the variables just created. Once you |
|
3053 | 3056 | want to continue, you simply execute the next block of the demo. The |
|
3054 | 3057 | following listing shows the markup necessary for dividing a script into |
|
3055 | 3058 | sections for execution as a demo:: |
|
3056 | 3059 | |
|
3057 | 3060 | |
|
3058 | 3061 | """A simple interactive demo to illustrate the use of IPython's Demo class. |
|
3059 | 3062 | |
|
3060 | 3063 | Any python script can be run as a demo, but that does little more than showing |
|
3061 | 3064 | it on-screen, syntax-highlighted in one shot. If you add a little simple |
|
3062 | 3065 | markup, you can stop at specified intervals and return to the ipython prompt, |
|
3063 | 3066 | resuming execution later. |
|
3064 | 3067 | """ |
|
3065 | 3068 | |
|
3066 | 3069 | print 'Hello, welcome to an interactive IPython demo.' |
|
3067 | 3070 | print 'Executing this block should require confirmation before proceeding,' |
|
3068 | 3071 | print 'unless auto_all has been set to true in the demo object' |
|
3069 | 3072 | |
|
3070 | 3073 | # The mark below defines a block boundary, which is a point where IPython will |
|
3071 | 3074 | # stop execution and return to the interactive prompt. |
|
3072 | 3075 | # Note that in actual interactive execution, |
|
3073 | 3076 | # <demo> --- stop --- |
|
3074 | 3077 | |
|
3075 | 3078 | x = 1 |
|
3076 | 3079 | y = 2 |
|
3077 | 3080 | |
|
3078 | 3081 | # <demo> --- stop --- |
|
3079 | 3082 | |
|
3080 | 3083 | # the mark below makes this block as silent |
|
3081 | 3084 | # <demo> silent |
|
3082 | 3085 | |
|
3083 | 3086 | print 'This is a silent block, which gets executed but not printed.' |
|
3084 | 3087 | |
|
3085 | 3088 | # <demo> --- stop --- |
|
3086 | 3089 | # <demo> auto |
|
3087 | 3090 | print 'This is an automatic block.' |
|
3088 | 3091 | print 'It is executed without asking for confirmation, but printed.' |
|
3089 | 3092 | z = x+y |
|
3090 | 3093 | |
|
3091 | 3094 | print 'z=',x |
|
3092 | 3095 | |
|
3093 | 3096 | # <demo> --- stop --- |
|
3094 | 3097 | # This is just another normal block. |
|
3095 | 3098 | print 'z is now:', z |
|
3096 | 3099 | |
|
3097 | 3100 | print 'bye!' |
|
3098 | 3101 | |
|
3099 | 3102 | In order to run a file as a demo, you must first make a Demo object out |
|
3100 | 3103 | of it. If the file is named myscript.py, the following code will make a |
|
3101 | 3104 | demo:: |
|
3102 | 3105 | |
|
3103 | 3106 | from IPython.demo import Demo |
|
3104 | 3107 | |
|
3105 | 3108 | mydemo = Demo('myscript.py') |
|
3106 | 3109 | |
|
3107 | 3110 | This creates the mydemo object, whose blocks you run one at a time by |
|
3108 | 3111 | simply calling the object with no arguments. If you have autocall active |
|
3109 | 3112 | in IPython (the default), all you need to do is type:: |
|
3110 | 3113 | |
|
3111 | 3114 | mydemo |
|
3112 | 3115 | |
|
3113 | 3116 | and IPython will call it, executing each block. Demo objects can be |
|
3114 | 3117 | restarted, you can move forward or back skipping blocks, re-execute the |
|
3115 | 3118 | last block, etc. Simply use the Tab key on a demo object to see its |
|
3116 | 3119 | methods, and call '?' on them to see their docstrings for more usage |
|
3117 | 3120 | details. In addition, the demo module itself contains a comprehensive |
|
3118 | 3121 | docstring, which you can access via:: |
|
3119 | 3122 | |
|
3120 | 3123 | from IPython import demo |
|
3121 | 3124 | |
|
3122 | 3125 | demo? |
|
3123 | 3126 | |
|
3124 | 3127 | Limitations: It is important to note that these demos are limited to |
|
3125 | 3128 | fairly simple uses. In particular, you can not put division marks in |
|
3126 | 3129 | indented code (loops, if statements, function definitions, etc.) |
|
3127 | 3130 | Supporting something like this would basically require tracking the |
|
3128 | 3131 | internal execution state of the Python interpreter, so only top-level |
|
3129 | 3132 | divisions are allowed. If you want to be able to open an IPython |
|
3130 | 3133 | instance at an arbitrary point in a program, you can use IPython's |
|
3131 | 3134 | embedding facilities, described in detail in Sec. 9 |
|
3132 | 3135 | |
|
3133 | 3136 | |
|
3134 | 3137 | .. _Matplotlib support: |
|
3135 | 3138 | |
|
3136 | 3139 | Plotting with matplotlib |
|
3137 | 3140 | ======================== |
|
3138 | 3141 | |
|
3139 | 3142 | The matplotlib library (http://matplotlib.sourceforge.net |
|
3140 | 3143 | http://matplotlib.sourceforge.net) provides high quality 2D plotting for |
|
3141 | 3144 | Python. Matplotlib can produce plots on screen using a variety of GUI |
|
3142 | 3145 | toolkits, including Tk, GTK and WXPython. It also provides a number of |
|
3143 | 3146 | commands useful for scientific computing, all with a syntax compatible |
|
3144 | 3147 | with that of the popular Matlab program. |
|
3145 | 3148 | |
|
3146 |
IPython accepts the special option -pylab ( |
|
|
3147 |
options` |
|
|
3148 | settings in the .matplotlibrc file. IPython will detect the user's | |
|
3149 |
|
|
|
3150 |
|
|
|
3151 | interactive mode and modifies %run slightly, so that any | |
|
3152 | matplotlib-based script can be executed using %run and the final | |
|
3153 | show() command does not block the interactive shell. | |
|
3154 | ||
|
3155 | The -pylab option must be given first in order for IPython to | |
|
3156 | configure its threading mode. However, you can still issue other | |
|
3157 | options afterwards. This allows you to have a matplotlib-based | |
|
3158 | environment customized with additional modules using the standard | |
|
3159 | IPython profile mechanism (Sec. Profiles_): ''ipython -pylab -p | |
|
3160 | myprofile'' will load the profile defined in ipythonrc-myprofile after | |
|
3161 | configuring matplotlib. | |
|
3162 | ||
|
3163 | ||
|
3149 | IPython accepts the special option -pylab (see :ref:`here | |
|
3150 | <command_line_options>`). This configures it to support matplotlib, honoring | |
|
3151 | the settings in the .matplotlibrc file. IPython will detect the user's choice | |
|
3152 | of matplotlib GUI backend, and automatically select the proper threading model | |
|
3153 | to prevent blocking. It also sets matplotlib in interactive mode and modifies | |
|
3154 | %run slightly, so that any matplotlib-based script can be executed using %run | |
|
3155 | and the final show() command does not block the interactive shell. | |
|
3156 | ||
|
3157 | The -pylab option must be given first in order for IPython to configure its | |
|
3158 | threading mode. However, you can still issue other options afterwards. This | |
|
3159 | allows you to have a matplotlib-based environment customized with additional | |
|
3160 | modules using the standard IPython profile mechanism (see :ref:`here | |
|
3161 | <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in | |
|
3162 | ipythonrc-myprofile after configuring matplotlib. |
@@ -1,315 +1,317 b'' | |||
|
1 | 1 | .. _tutorial: |
|
2 | 2 | |
|
3 | 3 | ====================== |
|
4 | 4 | Quick IPython tutorial |
|
5 | 5 | ====================== |
|
6 | 6 | |
|
7 | 7 | .. contents:: |
|
8 | 8 | |
|
9 | 9 | IPython can be used as an improved replacement for the Python prompt, |
|
10 | 10 | and for that you don't really need to read any more of this manual. But |
|
11 | 11 | in this section we'll try to summarize a few tips on how to make the |
|
12 | 12 | most effective use of it for everyday Python development, highlighting |
|
13 | 13 | things you might miss in the rest of the manual (which is getting long). |
|
14 | 14 | We'll give references to parts in the manual which provide more detail |
|
15 | 15 | when appropriate. |
|
16 | 16 | |
|
17 | 17 | The following article by Jeremy Jones provides an introductory tutorial |
|
18 | 18 | about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html |
|
19 | 19 | |
|
20 | 20 | Highlights |
|
21 | 21 | ========== |
|
22 | 22 | |
|
23 | 23 | Tab completion |
|
24 | 24 | -------------- |
|
25 | 25 | |
|
26 | 26 | TAB-completion, especially for attributes, is a convenient way to explore the |
|
27 | structure of any object you're dealing with. Simply type object_name.<TAB> | |
|
28 |
|
|
|
29 |
more). Tab completion also works on file and directory |
|
|
30 |
with IPython's alias system allows you to do from within |
|
|
31 | things you normally would need the system shell for. | |
|
27 | structure of any object you're dealing with. Simply type object_name.<TAB> and | |
|
28 | a list of the object's attributes will be printed (see :ref:`the readline | |
|
29 | section <readline>` for more). Tab completion also works on file and directory | |
|
30 | names, which combined with IPython's alias system allows you to do from within | |
|
31 | IPython many of the things you normally would need the system shell for. | |
|
32 | 32 | |
|
33 | 33 | Explore your objects |
|
34 | 34 | -------------------- |
|
35 | 35 | |
|
36 | 36 | Typing object_name? will print all sorts of details about any object, |
|
37 | 37 | including docstrings, function definition lines (for call arguments) and |
|
38 | 38 | constructor details for classes. The magic commands %pdoc, %pdef, %psource |
|
39 | 39 | and %pfile will respectively print the docstring, function definition line, |
|
40 | 40 | full source code and the complete file for any object (when they can be |
|
41 | 41 | found). If automagic is on (it is by default), you don't need to type the '%' |
|
42 |
explicitly. See |
|
|
42 | explicitly. See :ref:`this section <dynamic_object_info>` for more. | |
|
43 | 43 | |
|
44 | 44 | The `%run` magic command |
|
45 | 45 | ------------------------ |
|
46 | 46 | |
|
47 | The %run magic command allows you to run any python script and load all of | |
|
48 |
|
|
|
49 |
|
|
|
50 |
|
|
|
51 |
|
|
|
52 |
|
|
|
53 |
|
|
|
47 | The %run magic command allows you to run any python script and load all of its | |
|
48 | data directly into the interactive namespace. Since the file is re-read from | |
|
49 | disk each time, changes you make to it are reflected immediately (in contrast | |
|
50 | to the behavior of import). I rarely use import for code I am testing, relying | |
|
51 | on %run instead. See :ref:`this section <magic>` for more on this and other | |
|
52 | magic commands, or type the name of any magic command and ? to get details on | |
|
53 | it. See also :ref:`this section <dreload>` for a recursive reload command. %run | |
|
54 | 54 | also has special flags for timing the execution of your scripts (-t) and for |
|
55 | 55 | executing them under the control of either Python's pdb debugger (-d) or |
|
56 | 56 | profiler (-p). With all of these, %run can be used as the main tool for |
|
57 | 57 | efficient interactive development of code which you write in your editor of |
|
58 | 58 | choice. |
|
59 | 59 | |
|
60 | 60 | Debug a Python script |
|
61 | 61 | --------------------- |
|
62 | 62 | |
|
63 | Use the Python debugger, pdb. The %pdb command allows you to toggle on and | |
|
64 |
|
|
|
65 |
|
|
|
66 |
|
|
|
67 |
|
|
|
68 |
|
|
|
69 |
|
|
|
70 |
|
|
|
71 |
|
|
|
72 |
|
|
|
73 |
|
|
|
74 |
|
|
|
75 | the 1/0. Note also that '%run -d' activates pdb and automatically sets | |
|
76 | initial breakpoints for you to step through your code, watch variables, etc. | |
|
77 |
|
|
|
63 | Use the Python debugger, pdb. The %pdb command allows you to toggle on and off | |
|
64 | the automatic invocation of an IPython-enhanced pdb debugger (with coloring, | |
|
65 | tab completion and more) at any uncaught exception. The advantage of this is | |
|
66 | that pdb starts inside the function where the exception occurred, with all data | |
|
67 | still available. You can print variables, see code, execute statements and even | |
|
68 | walk up and down the call stack to track down the true source of the problem | |
|
69 | (which often is many layers in the stack above where the exception gets | |
|
70 | triggered). Running programs with %run and pdb active can be an efficient to | |
|
71 | develop and debug code, in many cases eliminating the need for print statements | |
|
72 | or external debugging tools. I often simply put a 1/0 in a place where I want | |
|
73 | to take a look so that pdb gets called, quickly view whatever variables I need | |
|
74 | to or test various pieces of code and then remove the 1/0. Note also that '%run | |
|
75 | -d' activates pdb and automatically sets initial breakpoints for you to step | |
|
76 | through your code, watch variables, etc. The :ref:`output caching section | |
|
77 | <output_caching>` has more details. | |
|
78 | 78 | |
|
79 | 79 | Use the output cache |
|
80 | 80 | -------------------- |
|
81 | 81 | |
|
82 | 82 | All output results are automatically stored in a global dictionary named Out |
|
83 | 83 | and variables named _1, _2, etc. alias them. For example, the result of input |
|
84 | 84 | line 4 is available either as Out[4] or as _4. Additionally, three variables |
|
85 | 85 | named _, __ and ___ are always kept updated with the for the last three |
|
86 | 86 | results. This allows you to recall any previous result and further use it for |
|
87 |
new calculations. See |
|
|
87 | new calculations. See :ref:`the output caching section <output_caching>` for | |
|
88 | more. | |
|
88 | 89 | |
|
89 | 90 | Suppress output |
|
90 | 91 | --------------- |
|
91 | 92 | |
|
92 | 93 | Put a ';' at the end of a line to suppress the printing of output. This is |
|
93 | 94 | useful when doing calculations which generate long output you are not |
|
94 | 95 | interested in seeing. The _* variables and the Out[] list do get updated with |
|
95 | 96 | the contents of the output, even if it is not printed. You can thus still |
|
96 | 97 | access the generated results this way for further processing. |
|
97 | 98 | |
|
98 | 99 | Input cache |
|
99 | 100 | ----------- |
|
100 | 101 | |
|
101 | 102 | A similar system exists for caching input. All input is stored in a global |
|
102 | 103 | list called In , so you can re-execute lines 22 through 28 plus line 34 by |
|
103 | 104 | typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need |
|
104 | 105 | to execute the same set of lines often, you can assign them to a macro with |
|
105 |
the %macro function. See |
|
|
106 | the %macro function. See :ref:`here <input_caching>` for more. | |
|
106 | 107 | |
|
107 | 108 | Use your input history |
|
108 | 109 | ---------------------- |
|
109 | 110 | |
|
110 | 111 | The %hist command can show you all previous input, without line numbers if |
|
111 | 112 | desired (option -n) so you can directly copy and paste code either back in |
|
112 | 113 | IPython or in a text editor. You can also save all your history by turning on |
|
113 | 114 | logging via %logstart; these logs can later be either reloaded as IPython |
|
114 | 115 | sessions or used as code for your programs. |
|
115 | 116 | |
|
116 | 117 | Define your own system aliases |
|
117 | 118 | ------------------------------ |
|
118 | 119 | |
|
119 | 120 | Even though IPython gives you access to your system shell via the ! prefix, |
|
120 | 121 | it is convenient to have aliases to the system commands you use most often. |
|
121 | 122 | This allows you to work seamlessly from inside IPython with the same commands |
|
122 | 123 | you are used to in your system shell. IPython comes with some pre-defined |
|
123 | 124 | aliases and a complete system for changing directories, both via a stack (see |
|
124 | 125 | %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of |
|
125 | 126 | visited directories and allows you to go to any previously visited one. |
|
126 | 127 | |
|
127 | 128 | Call system shell commands |
|
128 | 129 | -------------------------- |
|
129 | 130 | |
|
130 | 131 | Use Python to manipulate the results of system commands. The '!!' special |
|
131 | 132 | syntax, and the %sc and %sx magic commands allow you to capture system output |
|
132 | 133 | into Python variables. |
|
133 | 134 | |
|
134 | 135 | Use Python variables when calling the shell |
|
135 | 136 | ------------------------------------------- |
|
136 | 137 | |
|
137 | Expand python variables when calling the shell (either via '!' and '!!' or | |
|
138 |
|
|
|
139 |
python expressions. See |
|
|
138 | Expand python variables when calling the shell (either via '!' and '!!' or via | |
|
139 | aliases) by prepending a $ in front of them. You can also expand complete | |
|
140 | python expressions. See :ref:`our shell section <system_shell_access>` for | |
|
141 | more details. | |
|
140 | 142 | |
|
141 | 143 | Use profiles |
|
142 | 144 | ------------ |
|
143 | 145 | |
|
144 | 146 | Use profiles to maintain different configurations (modules to load, function |
|
145 | 147 | definitions, option settings) for particular tasks. You can then have |
|
146 |
customized versions of IPython for specific purposes. |
|
|
147 | more. | |
|
148 | customized versions of IPython for specific purposes. :ref:`This section | |
|
149 | <profiles>` has more details. | |
|
148 | 150 | |
|
149 | 151 | |
|
150 | 152 | Embed IPython in your programs |
|
151 | 153 | ------------------------------ |
|
152 | 154 | |
|
153 | 155 | A few lines of code are enough to load a complete IPython inside your own |
|
154 | 156 | programs, giving you the ability to work with your data interactively after |
|
155 |
automatic processing has been completed. See |
|
|
157 | automatic processing has been completed. See :ref:`here <embedding>` for more. | |
|
156 | 158 | |
|
157 | 159 | Use the Python profiler |
|
158 | 160 | ----------------------- |
|
159 | 161 | |
|
160 | 162 | When dealing with performance issues, the %run command with a -p option |
|
161 | 163 | allows you to run complete programs under the control of the Python profiler. |
|
162 | 164 | The %prun command does a similar job for single Python expressions (like |
|
163 | 165 | function calls). |
|
164 | 166 | |
|
165 | 167 | Use IPython to present interactive demos |
|
166 | 168 | ---------------------------------------- |
|
167 | 169 | |
|
168 | 170 | Use the IPython.demo.Demo class to load any Python script as an interactive |
|
169 | demo. With a minimal amount of simple markup, you can control the execution | |
|
170 |
|
|
|
171 | demo. With a minimal amount of simple markup, you can control the execution of | |
|
172 | the script, stopping as needed. See :ref:`here <interactive_demos>` for more. | |
|
171 | 173 | |
|
172 | 174 | Run doctests |
|
173 | 175 | ------------ |
|
174 | 176 | |
|
175 | 177 | Run your doctests from within IPython for development and debugging. The |
|
176 | 178 | special %doctest_mode command toggles a mode where the prompt, output and |
|
177 | 179 | exceptions display matches as closely as possible that of the default Python |
|
178 | 180 | interpreter. In addition, this mode allows you to directly paste in code that |
|
179 | 181 | contains leading '>>>' prompts, even if they have extra leading whitespace |
|
180 | 182 | (as is common in doctest files). This combined with the '%history -tn' call |
|
181 | 183 | to see your translated history (with these extra prompts removed and no line |
|
182 | 184 | numbers) allows for an easy doctest workflow, where you can go from doctest |
|
183 | 185 | to interactive execution to pasting into valid Python code as needed. |
|
184 | 186 | |
|
185 | 187 | Source code handling tips |
|
186 | 188 | ========================= |
|
187 | 189 | |
|
188 | 190 | IPython is a line-oriented program, without full control of the |
|
189 | 191 | terminal. Therefore, it doesn't support true multiline editing. However, |
|
190 | 192 | it has a number of useful tools to help you in dealing effectively with |
|
191 | 193 | more complex editing. |
|
192 | 194 | |
|
193 | 195 | The %edit command gives a reasonable approximation of multiline editing, |
|
194 | 196 | by invoking your favorite editor on the spot. IPython will execute the |
|
195 | 197 | code you type in there as if it were typed interactively. Type %edit? |
|
196 | 198 | for the full details on the edit command. |
|
197 | 199 | |
|
198 | 200 | If you have typed various commands during a session, which you'd like to |
|
199 | 201 | reuse, IPython provides you with a number of tools. Start by using %hist |
|
200 | 202 | to see your input history, so you can see the line numbers of all input. |
|
201 | 203 | Let us say that you'd like to reuse lines 10 through 20, plus lines 24 |
|
202 | 204 | and 28. All the commands below can operate on these with the syntax:: |
|
203 | 205 | |
|
204 | 206 | %command 10-20 24 28 |
|
205 | 207 | |
|
206 | 208 | where the command given can be: |
|
207 | 209 | |
|
208 | 210 | * %macro <macroname>: this stores the lines into a variable which, |
|
209 | 211 | when called at the prompt, re-executes the input. Macros can be |
|
210 | 212 | edited later using '%edit macroname', and they can be stored |
|
211 | 213 | persistently across sessions with '%store macroname' (the storage |
|
212 | 214 | system is per-profile). The combination of quick macros, |
|
213 | 215 | persistent storage and editing, allows you to easily refine |
|
214 | 216 | quick-and-dirty interactive input into permanent utilities, always |
|
215 | 217 | available both in IPython and as files for general reuse. |
|
216 | 218 | * %edit: this will open a text editor with those lines pre-loaded |
|
217 | 219 | for further modification. It will then execute the resulting |
|
218 | 220 | file's contents as if you had typed it at the prompt. |
|
219 | 221 | * %save <filename>: this saves the lines directly to a named file on |
|
220 | 222 | disk. |
|
221 | 223 | |
|
222 | 224 | While %macro saves input lines into memory for interactive re-execution, |
|
223 | 225 | sometimes you'd like to save your input directly to a file. The %save |
|
224 | 226 | magic does this: its input sytnax is the same as %macro, but it saves |
|
225 | 227 | your input directly to a Python file. Note that the %logstart command |
|
226 | 228 | also saves input, but it logs all input to disk (though you can |
|
227 | 229 | temporarily suspend it and reactivate it with %logoff/%logon); %save |
|
228 | 230 | allows you to select which lines of input you need to save. |
|
229 | 231 | |
|
230 | 232 | |
|
231 | 233 | Lightweight 'version control' |
|
232 | 234 | ============================= |
|
233 | 235 | |
|
234 | 236 | When you call %edit with no arguments, IPython opens an empty editor |
|
235 | 237 | with a temporary file, and it returns the contents of your editing |
|
236 | 238 | session as a string variable. Thanks to IPython's output caching |
|
237 | 239 | mechanism, this is automatically stored:: |
|
238 | 240 | |
|
239 | 241 | In [1]: %edit |
|
240 | 242 | |
|
241 | 243 | IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py |
|
242 | 244 | |
|
243 | 245 | Editing... done. Executing edited code... |
|
244 | 246 | |
|
245 | 247 | hello - this is a temporary file |
|
246 | 248 | |
|
247 | 249 | Out[1]: "print 'hello - this is a temporary file'\n" |
|
248 | 250 | |
|
249 | 251 | Now, if you call '%edit -p', IPython tries to open an editor with the |
|
250 | 252 | same data as the last time you used %edit. So if you haven't used %edit |
|
251 | 253 | in the meantime, this same contents will reopen; however, it will be |
|
252 | 254 | done in a new file. This means that if you make changes and you later |
|
253 | 255 | want to find an old version, you can always retrieve it by using its |
|
254 | 256 | output number, via '%edit _NN', where NN is the number of the output |
|
255 | 257 | prompt. |
|
256 | 258 | |
|
257 | 259 | Continuing with the example above, this should illustrate this idea:: |
|
258 | 260 | |
|
259 | 261 | In [2]: edit -p |
|
260 | 262 | |
|
261 | 263 | IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py |
|
262 | 264 | |
|
263 | 265 | Editing... done. Executing edited code... |
|
264 | 266 | |
|
265 | 267 | hello - now I made some changes |
|
266 | 268 | |
|
267 | 269 | Out[2]: "print 'hello - now I made some changes'\n" |
|
268 | 270 | |
|
269 | 271 | In [3]: edit _1 |
|
270 | 272 | |
|
271 | 273 | IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py |
|
272 | 274 | |
|
273 | 275 | Editing... done. Executing edited code... |
|
274 | 276 | |
|
275 | 277 | hello - this is a temporary file |
|
276 | 278 | |
|
277 | 279 | IPython version control at work :) |
|
278 | 280 | |
|
279 | 281 | Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n" |
|
280 | 282 | |
|
281 | 283 | |
|
282 | 284 | This section was written after a contribution by Alexander Belchenko on |
|
283 | 285 | the IPython user list. |
|
284 | 286 | |
|
285 | 287 | |
|
286 | 288 | Effective logging |
|
287 | 289 | ================= |
|
288 | 290 | |
|
289 | 291 | A very useful suggestion sent in by Robert Kern follows: |
|
290 | 292 | |
|
291 | 293 | I recently happened on a nifty way to keep tidy per-project log files. I |
|
292 | 294 | made a profile for my project (which is called "parkfield"):: |
|
293 | 295 | |
|
294 | 296 | include ipythonrc |
|
295 | 297 | |
|
296 | 298 | # cancel earlier logfile invocation: |
|
297 | 299 | |
|
298 | 300 | logfile '' |
|
299 | 301 | |
|
300 | 302 | execute import time |
|
301 | 303 | |
|
302 | 304 | execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate' |
|
303 | 305 | |
|
304 | 306 | execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d')) |
|
305 | 307 | |
|
306 | 308 | I also added a shell alias for convenience:: |
|
307 | 309 | |
|
308 | 310 | alias parkfield="ipython -pylab -profile parkfield" |
|
309 | 311 | |
|
310 | 312 | Now I have a nice little directory with everything I ever type in, |
|
311 | 313 | organized by project and date. |
|
312 | 314 | |
|
313 | 315 | Contribute your own: If you have your own favorite tip on using IPython |
|
314 | 316 | efficiently for a certain task (especially things which can't be done in |
|
315 | 317 | the normal Python interpreter), don't hesitate to send it! |
@@ -1,61 +1,87 b'' | |||
|
1 | 1 | .. _license: |
|
2 | 2 | |
|
3 |
===================== |
|
|
4 |
License and Copyright |
|
|
5 |
===================== |
|
|
3 | ===================== | |
|
4 | License and Copyright | |
|
5 | ===================== | |
|
6 | 6 | |
|
7 | This files needs to be updated to reflect what the new COPYING.txt files says about our license and copyright! | |
|
7 | License | |
|
8 | ======= | |
|
8 | 9 | |
|
9 |
IPython is |
|
|
10 | form can be found at: http://www.opensource.org/licenses/bsd-license.php. The full text of the | |
|
11 | IPython license is reproduced below:: | |
|
10 | IPython is licensed under the terms of the new or revised BSD license, as follows:: | |
|
12 | 11 | |
|
13 | IPython is released under a BSD-type license. | |
|
12 | Copyright (c) 2008, IPython Development Team | |
|
14 | 13 | |
|
15 | Copyright (c) 2001, 2002, 2003, 2004 Fernando Perez | |
|
16 | <fperez@colorado.edu>. | |
|
14 | All rights reserved. | |
|
17 | 15 | |
|
18 | Copyright (c) 2001 Janko Hauser <jhauser@zscout.de> and | |
|
19 | Nathaniel Gray <n8gray@caltech.edu>. | |
|
16 | Redistribution and use in source and binary forms, with or without modification, | |
|
17 | are permitted provided that the following conditions are met: | |
|
20 | 18 | |
|
21 | All rights reserved. | |
|
19 | Redistributions of source code must retain the above copyright notice, this list of | |
|
20 | conditions and the following disclaimer. | |
|
21 | ||
|
22 | Redistributions in binary form must reproduce the above copyright notice, this list | |
|
23 | of conditions and the following disclaimer in the documentation and/or other | |
|
24 | materials provided with the distribution. | |
|
25 | ||
|
26 | Neither the name of the IPython Development Team nor the names of its contributors | |
|
27 | may be used to endorse or promote products derived from this software without | |
|
28 | specific prior written permission. | |
|
29 | ||
|
30 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY | |
|
31 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | |
|
32 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. | |
|
33 | IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, | |
|
34 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT | |
|
35 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | |
|
36 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, | |
|
37 | WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) | |
|
38 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
|
39 | POSSIBILITY OF SUCH DAMAGE. | |
|
40 | ||
|
41 | About the IPython Development Team | |
|
42 | ================================== | |
|
43 | ||
|
44 | Fernando Perez began IPython in 2001 based on code from Janko Hauser <jhauser@zscout.de> | |
|
45 | and Nathaniel Gray <n8gray@caltech.edu>. Fernando is still the project lead. | |
|
46 | ||
|
47 | The IPython Development Team is the set of all contributors to the IPython project. | |
|
48 | This includes all of the IPython subprojects. Here is a list of the currently active contributors: | |
|
49 | ||
|
50 | * Matthieu Brucher | |
|
51 | * Ondrej Certik | |
|
52 | * Laurent Dufrechou | |
|
53 | * Robert Kern | |
|
54 | * Brian E. Granger | |
|
55 | * Fernando Perez (project leader) | |
|
56 | * Benjamin Ragan-Kelley | |
|
57 | * Ville M. Vainio | |
|
58 | * Gael Varoququx | |
|
59 | * Stefan van der Walt | |
|
60 | * Tech-X Corporation | |
|
61 | * Barry Wark | |
|
62 | ||
|
63 | If your name is missing, please add it. | |
|
64 | ||
|
65 | Our Copyright Policy | |
|
66 | ==================== | |
|
67 | ||
|
68 | IPython uses a shared copyright model. Each contributor maintains copyright over | |
|
69 | their contributions to IPython. But, it is important to note that these | |
|
70 | contributions are typically only changes to the repositories. Thus, the IPython | |
|
71 | source code, in its entirety is not the copyright of any single person or | |
|
72 | institution. Instead, it is the collective copyright of the entire IPython | |
|
73 | Development Team. If individual contributors want to maintain a record of what | |
|
74 | changes/contributions they have specific copyright on, they should indicate their | |
|
75 | copyright in the commit message of the change, when they commit the change to | |
|
76 | one of the IPython repositories. | |
|
22 | 77 | |
|
23 | Redistribution and use in source and binary forms, with or without | |
|
24 | modification, are permitted provided that the following conditions | |
|
25 | are met: | |
|
26 | ||
|
27 | a. Redistributions of source code must retain the above copyright | |
|
28 | notice, this list of conditions and the following disclaimer. | |
|
29 | ||
|
30 | b. Redistributions in binary form must reproduce the above copyright | |
|
31 | notice, this list of conditions and the following disclaimer in the | |
|
32 | documentation and/or other materials provided with the distribution. | |
|
33 | ||
|
34 | c. Neither the name of the copyright holders nor the names of any | |
|
35 | contributors to this software may be used to endorse or promote | |
|
36 | products derived from this software without specific prior written | |
|
37 | permission. | |
|
38 | ||
|
39 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
|
40 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
|
41 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS | |
|
42 | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE | |
|
43 | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, | |
|
44 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, | |
|
45 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |
|
46 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | |
|
47 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | |
|
48 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN | |
|
49 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | |
|
50 | POSSIBILITY OF SUCH DAMAGE. | |
|
51 | ||
|
52 | Individual authors are the holders of the copyright for their code and | |
|
53 | are listed in each file. | |
|
78 | Miscellaneous | |
|
79 | ============= | |
|
54 | 80 | |
|
55 | 81 | Some files (DPyGetOpt.py, for example) may be licensed under different |
|
56 | 82 | conditions. Ultimately each file indicates clearly the conditions under |
|
57 | 83 | which its author/authors have decided to publish the code. |
|
58 | 84 | |
|
59 | 85 | Versions of IPython up to and including 0.6.3 were released under the |
|
60 | 86 | GNU Lesser General Public License (LGPL), available at |
|
61 | 87 | http://www.gnu.org/copyleft/lesser.html. No newline at end of file |
@@ -1,174 +1,233 b'' | |||
|
1 | 1 | .. _overview: |
|
2 | 2 | |
|
3 | 3 | ============ |
|
4 | 4 | Introduction |
|
5 | 5 | ============ |
|
6 | 6 | |
|
7 | 7 | Overview |
|
8 | 8 | ======== |
|
9 | 9 | |
|
10 | 10 | One of Python's most useful features is its interactive interpreter. |
|
11 | 11 | This system allows very fast testing of ideas without the overhead of |
|
12 | 12 | creating test files as is typical in most programming languages. |
|
13 | 13 | However, the interpreter supplied with the standard Python distribution |
|
14 | 14 | is somewhat limited for extended interactive use. |
|
15 | 15 | |
|
16 | 16 | The goal of IPython is to create a comprehensive environment for |
|
17 | 17 | interactive and exploratory computing. To support, this goal, IPython |
|
18 | 18 | has two main components: |
|
19 | 19 | |
|
20 |
|
|
|
21 |
|
|
|
20 | * An enhanced interactive Python shell. | |
|
21 | * An architecture for interactive parallel computing. | |
|
22 | 22 | |
|
23 | 23 | All of IPython is open source (released under the revised BSD license). |
|
24 | 24 | |
|
25 | 25 | Enhanced interactive Python shell |
|
26 | 26 | ================================= |
|
27 | 27 | |
|
28 |
IPython's interactive shell (`ipython`), has the following goals |
|
|
29 | ||
|
30 | 1. Provide an interactive shell superior to Python's default. IPython | |
|
31 | has many features for object introspection, system shell access, | |
|
32 | and its own special command system for adding functionality when | |
|
33 | working interactively. It tries to be a very efficient environment | |
|
34 | both for Python code development and for exploration of problems | |
|
35 | using Python objects (in situations like data analysis). | |
|
36 | 2. Serve as an embeddable, ready to use interpreter for your own | |
|
37 | programs. IPython can be started with a single call from inside | |
|
38 | another program, providing access to the current namespace. This | |
|
39 | can be very useful both for debugging purposes and for situations | |
|
40 | where a blend of batch-processing and interactive exploration are | |
|
41 | needed. | |
|
42 | 3. Offer a flexible framework which can be used as the base | |
|
43 | environment for other systems with Python as the underlying | |
|
44 | language. Specifically scientific environments like Mathematica, | |
|
45 | IDL and Matlab inspired its design, but similar ideas can be | |
|
46 | useful in many fields. | |
|
47 | 4. Allow interactive testing of threaded graphical toolkits. IPython | |
|
48 | has support for interactive, non-blocking control of GTK, Qt and | |
|
49 | WX applications via special threading flags. The normal Python | |
|
50 | shell can only do this for Tkinter applications. | |
|
28 | IPython's interactive shell (:command:`ipython`), has the following goals, | |
|
29 | amongst others: | |
|
30 | ||
|
31 | 1. Provide an interactive shell superior to Python's default. IPython | |
|
32 | has many features for object introspection, system shell access, | |
|
33 | and its own special command system for adding functionality when | |
|
34 | working interactively. It tries to be a very efficient environment | |
|
35 | both for Python code development and for exploration of problems | |
|
36 | using Python objects (in situations like data analysis). | |
|
37 | ||
|
38 | 2. Serve as an embeddable, ready to use interpreter for your own | |
|
39 | programs. IPython can be started with a single call from inside | |
|
40 | another program, providing access to the current namespace. This | |
|
41 | can be very useful both for debugging purposes and for situations | |
|
42 | where a blend of batch-processing and interactive exploration are | |
|
43 | needed. New in the 0.9 version of IPython is a reusable wxPython | |
|
44 | based IPython widget. | |
|
45 | ||
|
46 | 3. Offer a flexible framework which can be used as the base | |
|
47 | environment for other systems with Python as the underlying | |
|
48 | language. Specifically scientific environments like Mathematica, | |
|
49 | IDL and Matlab inspired its design, but similar ideas can be | |
|
50 | useful in many fields. | |
|
51 | ||
|
52 | 4. Allow interactive testing of threaded graphical toolkits. IPython | |
|
53 | has support for interactive, non-blocking control of GTK, Qt and | |
|
54 | WX applications via special threading flags. The normal Python | |
|
55 | shell can only do this for Tkinter applications. | |
|
51 | 56 | |
|
52 | 57 | Main features of the interactive shell |
|
53 | 58 | -------------------------------------- |
|
54 | 59 | |
|
55 |
|
|
|
56 |
|
|
|
57 |
|
|
|
58 |
|
|
|
59 | * Searching through modules and namespaces with :samp:`*` wildcards, both | |
|
60 | when using the :samp:`?` system and via the :samp:`%psearch` command. | |
|
61 | * Completion in the local namespace, by typing :kbd:`TAB` at the prompt. | |
|
62 | This works for keywords, modules, methods, variables and files in the | |
|
63 | current directory. This is supported via the readline library, and | |
|
64 | full access to configuring readline's behavior is provided. | |
|
65 | Custom completers can be implemented easily for different purposes | |
|
66 | (system commands, magic arguments etc.) | |
|
67 | * Numbered input/output prompts with command history (persistent | |
|
68 | across sessions and tied to each profile), full searching in this | |
|
69 | history and caching of all input and output. | |
|
70 | * User-extensible 'magic' commands. A set of commands prefixed with | |
|
71 | :samp:`%` is available for controlling IPython itself and provides | |
|
72 | directory control, namespace information and many aliases to | |
|
73 | common system shell commands. | |
|
74 | * Alias facility for defining your own system aliases. | |
|
75 | * Complete system shell access. Lines starting with :samp:`!` are passed | |
|
76 | directly to the system shell, and using :samp:`!!` or :samp:`var = !cmd` | |
|
77 | captures shell output into python variables for further use. | |
|
78 | * Background execution of Python commands in a separate thread. | |
|
79 | IPython has an internal job manager called jobs, and a | |
|
80 | conveninence backgrounding magic function called :samp:`%bg`. | |
|
81 | * The ability to expand python variables when calling the system | |
|
82 | shell. In a shell command, any python variable prefixed with :samp:`$` is | |
|
83 | expanded. A double :samp:`$$` allows passing a literal :samp:`$` to the shell (for | |
|
84 | access to shell and environment variables like :envvar:`PATH`). | |
|
85 | * Filesystem navigation, via a magic :samp:`%cd` command, along with a | |
|
86 | persistent bookmark system (using :samp:`%bookmark`) for fast access to | |
|
87 | frequently visited directories. | |
|
88 | * A lightweight persistence framework via the :samp:`%store` command, which | |
|
89 | allows you to save arbitrary Python variables. These get restored | |
|
90 | automatically when your session restarts. | |
|
91 | * Automatic indentation (optional) of code as you type (through the | |
|
92 | readline library). | |
|
93 | * Macro system for quickly re-executing multiple lines of previous | |
|
94 | input with a single name. Macros can be stored persistently via | |
|
95 | :samp:`%store` and edited via :samp:`%edit`. | |
|
96 | * Session logging (you can then later use these logs as code in your | |
|
97 | programs). Logs can optionally timestamp all input, and also store | |
|
98 | session output (marked as comments, so the log remains valid | |
|
99 | Python source code). | |
|
100 | * Session restoring: logs can be replayed to restore a previous | |
|
101 | session to the state where you left it. | |
|
102 | * Verbose and colored exception traceback printouts. Easier to parse | |
|
103 | visually, and in verbose mode they produce a lot of useful | |
|
104 | debugging information (basically a terminal version of the cgitb | |
|
105 | module). | |
|
106 | * Auto-parentheses: callable objects can be executed without | |
|
107 | parentheses: :samp:`sin 3` is automatically converted to :samp:`sin(3)`. | |
|
108 | * Auto-quoting: using :samp:`,`, or :samp:`;` as the first character forces | |
|
109 | auto-quoting of the rest of the line: :samp:`,my_function a b` becomes | |
|
110 | automatically :samp:`my_function("a","b")`, while :samp:`;my_function a b` | |
|
111 | becomes :samp:`my_function("a b")`. | |
|
112 | * Extensible input syntax. You can define filters that pre-process | |
|
113 | user input to simplify input in special situations. This allows | |
|
114 | for example pasting multi-line code fragments which start with | |
|
115 | :samp:`>>>` or :samp:`...` such as those from other python sessions or the | |
|
116 | standard Python documentation. | |
|
117 | * Flexible configuration system. It uses a configuration file which | |
|
118 | allows permanent setting of all command-line options, module | |
|
119 | loading, code and file execution. The system allows recursive file | |
|
120 | inclusion, so you can have a base file with defaults and layers | |
|
121 | which load other customizations for particular projects. | |
|
122 | * Embeddable. You can call IPython as a python shell inside your own | |
|
123 | python programs. This can be used both for debugging code or for | |
|
124 | providing interactive abilities to your programs with knowledge | |
|
125 | about the local namespaces (very useful in debugging and data | |
|
126 | analysis situations). | |
|
127 | * Easy debugger access. You can set IPython to call up an enhanced | |
|
128 | version of the Python debugger (pdb) every time there is an | |
|
129 | uncaught exception. This drops you inside the code which triggered | |
|
130 | the exception with all the data live and it is possible to | |
|
131 | navigate the stack to rapidly isolate the source of a bug. The | |
|
132 | :samp:`%run` magic command (with the :samp:`-d` option) can run any script under | |
|
133 | pdb's control, automatically setting initial breakpoints for you. | |
|
134 | This version of pdb has IPython-specific improvements, including | |
|
135 | tab-completion and traceback coloring support. For even easier | |
|
136 | debugger access, try :samp:`%debug` after seeing an exception. winpdb is | |
|
137 | also supported, see ipy_winpdb extension. | |
|
138 | * Profiler support. You can run single statements (similar to | |
|
139 | :samp:`profile.run()`) or complete programs under the profiler's control. | |
|
140 | While this is possible with standard cProfile or profile modules, | |
|
141 | IPython wraps this functionality with magic commands (see :samp:`%prun` | |
|
142 | and :samp:`%run -p`) convenient for rapid interactive work. | |
|
143 | * Doctest support. The special :samp:`%doctest_mode` command toggles a mode | |
|
144 | that allows you to paste existing doctests (with leading :samp:`>>>` | |
|
145 | prompts and whitespace) and uses doctest-compatible prompts and | |
|
146 | output, so you can use IPython sessions as doctest code. | |
|
60 | * Dynamic object introspection. One can access docstrings, function | |
|
61 | definition prototypes, source code, source files and other details | |
|
62 | of any object accessible to the interpreter with a single | |
|
63 | keystroke (:samp:`?`, and using :samp:`??` provides additional detail). | |
|
64 | ||
|
65 | * Searching through modules and namespaces with :samp:`*` wildcards, both | |
|
66 | when using the :samp:`?` system and via the :samp:`%psearch` command. | |
|
67 | ||
|
68 | * Completion in the local namespace, by typing :kbd:`TAB` at the prompt. | |
|
69 | This works for keywords, modules, methods, variables and files in the | |
|
70 | current directory. This is supported via the readline library, and | |
|
71 | full access to configuring readline's behavior is provided. | |
|
72 | Custom completers can be implemented easily for different purposes | |
|
73 | (system commands, magic arguments etc.) | |
|
74 | ||
|
75 | * Numbered input/output prompts with command history (persistent | |
|
76 | across sessions and tied to each profile), full searching in this | |
|
77 | history and caching of all input and output. | |
|
78 | ||
|
79 | * User-extensible 'magic' commands. A set of commands prefixed with | |
|
80 | :samp:`%` is available for controlling IPython itself and provides | |
|
81 | directory control, namespace information and many aliases to | |
|
82 | common system shell commands. | |
|
83 | ||
|
84 | * Alias facility for defining your own system aliases. | |
|
85 | ||
|
86 | * Complete system shell access. Lines starting with :samp:`!` are passed | |
|
87 | directly to the system shell, and using :samp:`!!` or :samp:`var = !cmd` | |
|
88 | captures shell output into python variables for further use. | |
|
89 | ||
|
90 | * Background execution of Python commands in a separate thread. | |
|
91 | IPython has an internal job manager called jobs, and a | |
|
92 | convenience backgrounding magic function called :samp:`%bg`. | |
|
93 | ||
|
94 | * The ability to expand python variables when calling the system | |
|
95 | shell. In a shell command, any python variable prefixed with :samp:`$` is | |
|
96 | expanded. A double :samp:`$$` allows passing a literal :samp:`$` to the shell (for | |
|
97 | access to shell and environment variables like :envvar:`PATH`). | |
|
98 | ||
|
99 | * Filesystem navigation, via a magic :samp:`%cd` command, along with a | |
|
100 | persistent bookmark system (using :samp:`%bookmark`) for fast access to | |
|
101 | frequently visited directories. | |
|
102 | ||
|
103 | * A lightweight persistence framework via the :samp:`%store` command, which | |
|
104 | allows you to save arbitrary Python variables. These get restored | |
|
105 | automatically when your session restarts. | |
|
106 | ||
|
107 | * Automatic indentation (optional) of code as you type (through the | |
|
108 | readline library). | |
|
109 | ||
|
110 | * Macro system for quickly re-executing multiple lines of previous | |
|
111 | input with a single name. Macros can be stored persistently via | |
|
112 | :samp:`%store` and edited via :samp:`%edit`. | |
|
113 | ||
|
114 | * Session logging (you can then later use these logs as code in your | |
|
115 | programs). Logs can optionally timestamp all input, and also store | |
|
116 | session output (marked as comments, so the log remains valid | |
|
117 | Python source code). | |
|
118 | ||
|
119 | * Session restoring: logs can be replayed to restore a previous | |
|
120 | session to the state where you left it. | |
|
121 | ||
|
122 | * Verbose and colored exception traceback printouts. Easier to parse | |
|
123 | visually, and in verbose mode they produce a lot of useful | |
|
124 | debugging information (basically a terminal version of the cgitb | |
|
125 | module). | |
|
126 | ||
|
127 | * Auto-parentheses: callable objects can be executed without | |
|
128 | parentheses: :samp:`sin 3` is automatically converted to :samp:`sin(3)`. | |
|
129 | ||
|
130 | * Auto-quoting: using :samp:`,`, or :samp:`;` as the first character forces | |
|
131 | auto-quoting of the rest of the line: :samp:`,my_function a b` becomes | |
|
132 | automatically :samp:`my_function("a","b")`, while :samp:`;my_function a b` | |
|
133 | becomes :samp:`my_function("a b")`. | |
|
134 | ||
|
135 | * Extensible input syntax. You can define filters that pre-process | |
|
136 | user input to simplify input in special situations. This allows | |
|
137 | for example pasting multi-line code fragments which start with | |
|
138 | :samp:`>>>` or :samp:`...` such as those from other python sessions or the | |
|
139 | standard Python documentation. | |
|
140 | ||
|
141 | * Flexible configuration system. It uses a configuration file which | |
|
142 | allows permanent setting of all command-line options, module | |
|
143 | loading, code and file execution. The system allows recursive file | |
|
144 | inclusion, so you can have a base file with defaults and layers | |
|
145 | which load other customizations for particular projects. | |
|
146 | ||
|
147 | * Embeddable. You can call IPython as a python shell inside your own | |
|
148 | python programs. This can be used both for debugging code or for | |
|
149 | providing interactive abilities to your programs with knowledge | |
|
150 | about the local namespaces (very useful in debugging and data | |
|
151 | analysis situations). | |
|
152 | ||
|
153 | * Easy debugger access. You can set IPython to call up an enhanced | |
|
154 | version of the Python debugger (pdb) every time there is an | |
|
155 | uncaught exception. This drops you inside the code which triggered | |
|
156 | the exception with all the data live and it is possible to | |
|
157 | navigate the stack to rapidly isolate the source of a bug. The | |
|
158 | :samp:`%run` magic command (with the :samp:`-d` option) can run any script under | |
|
159 | pdb's control, automatically setting initial breakpoints for you. | |
|
160 | This version of pdb has IPython-specific improvements, including | |
|
161 | tab-completion and traceback coloring support. For even easier | |
|
162 | debugger access, try :samp:`%debug` after seeing an exception. winpdb is | |
|
163 | also supported, see ipy_winpdb extension. | |
|
164 | ||
|
165 | * Profiler support. You can run single statements (similar to | |
|
166 | :samp:`profile.run()`) or complete programs under the profiler's control. | |
|
167 | While this is possible with standard cProfile or profile modules, | |
|
168 | IPython wraps this functionality with magic commands (see :samp:`%prun` | |
|
169 | and :samp:`%run -p`) convenient for rapid interactive work. | |
|
170 | ||
|
171 | * Doctest support. The special :samp:`%doctest_mode` command toggles a mode | |
|
172 | that allows you to paste existing doctests (with leading :samp:`>>>` | |
|
173 | prompts and whitespace) and uses doctest-compatible prompts and | |
|
174 | output, so you can use IPython sessions as doctest code. | |
|
147 | 175 | |
|
148 | 176 | Interactive parallel computing |
|
149 | 177 | ============================== |
|
150 | 178 | |
|
151 | 179 | Increasingly, parallel computer hardware, such as multicore CPUs, clusters and supercomputers, is becoming ubiquitous. Over the last 3 years, we have developed an |
|
152 | 180 | architecture within IPython that allows such hardware to be used quickly and easily |
|
153 | 181 | from Python. Moreover, this architecture is designed to support interactive and |
|
154 | 182 | collaborative parallel computing. |
|
155 | 183 | |
|
184 | The main features of this system are: | |
|
185 | ||
|
186 | * Quickly parallelize Python code from an interactive Python/IPython session. | |
|
187 | ||
|
188 | * A flexible and dynamic process model that be deployed on anything from | |
|
189 | multicore workstations to supercomputers. | |
|
190 | ||
|
191 | * An architecture that supports many different styles of parallelism, from | |
|
192 | message passing to task farming. And all of these styles can be handled | |
|
193 | interactively. | |
|
194 | ||
|
195 | * Both blocking and fully asynchronous interfaces. | |
|
196 | ||
|
197 | * High level APIs that enable many things to be parallelized in a few lines | |
|
198 | of code. | |
|
199 | ||
|
200 | * Write parallel code that will run unchanged on everything from multicore | |
|
201 | workstations to supercomputers. | |
|
202 | ||
|
203 | * Full integration with Message Passing libraries (MPI). | |
|
204 | ||
|
205 | * Capabilities based security model with full encryption of network connections. | |
|
206 | ||
|
207 | * Share live parallel jobs with other users securely. We call this collaborative | |
|
208 | parallel computing. | |
|
209 | ||
|
210 | * Dynamically load balanced task farming system. | |
|
211 | ||
|
212 | * Robust error handling. Python exceptions raised in parallel execution are | |
|
213 | gathered and presented to the top-level code. | |
|
214 | ||
|
156 | 215 | For more information, see our :ref:`overview <parallel_index>` of using IPython for |
|
157 | 216 | parallel computing. |
|
158 | 217 | |
|
159 | 218 | Portability and Python requirements |
|
160 | 219 | ----------------------------------- |
|
161 | 220 | |
|
162 | 221 | As of the 0.9 release, IPython requires Python 2.4 or greater. We have |
|
163 | 222 | not begun to test IPython on Python 2.6 or 3.0, but we expect it will |
|
164 | 223 | work with some minor changes. |
|
165 | 224 | |
|
166 | 225 | IPython is known to work on the following operating systems: |
|
167 | 226 | |
|
168 | 227 | * Linux |
|
169 | 228 | * AIX |
|
170 | 229 | * Most other Unix-like OSs (Solaris, BSD, etc.) |
|
171 | 230 | * Mac OS X |
|
172 | 231 | * Windows (CygWin, XP, Vista, etc.) |
|
173 | 232 | |
|
174 | 233 | See :ref:`here <install_index>` for instructions on how to install IPython. No newline at end of file |
@@ -1,17 +1,14 b'' | |||
|
1 | 1 | .. _parallel_index: |
|
2 | 2 | |
|
3 | 3 | ==================================== |
|
4 |
Using IPython for |
|
|
4 | Using IPython for parallel computing | |
|
5 | 5 | ==================================== |
|
6 | 6 | |
|
7 | User Documentation | |
|
8 | ================== | |
|
9 | ||
|
10 | 7 | .. toctree:: |
|
11 | 8 | :maxdepth: 2 |
|
12 | 9 | |
|
13 | 10 | parallel_intro.txt |
|
14 | 11 | parallel_multiengine.txt |
|
15 | 12 | parallel_task.txt |
|
16 | 13 | parallel_mpi.txt |
|
17 | 14 |
@@ -1,242 +1,327 b'' | |||
|
1 | 1 | .. _ip1par: |
|
2 | 2 | |
|
3 |
============================ |
|
|
4 | Using IPython for parallel computing | |
|
5 |
============================ |
|
|
3 | ============================ | |
|
4 | Overview and getting started | |
|
5 | ============================ | |
|
6 | 6 | |
|
7 | 7 | .. contents:: |
|
8 | 8 | |
|
9 | 9 | Introduction |
|
10 | 10 | ============ |
|
11 | 11 | |
|
12 |
This file gives an overview of IPython |
|
|
12 | This file gives an overview of IPython's sophisticated and | |
|
13 | 13 | powerful architecture for parallel and distributed computing. This |
|
14 | 14 | architecture abstracts out parallelism in a very general way, which |
|
15 | 15 | enables IPython to support many different styles of parallelism |
|
16 | 16 | including: |
|
17 | 17 | |
|
18 |
|
|
|
19 |
|
|
|
20 |
|
|
|
21 |
|
|
|
22 |
|
|
|
23 |
|
|
|
24 |
|
|
|
18 | * Single program, multiple data (SPMD) parallelism. | |
|
19 | * Multiple program, multiple data (MPMD) parallelism. | |
|
20 | * Message passing using ``MPI``. | |
|
21 | * Task farming. | |
|
22 | * Data parallel. | |
|
23 | * Combinations of these approaches. | |
|
24 | * Custom user defined approaches. | |
|
25 | 25 | |
|
26 | 26 | Most importantly, IPython enables all types of parallel applications to |
|
27 | 27 | be developed, executed, debugged and monitored *interactively*. Hence, |
|
28 | 28 | the ``I`` in IPython. The following are some example usage cases for IPython: |
|
29 | 29 | |
|
30 |
|
|
|
31 |
|
|
|
32 |
|
|
|
33 | * Steer traditional MPI applications on a supercomputer from an | |
|
34 | IPython session on your laptop. | |
|
35 | * Analyze and visualize large datasets (that could be remote and/or | |
|
36 | distributed) interactively using IPython and tools like | |
|
37 | matplotlib/TVTK. | |
|
38 | * Develop, test and debug new parallel algorithms | |
|
39 | (that may use MPI) interactively. | |
|
40 | * Tie together multiple MPI jobs running on different systems into | |
|
41 | one giant distributed and parallel system. | |
|
42 | * Start a parallel job on your cluster and then have a remote | |
|
43 | collaborator connect to it and pull back data into their | |
|
44 | local IPython session for plotting and analysis. | |
|
45 | * Run a set of tasks on a set of CPUs using dynamic load balancing. | |
|
30 | * Quickly parallelize algorithms that are embarrassingly parallel | |
|
31 | using a number of simple approaches. Many simple things can be | |
|
32 | parallelized interactively in one or two lines of code. | |
|
33 | ||
|
34 | * Steer traditional MPI applications on a supercomputer from an | |
|
35 | IPython session on your laptop. | |
|
36 | ||
|
37 | * Analyze and visualize large datasets (that could be remote and/or | |
|
38 | distributed) interactively using IPython and tools like | |
|
39 | matplotlib/TVTK. | |
|
40 | ||
|
41 | * Develop, test and debug new parallel algorithms | |
|
42 | (that may use MPI) interactively. | |
|
43 | ||
|
44 | * Tie together multiple MPI jobs running on different systems into | |
|
45 | one giant distributed and parallel system. | |
|
46 | ||
|
47 | * Start a parallel job on your cluster and then have a remote | |
|
48 | collaborator connect to it and pull back data into their | |
|
49 | local IPython session for plotting and analysis. | |
|
50 | ||
|
51 | * Run a set of tasks on a set of CPUs using dynamic load balancing. | |
|
46 | 52 | |
|
47 | 53 | Architecture overview |
|
48 | 54 | ===================== |
|
49 | 55 | |
|
50 | 56 | The IPython architecture consists of three components: |
|
51 | 57 | |
|
52 |
|
|
|
53 |
|
|
|
54 |
|
|
|
58 | * The IPython engine. | |
|
59 | * The IPython controller. | |
|
60 | * Various controller clients. | |
|
61 | ||
|
62 | These components live in the :mod:`IPython.kernel` package and are | |
|
63 | installed with IPython. They do, however, have additional dependencies | |
|
64 | that must be installed. For more information, see our | |
|
65 | :ref:`installation documentation <install_index>`. | |
|
55 | 66 | |
|
56 | 67 | IPython engine |
|
57 | 68 | --------------- |
|
58 | 69 | |
|
59 | 70 | The IPython engine is a Python instance that takes Python commands over a |
|
60 | 71 | network connection. Eventually, the IPython engine will be a full IPython |
|
61 | 72 | interpreter, but for now, it is a regular Python interpreter. The engine |
|
62 | 73 | can also handle incoming and outgoing Python objects sent over a network |
|
63 | 74 | connection. When multiple engines are started, parallel and distributed |
|
64 | 75 | computing becomes possible. An important feature of an IPython engine is |
|
65 | 76 | that it blocks while user code is being executed. Read on for how the |
|
66 | 77 | IPython controller solves this problem to expose a clean asynchronous API |
|
67 | 78 | to the user. |
|
68 | 79 | |
|
69 | 80 | IPython controller |
|
70 | 81 | ------------------ |
|
71 | 82 | |
|
72 | 83 | The IPython controller provides an interface for working with a set of |
|
73 | 84 | engines. At an general level, the controller is a process to which |
|
74 | 85 | IPython engines can connect. For each connected engine, the controller |
|
75 | 86 | manages a queue. All actions that can be performed on the engine go |
|
76 | 87 | through this queue. While the engines themselves block when user code is |
|
77 | 88 | run, the controller hides that from the user to provide a fully |
|
78 |
asynchronous interface to a set of engines. |
|
|
79 | listens on a network port for engines to connect to it, it must be | |
|
80 | started before any engines are started. | |
|
89 | asynchronous interface to a set of engines. | |
|
90 | ||
|
91 | .. note:: | |
|
92 | ||
|
93 | Because the controller listens on a network port for engines to | |
|
94 | connect to it, it must be started *before* any engines are started. | |
|
81 | 95 | |
|
82 | 96 | The controller also provides a single point of contact for users who wish |
|
83 | 97 | to utilize the engines connected to the controller. There are different |
|
84 | 98 | ways of working with a controller. In IPython these ways correspond to different interfaces that the controller is adapted to. Currently we have two default interfaces to the controller: |
|
85 | 99 | |
|
86 | * The MultiEngine interface. | |
|
87 | * The Task interface. | |
|
100 | * The MultiEngine interface, which provides the simplest possible way of working | |
|
101 | with engines interactively. | |
|
102 | * The Task interface, which provides presents the engines as a load balanced | |
|
103 | task farming system. | |
|
88 | 104 | |
|
89 | 105 | Advanced users can easily add new custom interfaces to enable other |
|
90 | 106 | styles of parallelism. |
|
91 | 107 | |
|
92 | 108 | .. note:: |
|
93 | 109 | |
|
94 | 110 | A single controller and set of engines can be accessed |
|
95 | 111 | through multiple interfaces simultaneously. This opens the |
|
96 | 112 | door for lots of interesting things. |
|
97 | 113 | |
|
98 | 114 | Controller clients |
|
99 | 115 | ------------------ |
|
100 | 116 | |
|
101 | 117 | For each controller interface, there is a corresponding client. These |
|
102 | 118 | clients allow users to interact with a set of engines through the |
|
103 | interface. | |
|
119 | interface. Here are the two default clients: | |
|
120 | ||
|
121 | * The :class:`MultiEngineClient` class. | |
|
122 | * The :class:`TaskClient` class. | |
|
104 | 123 | |
|
105 | 124 | Security |
|
106 | 125 | -------- |
|
107 | 126 | |
|
108 |
By default (as long as `pyOpenSSL` is installed) all network connections between the controller and engines and the controller and clients are secure. What does this mean? First of all, all of the connections will be encrypted using SSL. Second, the connections are authenticated. We handle authentication in a `capabilities`__ based security model. In this model, a "capability (known in some systems as a key) is a communicable, unforgeable token of authority". Put simply, a capability is like a key to your house. If you have the key to your house, you can get in |
|
|
127 | By default (as long as `pyOpenSSL` is installed) all network connections between the controller and engines and the controller and clients are secure. What does this mean? First of all, all of the connections will be encrypted using SSL. Second, the connections are authenticated. We handle authentication in a `capabilities`__ based security model. In this model, a "capability (known in some systems as a key) is a communicable, unforgeable token of authority". Put simply, a capability is like a key to your house. If you have the key to your house, you can get in. If not, you can't. | |
|
109 | 128 | |
|
110 | 129 | .. __: http://en.wikipedia.org/wiki/Capability-based_security |
|
111 | 130 | |
|
112 |
In our architecture, the controller is the only process that listens on network ports, and is thus responsible to creating these keys. In IPython, these keys are known as Foolscap URLs, or FURLs, because of the underlying network protocol we are using. As a user, you don't need to know anything about the details of these FURLs, other than that when the controller starts, it saves a set of FURLs to files named something.furl. The default location of these files is |
|
|
131 | In our architecture, the controller is the only process that listens on network ports, and is thus responsible to creating these keys. In IPython, these keys are known as Foolscap URLs, or FURLs, because of the underlying network protocol we are using. As a user, you don't need to know anything about the details of these FURLs, other than that when the controller starts, it saves a set of FURLs to files named :file:`something.furl`. The default location of these files is the :file:`~./ipython/security` directory. | |
|
113 | 132 | |
|
114 | To connect and authenticate to the controller an engine or client simply needs to present an appropriate furl (that was originally created by the controller) to the controller. Thus, the .furl files need to be copied to a location where the clients and engines can find them. Typically, this is the ~./ipython directory on the host where the client/engine is running (which could be a different host than the controller). Once the .furl files are copied over, everything should work fine. | |
|
133 | To connect and authenticate to the controller an engine or client simply needs to present an appropriate furl (that was originally created by the controller) to the controller. Thus, the .furl files need to be copied to a location where the clients and engines can find them. Typically, this is the :file:`~./ipython/security` directory on the host where the client/engine is running (which could be a different host than the controller). Once the .furl files are copied over, everything should work fine. | |
|
134 | ||
|
135 | Currently, there are three .furl files that the controller creates: | |
|
136 | ||
|
137 | ipcontroller-engine.furl | |
|
138 | This ``.furl`` file is the key that gives an engine the ability to connect | |
|
139 | to a controller. | |
|
140 | ||
|
141 | ipcontroller-tc.furl | |
|
142 | This ``.furl`` file is the key that a :class:`TaskClient` must use to | |
|
143 | connect to the task interface of a controller. | |
|
144 | ||
|
145 | ipcontroller-mec.furl | |
|
146 | This ``.furl`` file is the key that a :class:`MultiEngineClient` must use to | |
|
147 | connect to the multiengine interface of a controller. | |
|
148 | ||
|
149 | More details of how these ``.furl`` files are used are given below. | |
|
115 | 150 | |
|
116 | 151 | Getting Started |
|
117 | 152 | =============== |
|
118 | 153 | |
|
119 | 154 | To use IPython for parallel computing, you need to start one instance of |
|
120 | 155 | the controller and one or more instances of the engine. The controller |
|
121 | 156 | and each engine can run on different machines or on the same machine. |
|
122 | 157 | Because of this, there are many different possibilities for setting up |
|
123 | 158 | the IP addresses and ports used by the various processes. |
|
124 | 159 | |
|
125 | 160 | Starting the controller and engine on your local machine |
|
126 | 161 | -------------------------------------------------------- |
|
127 | 162 | |
|
128 | 163 | This is the simplest configuration that can be used and is useful for |
|
129 | 164 | testing the system and on machines that have multiple cores and/or |
|
130 |
multple CPUs. The easiest way of |
|
|
165 | multple CPUs. The easiest way of getting started is to use the :command:`ipcluster` | |
|
131 | 166 | command:: |
|
132 | 167 | |
|
133 | 168 | $ ipcluster -n 4 |
|
134 | ||
|
169 | ||
|
135 | 170 | This will start an IPython controller and then 4 engines that connect to |
|
136 | 171 | the controller. Lastly, the script will print out the Python commands |
|
137 | 172 | that you can use to connect to the controller. It is that easy. |
|
138 | 173 | |
|
139 | Underneath the hood, the ``ipcluster`` script uses two other top-level | |
|
174 | .. warning:: | |
|
175 | ||
|
176 | The :command:`ipcluster` does not currently work on Windows. We are | |
|
177 | working on it though. | |
|
178 | ||
|
179 | Underneath the hood, the controller creates ``.furl`` files in the | |
|
180 | :file:`~./ipython/security` directory. Because the engines are on the | |
|
181 | same host, they automatically find the needed :file:`ipcontroller-engine.furl` | |
|
182 | there and use it to connect to the controller. | |
|
183 | ||
|
184 | The :command:`ipcluster` script uses two other top-level | |
|
140 | 185 | scripts that you can also use yourself. These scripts are |
|
141 |
|
|
|
186 | :command:`ipcontroller`, which starts the controller and :command:`ipengine` which | |
|
142 | 187 | starts one engine. To use these scripts to start things on your local |
|
143 | 188 | machine, do the following. |
|
144 | 189 | |
|
145 | 190 | First start the controller:: |
|
146 | 191 | |
|
147 |
$ ipcontroller |
|
|
192 | $ ipcontroller | |
|
148 | 193 | |
|
149 | 194 | Next, start however many instances of the engine you want using (repeatedly) the command:: |
|
150 | 195 | |
|
151 |
$ ipengine |
|
|
196 | $ ipengine | |
|
197 | ||
|
198 | The engines should start and automatically connect to the controller using the ``.furl`` files in :file:`~./ipython/security`. You are now ready to use the controller and engines from IPython. | |
|
152 | 199 | |
|
153 | 200 | .. warning:: |
|
154 | 201 | |
|
155 | 202 | The order of the above operations is very important. You *must* |
|
156 | 203 | start the controller before the engines, since the engines connect |
|
157 | 204 | to the controller as they get started. |
|
158 | 205 | |
|
159 | On some platforms you may need to give these commands in the form | |
|
160 | ``(ipcontroller &)`` and ``(ipengine &)`` for them to work properly. The | |
|
161 | engines should start and automatically connect to the controller on the | |
|
162 | default ports, which are chosen for this type of setup. You are now ready | |
|
163 | to use the controller and engines from IPython. | |
|
206 | .. note:: | |
|
164 | 207 | |
|
165 | Starting the controller and engines on different machines | |
|
166 | --------------------------------------------------------- | |
|
208 | On some platforms (OS X), to put the controller and engine into the background | |
|
209 | you may need to give these commands in the form ``(ipcontroller &)`` | |
|
210 | and ``(ipengine &)`` (with the parentheses) for them to work properly. | |
|
167 | 211 | |
|
168 | This section needs to be updated to reflect the new Foolscap capabilities based | |
|
169 | model. | |
|
170 | 212 | |
|
171 | Using ``ipcluster`` with ``ssh`` | |
|
172 | -------------------------------- | |
|
213 | Starting the controller and engines on different hosts | |
|
214 | ------------------------------------------------------ | |
|
173 | 215 | |
|
174 | The ``ipcluster`` command can also start a controller and engines using | |
|
175 | ``ssh``. We need more documentation on this, but for now here is any | |
|
176 | example startup script:: | |
|
216 | When the controller and engines are running on different hosts, things are | |
|
217 | slightly more complicated, but the underlying ideas are the same: | |
|
177 | 218 | |
|
178 | controller = dict(host='myhost', | |
|
179 | engine_port=None, # default is 10105 | |
|
180 | control_port=None, | |
|
181 | ) | |
|
219 | 1. Start the controller on a host using :command:`ipcontroler`. | |
|
220 | 2. Copy :file:`ipcontroller-engine.furl` from :file:`~./ipython/security` on the controller's host to the host where the engines will run. | |
|
221 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. | |
|
182 | 222 | |
|
183 | # keys are hostnames, values are the number of engine on that host | |
|
184 | engines = dict(node1=2, | |
|
185 | node2=2, | |
|
186 | node3=2, | |
|
187 | node3=2, | |
|
188 | ) | |
|
223 | The only thing you have to be careful of is to tell :command:`ipengine` where the :file:`ipcontroller-engine.furl` file is located. There are two ways you can do this: | |
|
224 | ||
|
225 | * Put :file:`ipcontroller-engine.furl` in the :file:`~./ipython/security` directory | |
|
226 | on the engine's host, where it will be found automatically. | |
|
227 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` flag. | |
|
228 | ||
|
229 | The ``--furl-file`` flag works like this:: | |
|
230 | ||
|
231 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl | |
|
232 | ||
|
233 | .. note:: | |
|
234 | ||
|
235 | If the controller's and engine's hosts all have a shared file system | |
|
236 | (:file:`~./ipython/security` is the same on all of them), then things | |
|
237 | will just work! | |
|
238 | ||
|
239 | Make .furl files persistent | |
|
240 | --------------------------- | |
|
241 | ||
|
242 | At fist glance it may seem that that managing the ``.furl`` files is a bit annoying. Going back to the house and key analogy, copying the ``.furl`` around each time you start the controller is like having to make a new key everytime you want to unlock the door and enter your house. As with your house, you want to be able to create the key (or ``.furl`` file) once, and then simply use it at any point in the future. | |
|
243 | ||
|
244 | This is possible. The only thing you have to do is decide what ports the controller will listen on for the engines and clients. This is done as follows:: | |
|
245 | ||
|
246 | $ ipcontroller --client-port=10101 --engine-port=10102 | |
|
247 | ||
|
248 | Then, just copy the furl files over the first time and you are set. You can start and stop the controller and engines any many times as you want in the future, just make sure to tell the controller to use the *same* ports. | |
|
249 | ||
|
250 | .. note:: | |
|
251 | ||
|
252 | You may ask the question: what ports does the controller listen on if you | |
|
253 | don't tell is to use specific ones? The default is to use high random port | |
|
254 | numbers. We do this for two reasons: i) to increase security through obcurity | |
|
255 | and ii) to multiple controllers on a given host to start and automatically | |
|
256 | use different ports. | |
|
189 | 257 | |
|
190 | 258 | Starting engines using ``mpirun`` |
|
191 | 259 | --------------------------------- |
|
192 | 260 | |
|
193 | 261 | The IPython engines can be started using ``mpirun``/``mpiexec``, even if |
|
194 | the engines don't call MPI_Init() or use the MPI API in any way. This is | |
|
262 | the engines don't call ``MPI_Init()`` or use the MPI API in any way. This is | |
|
195 | 263 | supported on modern MPI implementations like `Open MPI`_.. This provides |
|
196 | 264 | an really nice way of starting a bunch of engine. On a system with MPI |
|
197 | 265 | installed you can do:: |
|
198 | 266 | |
|
199 | mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0 | |
|
267 | mpirun -n 4 ipengine | |
|
268 | ||
|
269 | to start 4 engine on a cluster. This works even if you don't have any | |
|
270 | Python-MPI bindings installed. | |
|
200 | 271 | |
|
201 | 272 | .. _Open MPI: http://www.open-mpi.org/ |
|
202 | 273 | |
|
203 | 274 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. |
|
204 | 275 | |
|
205 | 276 | Log files |
|
206 | 277 | --------- |
|
207 | 278 | |
|
208 | 279 | All of the components of IPython have log files associated with them. |
|
209 | 280 | These log files can be extremely useful in debugging problems with |
|
210 | 281 | IPython and can be found in the directory ``~/.ipython/log``. Sending |
|
211 | 282 | the log files to us will often help us to debug any problems. |
|
212 | 283 | |
|
213 | 284 | Next Steps |
|
214 | 285 | ========== |
|
215 | 286 | |
|
216 | 287 | Once you have started the IPython controller and one or more engines, you |
|
217 |
are ready to use the engines to do som |
|
|
288 | are ready to use the engines to do something useful. To make sure | |
|
218 | 289 | everything is working correctly, try the following commands:: |
|
219 | 290 | |
|
220 | 291 | In [1]: from IPython.kernel import client |
|
221 | 292 | |
|
222 |
In [2]: mec = client.MultiEngineClient() |
|
|
293 | In [2]: mec = client.MultiEngineClient() | |
|
223 | 294 | |
|
224 | 295 | In [4]: mec.get_ids() |
|
225 | 296 | Out[4]: [0, 1, 2, 3] |
|
226 | 297 | |
|
227 | 298 | In [5]: mec.execute('print "Hello World"') |
|
228 | 299 | Out[5]: |
|
229 | 300 | <Results List> |
|
230 | 301 | [0] In [1]: print "Hello World" |
|
231 | 302 | [0] Out[1]: Hello World |
|
232 | 303 | |
|
233 | 304 | [1] In [1]: print "Hello World" |
|
234 | 305 | [1] Out[1]: Hello World |
|
235 | 306 | |
|
236 | 307 | [2] In [1]: print "Hello World" |
|
237 | 308 | [2] Out[1]: Hello World |
|
238 | 309 | |
|
239 | 310 | [3] In [1]: print "Hello World" |
|
240 | 311 | [3] Out[1]: Hello World |
|
241 | 312 | |
|
242 | If this works, you are ready to learn more about the :ref:`MultiEngine <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the controller. | |
|
313 | Remember, a client also needs to present a ``.furl`` file to the controller. How does this happen? When a multiengine client is created with no arguments, the client tries to find the corresponding ``.furl`` file in the local :file:`~./ipython/security` directory. If it finds it, you are set. If you have put the ``.furl`` file in a different location or it has a different name, create the client like this:: | |
|
314 | ||
|
315 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') | |
|
316 | ||
|
317 | Same thing hold true of creating a task client:: | |
|
318 | ||
|
319 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') | |
|
320 | ||
|
321 | You are now ready to learn more about the :ref:`MultiEngine <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the controller. | |
|
322 | ||
|
323 | .. note:: | |
|
324 | ||
|
325 | Don't forget that the engine, multiengine client and task client all have | |
|
326 | *different* furl files. You must move *each* of these around to an appropriate | |
|
327 | location so that the engines and clients can use them to connect to the controller. |
|
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 |
General Comments 0
You need to be logged in to leave comments.
Login now