The following recipe shows different ways that the REPL can be used.
Executing commands in the REPL
Getting ready
Any one method can be used from the preceding two recipes here to obtain a REPL.
How to do it...
- Open the REPL through your preferred application.
- Many of the same capabilities provided by the REPL in CPython also work in the MicroPython implementation. The last returned value can be accessed with _:
>>> 2 + 2
4
>>> _ + 2
6
-
Continuation lines are also supported, making it possible to define functions or for loops through the REPL, as shown in the following output:
>>> def add(a, b):
... return a + b
...
...
...
>>> add(2, 2)
4
>>>
- Arbitrary precision integers are also supported, even on constrained microcontroller hardware. The following code shows arithmetic with integers beyond the limit of a 64-bit integer value:
>>> 2**100 + 2**101
3802951800684688204490109616128
How it works...
The REPL implementation has most of the features that we've come to know and love in the CPython implementation. The MicroPython implementation has to deal with tough hardware constraints so that it can run on a microcontroller. But, even with these constraints, the end user experience of the REPL in both implementations is almost identical, making it an easy transition for Python developers.
There's more...
The REPL can be an invaluable tool when you want to experiment with certain MicroPython libraries or certain features on a device. It lets you easily import different Python modules and call functions provided by those libraries in a more direct fashion to discover how they will actually interact with the hardware. Many components on these microcontrollers can be fine-tuned for different project needs. The REPL frequently ends up being an ideal place to do this fine-tuning.
See also
Here are a few references:
- The MicroPython Interactive Interpreter Mode (REPL) is documented at http://docs.micropython.org/en/latest/reference/repl.html.
- Documentation on the MicroPython built-in types can be found at http://docs.micropython.org/en/latest/genrst/builtin_types.html.