Using a jupyter notebook in VSCode, I'm trying to run the following code from this documentation:
import numpy as np
from IPython.display import Audio
framerate = 44100
t = np.linspace(0,5,framerate*5)
data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
Audio(data, rate=framerate)
However, I only get this
If I press play button, then nothing happens...
As of today, it seems VSCode Jupyter extension does not support audio. You can track the issue here on their Github.
One solution can be merging this pull request and rebuilding VSCode, which is not suggested.
The preferred alternate solution is using jupyter lab instead of VSCode for such use cases.
As of version 1.7, it seems they’ve fixed it.
Related
I am looking for a way to programmatically replicate the Run Cell Below functionality VS code.
Previously, I used Jupyter through Conda and used the following code:
import ipywidgets as widgets
from IPython.display import display,Markdown,Javascript,HTML
def run_below(ev):
Javascript('IPython.notebook.execute_cells_below()')
button = widgets.Button(description="Click to run cells below")
button.on_click(run_below)
display(button)
This code worked great, but when I tried to plop it into VSCode, the button just does nothing. I don't understand much about how the VSCode Jupyter backend works, but I'm imagining it has something do do with the IPython.notebook module not working correctly in this IDE (or perhaps the IPython.display.Javascript module?). I really have no real idea though.
Does anyone know how I could do this in VSCode's Jupyter implementation?
I have searched for hours on this topic, but have not been able to find a working solution that works. Please let me know if y'all have any ideas.
Environment Info:
Python Version: 3.9.12
VSCode Version: 1.69.0
Jupyter Extension Version: v2022.6.1001902341
It appears that the ability to access the Kernel in VS code is not possible at this time. See the following GitHub issues to see if this has changed at the time of reading:
Similar question migrated to #6918
Issue #6918 that will resolve problem once closed
Not exactly an answer to detailed question but is an answer to the title of the question "Programmatically execute cell jupyter vscode" since I landed on this page searching for how to do this. The following code supports this task - just make sure to hit save CTRL-S if you make changes to cells that are going to be run by the following function since it reads the current version of file from disk
def execute_cell(filepath,cell_number_range=[0]):
import io
from nbformat import current
with io.open(filepath) as f:
nb = current.read(f, 'json')
ip = get_ipython()
for cell_number in cell_number_range:
cell=nb.worksheets[0].cells[cell_number]
#print (cell)
if cell.cell_type == 'code' : ip.run_cell(cell.input)
also for finding name of current notebook in vscode is easy but not easy in jupyterlab
import os
globals()['__vsc_ipynb_file__'] #full name only in vscode
os.path.basename(globals()['__vsc_ipynb_file__']) #basename only in vscode . globals()['_dh'] #dir in most
I am running jupyter notebook in vscode. But when I try to run the following cell of code I got error.
import os
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
import torchvision.transforms as tt
import torch
import torch.nn as nn
import cv2
from tqdm.notebook import tqdm
import torch.nn.functional as F
from torchvision.utils import save_image
from torchvision.utils import make_grid
import matplotlib.pyplot as plt
%matplotlib inline
The error is
Error loading preloads:
Could not find renderer
I tried but could not find its solution on the internet. How can I resolve this issue?
In my case, I had Jupyter notebook extension installed. So, I did ctrl+shift+P and did Reload window; resolved!
In case you just don't see the bar without any error: disable Jupyter notebook renderers extension, test, and then re-enable it
I am having the same issue with the latest release of the VS code Jupyer extension. The fix for now is to just go to the Jupyter extension tab, then the button that says "Uninstall," click the down arrow and hit "Install Another Version" and just install the version from > 1 mo ago and it should work fine. Hopefully they'll resolve this issue in the latest version soon.
Install/reinstall Jupyter Notebook Renderers Extension
Reload Window
Open the Command Palette (Ctrl + Shift + P)
Then type: Reload Window
If this still doesn't work, make sure plot presentation is set to:
image/png
Jupyter Notebook Renderer (ms-toolsai.jupyter-renderers)
Change Presentation
Select Renderer
You should now be able to generate a plot in the interactive window. Hovering over the plot will give options to expand or save.
To get a better looking plot when zoomed in enable the "Jupyter: Generate SVGPlots" setting in the "Jupyter" extension and reload the window again. Then change the plot presentation to:
image/svg+xml
Jupyter Notebook Renderer (ms-toolsai.jupyter-renderers)
From the github issue: Renderer extension not being installed -- causes some packages not to work, like plotly. It should have been fixed in new release because the issue was closed on 14 Jan.
Run this code and see if the question goes away:
import plotly.io as pio
pio.renderers.default = 'iframe_connected'
OR
You may try to uninstall Jupyter extension completely by deleting its packages in the folder \...\.vscode\extensions\ms-toolsai.jupyter then reinstall the latest version.
Install extension Jupyter Notebook Renderers and update your VS code to the latest version.
just disable the "jupyter notebook renderers" in the extension section and then Reload it. Lastly, enable it and you're good to go.
When you install the Jupyter extension, Jupyter Notebook Renderers are also installed because it's included in the extension pack. This extension is causing this error so remove the extension from the Jupyter extension details and try running the block again.
If the mentioned solutions do not work try the followings as well:
check if you have all packages installed, for me the problem was that one package was not installed and I saw the same error as you mentioned which is totally irrelevant to missing one package!
if that does not work either, simply check if you are using the correct Python interpreter in the correct environment.
As for me, this happened because of the "Workspace Trust" thing, where normally you would open the file/files by right-clicking the folder from explorer and click "Open with VSCode". Instead, i opened the notebook's file directly with VSCode and the Workspace Trust tab shows up. The Workspace Trust makes almost all of your extension disabled, including the Jupyter's ones.
Normally, you can just trust your workspace/directory in the same session and your extensions will be reloaded without needing of restart, apparently this is not the case as the problem appeared and only disappeared after a VSCode restart.
So, TL;DR : Workspace Trust tab shows up > Trust the workspace > restart VSCode
I think you should try restarting VSCode.
Just uninstall Jupyter Notebook Extension in VScode Extension, Reload the VScode window then install back Jupyter Notebook extension and run the cells again. It sloved my problem
I want to choose the best IDE for Python programming so I'm testing different softwares but I have problem.
When I try this code blocks on VS Code I don't see any error but the image is not showing
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
VS Code
When I try run the same code on PyCharm I see some errors
PyCharm
But when I run the same code on Jupyter Notebook it works. What can I do?
Bro, try that:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread('exit-ramp.jpg')
plt.imshow(image)
plt.show()
i've made a test in my vscode.
Few weeks ago i used a lot pycharm... but i get some library errors with pandas and pycharm its a little bit heavy.
VSCODE its light and i didnt get any library error that i had with pycharm.
I believe this is a backend problem to be changed in matplotlib. If you start your Python shell whether you are in a bash shell or in vscode, you should use a backend that will show the plot. Otherwise the plt.show() call is required.
So, one solution is to change the backend either manually in you Python shell or when starting the Python shell as explained here below.
Note, however, that I always use the qt5 backend but got the same issue as yours: no plot appears. I changed to the Qt5Agg backend and it worked for me (providing PyQt5 is installed).
So, first solution, you can try to set the backend when starting the Python shell:
ipython --pylab Qt5Agg
You should use a GUI backend amongst the possible backend. If you do not known, try to replace Qt5Agg by auto
The second solution consists in changing the backend manually once in the Python shell:
import matplotlib as plt
plt.use('Qt5Agg')
Right click on your code -> Run current file in interactive window.
I'm running some basic code in the Visual Studio Code editor on MacOSX:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 20, 100)
plt.plot(x, np.sin(x))
plt.show()
...and can't seem to get the png/svg file image to come up after running this. This also doesn't stop executing and I have to manually terminate the process. However, if I run this directly in the Terminal (each line of code line for line) I get the resulting image. One work-around is to just save the file (plt.savefig('foo.png')). This seems to work - the image is saved in the specified file location. However, it would be good to just see the image come up after running the code.
When running matplotlib codes from the terminal, I experience the same kind of hanging of the application after saving the image to a file. In this case, one 'workaround' that has always worked for me is to turn off blocking. Basically alter your code in this way:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 20, 100)
plt.plot(x, np.sin(x))
plt.show(block=False)
input('press <ENTER> to continue')
It's not perfect, but the image is saved correctly and the application stops after you hit ENTER in the terminal. Hope this helps.
I am having a similar issue and I think it is a problem with the exact version of python that vs code is using to run the code.
For reference, I have vscode version 1.52.1 on a mac os Catalina. I installed python via anaconda and created a new environment for python 2.7 (tried with python 3.8 too). I open VSCode by calling code . from the folder I have my simple python codes saved in.
Like OP, I could reproduce the figure if I were to run the code from a python instance called from terminal but not from vscode.
MY SOLUTION:
From vscode, select as python interpreter the one found in /usr/bin/python not the one in ~/opt/anaconda3/env/python27/bin/python
But this is weird, because from a separate terminal window which python returns ~/opt/anaconda3/env/python27/bin/python. This suggests me (though I am no python expert) that there is an issue within vscode about linking the right interpreter with the libraries. Frankly being new to vscode, I find the need to pay attention to these details quite concerning.
I got the same problem, which was driving me nuts. The image was displayed when using Jupyter Notebooks, but not always when using VS Code. I just added one last line_ plt.show() - IMHO unnecessarily - but this worked well.
import matplotlib.pyplot as plt
import matplotlib.image as img
im = img.imread('myimage.png')
plt.imshow(im)
plt.show() # <- added this line and now the image shows every time!
I faced the same issue and here's what I did to solve it.
Since the code runs without any error but also does not generate any plot and needs to be terminated manually, it's difficult to figure out what's going on. I tried running python2.7 test.py
This works, plot is generated but python3 test.py does not work.
So, here's what you need to do -
Run, pip install matplotlib --upgrade to upgrade the matplotlib. This does not resolve the issue but now the error is printed.
"RuntimeError: Python is not installed as a framework" ......
So, finally, to solve the problem, refer to Working with Matplotlib on macOS
Since, I am using Anaconda, all I need to do is conda install python.app and then use pythonw to run all scripts. I hope you also find the solution to your particular case from the FAQ.
Overall, it's a Matplotlib problem, so upgrading (or reinstalling) and trying with different Python versions should get you going.
I'm trying out Jupyter console for the first time, but can't get the %matplotlib inline magic to work. Below is a screenshot of an example session:
The plot shows in a separate window after I run Line 6, and Line 7 doesn't do anything.
When I run %matplotlib --list, inline is given as one of the options:
Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt',
'nbagg', 'agg', 'gtk', 'tk', 'ipympl', 'inline']
When I try to use another backend, say qt5, it gives an error message because I don't have any Qt installed.
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, or PySide
package to be installed, but it was not found.
Running %matplotlib?? reads:
If you are using the inline matplotlib backend in the IPython Notebook
you can set which figure formats are enabled using the following::
In [1]: from IPython.display import set_matplotlib_formats
In [2]: set_matplotlib_formats('pdf', 'svg')
The default for inline figures sets `bbox_inches` to 'tight'. This can
cause discrepancies between the displayed image and the identical
image created using `savefig`. This behavior can be disabled using the
`%config` magic::
In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
But I don't know if it's something I can tweak around to solve my issue.
When I try it the magic IPython console, it says inline is an Unknown Backend.
UnknownBackend: No event loop integration for u'inline'. Supported event loops are: qt,
qt4, qt5, gtk, gtk2, gtk3, tk, wx, pyglet, glut, osx
I've also found this issue on github after some googling but I don't even know if it's relevant to my situation (most of their conversation didn't make sense to me lol).
Lastly, I'm not sure if this issue is related at all, but here it is, just in case: when I try to open Vim in Jupyter via the !vim command, it glitches pretty badly, preventing me from even exiting out of Jupyter itself without closing the terminal altogther. Vim works perfectly fine when called inside IPython console, however.
I'm using matplotlib 2.0.0.
If anyone could help me figure this out, that'd be great! Thank you!
You’re running a console which is completely text based and incapable of showing images. Therefore, although inline is available, it's not producing inline output.
I'm not sure why it doesn't throw an error, though, which it does in my case:
You can use %matplotlib inline in a GUI console, like Jupyter QTConsole
or in a jupyter notebook in the browser
%matplotlib without the inline works for me (I'm using osx and IPython 7.0.1)
If you're running an old version of ipython try %pylab inline instead. See notes in this tutorial