1+ import json
12import sys
23
34import pandas as pd
@@ -106,10 +107,10 @@ def display_code_for_index(self, line):
106107 """
107108 Display stored source code of a previously executed cell by index.
108109 Usage:
109- %% display_code_for_index 2
110+ %display_code_for_index 2
110111 """
111112 if not line .strip ():
112- self .cell_output ("No index specified. Use: %% display_code_for_index <index>" , stream = "stdout" )
113+ self .cell_output ("No index specified. Use: %display_code_for_index <index>" , stream = "stdout" )
113114 return
114115
115116 try :
@@ -146,10 +147,10 @@ def perfdata_to_variable(self, line):
146147 """
147148 Export collected performance data into a notebook variable.
148149 Usage:
149- %% perfdata_to_variable myvar
150+ %perfdata_to_variable myvar
150151 """
151152 if not line .strip ():
152- self .cell_output ("No variable for export specified. Use: %% perfdata_to_variable myvar" , stream = "stdout" )
153+ self .cell_output ("No variable for export specified. Use: %perfdata_to_variable myvar" , stream = "stdout" )
153154 return
154155
155156 varname = line .strip ()
@@ -176,11 +177,51 @@ def perfdata_to_variable(self, line):
176177 stream = "stdout"
177178 )
178179
180+ @line_magic
181+ def perfdata_to_json (self , line ):
182+ """
183+ Export performance data and code history to JSON files.
184+ Usage:
185+ %perfdata_to_json myfilename
186+ Creates:
187+ myfilename_perfdata.json
188+ myfilename_code.json
189+ """
190+ if not line .strip ():
191+ self .cell_output ("No filename specified. Use: %perfdata_to_json <myfile>" , stream = "stdout" )
192+ return
193+
194+ filename = line .strip ()
195+
196+ try :
197+ with open (f"{ filename } _perfdata.json" , "w" ) as f :
198+ json .dump (
199+ kernel_context .perfdata_handler .get_perfdata_history (),
200+ fp = f ,
201+ default = str
202+ )
203+
204+ with open (f"{ filename } _code.json" , "w" ) as f :
205+ json .dump (
206+ kernel_context .perfdata_handler .get_code_history (),
207+ fp = f ,
208+ default = str
209+ )
210+
211+ self .cell_output (
212+ f"Exported performance data to `{ filename } _perfdata.json` "
213+ f"and `{ filename } _code.json`" ,
214+ stream = "stdout"
215+ )
216+ except Exception as e :
217+ self .cell_output (f"Failed to export data: { e } " , stream = "stderr" )
218+
179219 @cell_magic
180220 def set_perfmonitor (self , line , code ):
181221 """
182222 Read the perfmonitor and try to select it.
183223 """
224+ # TODO fix modes (yet exist in kernel and extension)
184225 if self .mode == KernelMode .DEFAULT :
185226 monitor = code .split ("\n " )[1 ]
186227 if monitor in {"local" , "localhost" , "LOCAL" , "LOCALHOST" }:
0 commit comments