My problem is similar to the one that is treated [here]:(How can I check if code is executed in the IPython notebook?), but with an additional layer.
I am using some .py scripts with the special comment "# %%" that in visual studio code allow me to run some portions of the code interactively. The problem is that i want to execute the following line only if i run the section in interactive mode, not if i run the entire script:
%matplotlib widget
I wish something like that would work:
if src.visualization.isNotebook():
%matplotlib widget
where the function is defined as in the link:
def isNotebook() -> bool:
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
this works well when I run just the cell, but if i want to run the whole file, VScode sense "%matplotlib widget" as "SyntaxError: invalid syntax".
Is there a workaround? I need this because in interactive mode there is no option to save the plots to .pgf format, but the same code executed as script, opens a window that has the option to save as .pgf.