microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
pip/qsharp/_ipython.py
34lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | from ._qsharp import (_interpret_with_outputs, QSharpException) |
| 5 | |
| 6 | from IPython.core.magic import (register_cell_magic) |
| 7 | |
| 8 | |
| 9 | def register_magic(): |
| 10 | @register_cell_magic |
| 11 | def qsharp(line, cell): |
| 12 | "interpret q# code" |
| 13 | try: |
| 14 | (value, out) = _interpret_with_outputs(cell) |
| 15 | return DisplayableOutput(out, value) |
| 16 | except QSharpException as ex: |
| 17 | for diagnostic in ex.diagnostics: |
| 18 | print("\x1b[31m" + diagnostic.message + "\x1b[0m") |
| 19 | |
| 20 | |
| 21 | class DisplayableOutput: |
| 22 | def __init__(self, outputs, value): |
| 23 | self.outputs = outputs |
| 24 | self.value = value |
| 25 | |
| 26 | def _repr_html_(self): |
| 27 | val = "" |
| 28 | for output in self.outputs: |
| 29 | val += output._repr_html_() |
| 30 | |
| 31 | val += "<p>" |
| 32 | val += self.value.__repr__() |
| 33 | val += "</p>" |
| 34 | return val |
| 35 | |