| 22 | import ruamel.yaml |
| 23 | |
| 24 | def execute_code(code_str: str, Kernel, nb): |
| 25 | nb.cells.append(nbformat.v4.new_code_cell(code_str)) |
| 26 | total_cells = len(nb.cells) |
| 27 | cell = nb.cells[-1] |
| 28 | client = NotebookClient(nb, allow_errors=True) |
| 29 | client.kc = Kernel |
| 30 | print(cell) |
| 31 | |
| 32 | try: |
| 33 | client.reset_execution_trackers() |
| 34 | client.execute_cell(cell=cell, cell_index=-1) |
| 35 | except Exception as e: |
| 36 | traceback.print_exc() |
| 37 | error_message = str(e) |
| 38 | return error_message |
| 39 | |
| 40 | outputs = nb.cells[-1]['outputs'] |
| 41 | |
| 42 | result = "" |
| 43 | for output in outputs: |
| 44 | if output.output_type == "stream": # 如果输出是标准输出或标准错误 |
| 45 | result += output.text |
| 46 | elif output.output_type == "execute_result": # 如果输出是执行结果 |
| 47 | result += str(output['data']['text/plain']) |
| 48 | elif output.output_type == "error": # 如果输出是错误 |
| 49 | result += "There are some errors in the code. All variables in this cell should be redefined. Please Debug:\n" |
| 50 | result += "Error: " + str(output.ename) + "\n" |
| 51 | result += str(output.evalue) + "\n" |
| 52 | |
| 53 | return result |
| 54 | |
| 55 | |
| 56 | import os |