Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions circuitpython_kernel/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,49 @@ def is_magic(self, line):
KERNEL_LOGGER.debug(f"upload_delay set to {float(s_line[1])} s")
except TypeError:
pass
elif line.startswith("%python"):
#python line magic, runs what ever is on the line following the %python magic.
code = line.lstrip("%python")
code = code.lstrip(' ')
for item in code.split(";"):
item = item.lstrip(' ') #remove leading white space
try:
print(eval(item)) #does not print
except:
out = exec(item)
if out != None:
print(out) #does not print

else:
return False
return True

def is_cell_magic(self, code):
"""Cell magic to run python code.
-----
Cell shall begin with %%python followed by a new line
Will iteratively run each line of code.
"""

if code.startswith("%%python"):
code = code.lstrip("%%python")
code = code.lstrip(' ')
data = code.splitlines(True)
for item in data:

code = code.lstrip(' ') #this removes all preceeding white space,
#i need to figure out how to get for loops, etc working
try:
print(eval(item)) #does not print
except:
out = exec(item)

if out != None:
print(out) #does not print
return True
else:
return False

@classmethod
def is_comment(cls, line):
"""Returns true if the line of code is empty or a comment.
Expand Down Expand Up @@ -86,6 +125,13 @@ def run_code(self, code):
"""
# make sure we are connected to the board
self.board.connect()
##cell check for python cell magics
python_cell = self.is_cell_magic(code)

if python_cell == True:
out = []
err = []
return out, err
# Send code to board & fetch results (if any) after each line sent
for line in code.splitlines(False):
if not self.is_magic(line) and not self.is_comment(line):
Expand Down
158 changes: 158 additions & 0 deletions examples/Using_magics.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "ordered-violence",
"metadata": {},
"source": [
"# Tutorial using the inbuilt magics %python and %%python"
]
},
{
"cell_type": "markdown",
"id": "micro-palestine",
"metadata": {},
"source": [
"Ipython magics allow many things to be done inside jupyter notebooks from running bash scripts to running interactive plotting tools.\n",
"This tutorial looks at implementing simple magics command which allows the user to run Python code in the notebook whilst also running circuit python.\n",
"The 2 magics that are available to the user are `%python` and `%%python`:\\\n",
"\n",
"`%python` : is a line magic allowing a single line of python code to be run following the `%python` keyword\\\n",
"`%%python` : is a cell magic allowing the user to run the whole cell in python, rather than circuitpython.\\\n",
"\n",
"\n",
"Below is a quick example of this in play."
]
},
{
"cell_type": "markdown",
"id": "smooth-wesley",
"metadata": {},
"source": [
"To begin with we can make sure we are using the circuit python kernel by checking the top left corner of the page."
]
},
{
"cell_type": "markdown",
"id": "studied-knowing",
"metadata": {},
"source": [
"To show that the system is connected to the circuitpython we run the below command."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "mineral-herald",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"print(os.uname())"
]
},
{
"cell_type": "markdown",
"id": "prepared-object",
"metadata": {},
"source": [
"We can see from above the system is connected to the microcontroller."
]
},
{
"cell_type": "markdown",
"id": "remarkable-change",
"metadata": {},
"source": [
"Following this we can run a python line magic to import a single library. "
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "worse-pipeline",
"metadata": {},
"outputs": [],
"source": [
"%python import numpy"
]
},
{
"cell_type": "markdown",
"id": "radical-breath",
"metadata": {},
"source": [
"This line magics still works when we string code together with semicolons. Which we can see in the following cell."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "current-creativity",
"metadata": {},
"outputs": [],
"source": [
"%python import numpy as np; a = 2; b = 4; np.sum((a,b))"
]
},
{
"cell_type": "markdown",
"id": "sixth-commitment",
"metadata": {},
"source": [
"We can also run cell magics by adding the `%%python` which we see in the cell below."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "divine-spread",
"metadata": {},
"outputs": [],
"source": [
"%%python\n",
"import nbdev\n",
"import numpy as np\n",
"a = 2\n",
"b = 4\n",
"np.sum((a,b))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "compliant-syracuse",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "demanding-dover",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "CircuitPython",
"language": "python",
"name": "circuitpython"
},
"language_info": {
"codemirror_mode": {
"name": "python",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"pygments_lexer": "python3",
"version": "3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading