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
Related
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.
When I am following a Youtube tutorial, my code breaks when they try to import pytorch_lightning. I had a similar problem in my PyCharm environment but it has since gone away, and I am unsure why.
Error provided was
import pytorch_lightning as pl fails with ValueError: transformers.models.auto._spec_ is None.
This is my collab notebook : https://colab.research.google.com/drive/1DeeYFvK7wFsf9VBxjr184VAlulg6M_ly?usp=sharing
I decided to try and see if I can replicate the error using a minimal sub-example in a new notebook : https://colab.research.google.com/drive/1NiHIoIt8v215-lO8KoHKDSkCuw9W5S6a?usp=sharing
In the new notebook, it imports just fine. Why is it then in my actual notebook I get an error?
Update : Ending my runtime session, and restarting it, has solved the issue. However I'd like to know what I did that caused it in the first place, if possible, to avoid having this occur again.
it's a known issue with torchmetrics==0.7.0. Until torchmetrics==0.7.1 will be released, use an older version:
pip install "torchmetrics<0.7"
Here's the tracking issue: https://github.com/PyTorchLightning/pytorch-lightning/issues/11524
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 to use pytractor.
When I write import statement
from pytractor.webdriver import Firefox
Firefox is not referenced-not found. Neither Chrome.
However, pytractor instructions and example clearly have no problem importing
Firefox:
readme file
Anybody has solved this?
(I read the pytractor is not actively maintained, however last activity on its Github page is currently 6 days old so I guess it is maintained.)
example
UPDATE:
FF was underlined with red squiggly line in Pycharm but the code still works. I just didn't run it. It's Pycharm's error checking that was confusing.
Don't have any issues with that. Installed it from github:
$ pip install git+https://github.com/kpodl/pytractor
And imported in the Python shell:
$ ipython
In [1]: from pytractor.webdriver import Firefox
In [2]:
Make sure you don't have your script named pytractor.
I updated my python distribution yesterday to EPD 7.3-2 (64-bit). I am working on a mac with snow leopard.
Now the plot device of matplotlib is broken in at least two ways:
the "save" button doesn't work and makes the terminal or ipython crash and
the only way to see the figure is to have it in front of you, there is no python figure icon in the dock.
I did my homework and these same problems were reported here and here.
I tried to follow the instructions to fix this given in here, but this is the error that I get:
$python install_pythonw.py `which python`/../..
/Library/Frameworks/EPD64.framework/Versions/Current/.Python does not exist; exiting.
Indeed, I looked at the given folder and I could not find a .Python file. I added a comment at the answer to this problem but so far no one has replied to it :( :(
Any idea of how to fix this?
thanks!
I have seen this problem a few times, and it seems to be a problem in some backends. Also, it doesn't seem normal that your session crashes after 4 or 5 plots. In particular, the MacOSX backend seems buggy.
As you installed the EPD, I think it's less likely that your installation is broken.
The solution seems to be using a different backend. You can try with ipython --pylab a few backends, try their features and see if the save button works. You can try the following:
ipython --pylab=wx
ipython --pylab=tk
ipython --pylab=osx
The last one is the option that you're probably using right now, so perhaps not the best. If you just call ipython --pylab, it will use the default backend from your ~/.matplotlib/matplotlibrc file. Once you find a working backend you can change the default by editing that file. Look for a line like this:
backend : MacOSX
(your version may have a different backend.) Just change that setting to WXAgg, TkAgg, or Qt4Agg. With the --pylab option the names are slightly different, they don't have the Agg part. My favourite backend for OSX is the Qt4Agg backend, but I don't think it ships with EPD and the save button also doesn't work! But either WXAgg or TkAgg should work fine.
Other ways of changing the backend in a script are:
import matplotlib
matplotlib.use('WXAgg')
or
matplotlib.rcParams['backend'] = 'WXAgg'