How to set the running file path of jupyter in VScode? - python
When I use the jupyter extension in VScode and run a line of code in jupyter to save a file using relative path,I found the file(iris_tree.dot) in another file. It's just like i debug/run the code in another file path. How can I set the correct path of the jupyter runner?
#%%
from sklearn.tree import export_graphviz
export_graphviz(
tree_clf,
out_file="iris_tree.dot",
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
Just update the value of "Notebook File Root" to ${workspaceFolder} or ${fileDirname}.
I'm one of the developers on this extension. By default we follow the VSCode pattern of working directory as opposed to the Jupyter pattern. Meaning that we use the root of the currently open workspace folder as the current working directory for starting jupyter notebooks. That might be what is confusing you here.
To get around this you can either set cwd in your notebook code as redhatvicky mentioned or you can change the default current working directory in the following VSCode setting.
Jupyter -> Notebook File Root
Since you can change that setting per workspace you can have it always default to a specific location when working in just the workspace that contains your file.
Edit 2/16/22 New setting location
#Ian Huff's answer is still valid, however the setting seems to have changed location since then.
Instead of "Python -> Data Science -> Notebook File Root", it's now "Jupyter -> Notebook File Root"
Your question seems quite confusing and I am unable to post a comment. Please follow this link. As per your question, I think the issue is you need to select the correct python interpreter by CTRL+SHIFT+P and then Python: Select Interpreter to select the correct conda environment or a conda interpreter. Otherwise you can try and execute the following code to change your directory before any other command:
import os
try:
os.chdir(os.path.join(os.getcwd(), 'path_to_folder_to_have_the_file')) # '.' if the path is to current folder
print(os.getcwd())
except:
pass
Generally you can change the working directory by using "os.chdir(NEW_PATH)"
One another Suggestion is that , You can set the location to save the image from the code itself.
Here below is the code which might help you.
from __future__ import division, print_function, unicode_literals
# Common imports
import numpy as np
import os
# to make this notebook's output stable across runs
np.random.seed(42)
# To plot pretty figures
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "decision_trees"
def image_path(fig_id):
return os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id)
def save_fig(fig_id, tight_layout=True):
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
print(image_path(fig_id) + ".png")
plt.savefig(image_path(fig_id) + ".png", format='png', dpi=300)
save_fig("Fig-01-6TFG")
Related
Notebook in VSCode displays no output for some stored variables
Consider the following code: import pandas as pd import os csv = """Country,Total Cases,New Cases,Total Deaths,New Deaths,Recovered,Serious China,74187,1751,2006,138,14796,12017 Diamond Princess,621,79,,,17,20 Singapore,81,,,,29,4 Japan,80,6,1,,20,4 Hong Kong,63,1,2,1,5,6 S. Korea,51,20,,,16, Thailand,35,,,,17,2 USA,29,,,,3, Taiwan,23,1,1,,2, Malaysia,22,,,,15, Vietnam,16,,,,14, Germany,16,,,,9, Australia,15,,,,10, France,12,,1,,7, Macao,10,,,,5, U.A.E.,9,,,,3,1 U.K.,9,,,,8, Canada,8,,,,1, Philippines,3,,1,,2, Italy,3,,,,,2 India,3,,,,3, Russia,2,,,,2, Spain,2,,,,2, Nepal,1,,,,1, Belgium,1,,,,1, Sri Lanka,1,,,,1, Finland,1,,,,1, Egypt,1,,,,, Cambodia,1,,,,1, Sweden,1,,,,,""" with open("data/covid.csv", "w") as file: file.write(csv) df = pd.read_csv("data/covid.csv").fillna(0).astype(dtype = int, errors='ignore')\ .sort_values(by='Total Cases', ascending=False) latest = df.to_dict('list') some_var = latest.keys() print(latest.keys()) # It's a notebook. Printing or calling a variable does not matter. latest.keys() Please see the attached image to see the issue It works in a jupyter notebook on conda and if I run it via a normal python file. Which highlights that the issue lies with how VSCode displays notebook outputs As you can see, VSCode does not display some outputs after running a cell, but does display others after running a cell. If I try this in a conda environment, it works just fine: Any suggestions for why this issue only happens in VSCode & How I might go about fixing it? Is it a kernel thing?
This issue was caused by an extension within vscode called Leaflet Map. It changed the default renderer for notebook cells in vscode. If anyone else has issues with VSCode outputs in future, you can click the elipsis on the output cell -> Click Change Presentation & ensure you're using an up to date renderer:
Where to find the .py file of a specific tensorflow object in python
I have the following preprocessing pipeline in Tensorflow: data_transformation = tf.keras.Sequential([layers.experimental.preprocessing.RandomContrast(factor=(0.7,0.9)),layers.GaussianNoise(stddev=tf.random.uniform(shape=(),minval=0, maxval=1)), layers.experimental.preprocessing.RandomRotation(factor=0.1, fill_mode='reflect', interpolation='bilinear', seed=None, name=None, fill_value=0.0), layers.experimental.preprocessing.RandomZoom(height_factor=(0.1,0.2), width_factor=(0.1,0.2), fill_mode='reflect', interpolation='bilinear', seed=None, name=None, fill_value=0.0),]) I would like to change the layers.experimental.preprocessing.RandomContrast.py file to change how it works. However, I don't find such a file in my system. Whenever I found a file, it is an init.py file linking to a different directory. I know that, if I declare the following in the python terminal, It returns fine: import tensorflow as tf tf.image.random_contrast But if I look for image in my tensorflow directory, the following returns to me /usr/local/lib/python3.8/dist-packages/tensorflow/_api/v2/image /usr/local/lib/python3.8/dist-packages/tensorflow/_api/v2/compat/v1/image /usr/local/lib/python3.8/dist-packages/tensorflow/_api/v2/compat/v2/image /usr/local/lib/python3.8/dist-packages/tensorflow/include/tensorflow/core/kernels/image /usr/local/lib/python3.8/dist-packages/tensorflow/keras/preprocessing/image /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/api/_v1/keras/preprocessing/image /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/api/keras/preprocessing/image /usr/local/lib/python3.8/dist-packages/tensorflow/python/keras/api/_v2/keras/preprocessing/image All of these directories point to init.py files again. And it seems in an infinite loop looking for directories that are redirected by init.py files. How am I supposed to find the specific .py file of a specific import in python?
You can search on the web for : tf layers.experimental.preprocessing.RandomContrast Then follow the first link : RandomContrast and finally click on view source on github which will go here: image_preprocessing.py
Why doesn't SimpleITK display image with imageJ?
I am new in ITK. I wrote a small program to read image using sitk and display the image using imageJ. import os import SimpleITK as sitk pathDicom = 'C://Users//clouds.png' input = sitk.ReadImage(pathDicom) sitk.Show( input , debugOn=True) To link simpleITK to imageJ I set the environment variable. But I am getting following error for sitk.Show(): return _SimpleITK.Show(*args, **kwargs) RuntimeError: Exception thrown in SimpleITK Show: C:\d\VS14-Win32-pkg\SimpleITK\Code\IO\src\sitkShow.cxx:580: sitk::ERROR: Error in administrating child process: [Access is denied]. imageJ output is shown in the attached figure. Can someone tell what's the problem?
What version of SimpleITK are you running. It looks like it is not correctly finding the ImageJ executable. The 2nd line of the output shows that it's trying to execute 'C:\Users\Harish\fiji-win64\Fiji.app'. That's the Fiji directory, not the actual executable. Can you try moving the Fiji.app directory to be directly inside your home directory? So move it up a directory to get rid of fiji-win64 in the path. By default it searches there, so maybe the fiji-win64 directory is messing it up. The other thing you can try is the SITK_SHOW_COMMAND environment variable. Set it to the full path of the ImageJ executable. That will override the search for ImageJ.
OSError: Unable to locate Ghostscript on paths
I tried to open an EPS image with Pyzo, I have installed PIL and Ghostscript (as I saw that it is necessary on some other website topics), my code is: from PIL import Image im = Image.open('''myimage.eps''') im.show() but when I run the code, Pyzo return me: OSError: Unable to locate Ghostscript on paths I tried to look into it on several websites but it seems pretty complicated for a novice coding student.
In case someone else encounters this issue: It seems that Ghostscript has not been added to the paths properly. For those running Win7, here is a fix: Go to: Control Panel -> System -> Advanced system settings -> Environment Variables... Find the variable "PATH" -> Edit... -> add the path to your ghostscript binary folder, e.g. C:\Program Files\gs\gs9.22\bin\; to the end of the variable. It should be separated from the previous entry by a semicolon. I had to restart for the changes to take effect.
You need ghostscript. download: https://www.ghostscript.com/download/gsdnld.html Tell the variable(EpsImagePlugin.gs_windows_binary) what the path of EXE(gswin64c, gswin32c, gs ) it is. (If you don't want to change the system path.) from PIL import EpsImagePlugin EpsImagePlugin.gs_windows_binary = r'X:\...\gs\gs9.52\bin\gswin64c' im = Image.open('myimage.eps') im.save('myimage.png') You can see the following on PIL.EpsImagePlugin.py # EpsImagePlugin.py __version__ = "0.5" ... gs_windows_binary = None # 👈 def Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript""" ... if gs_windows_binary is not None: if not gs_windows_binary: # 👈 raise WindowsError("Unable to locate Ghostscript on paths") command[0] = gs_windows_binary So that's why I tell you to set the gs_windows_binary will work.
Reading image using Pillow fails in Jupyter notebook
I'm trying to read a jpg file using Pillow (Version 3.2.0) in Jupyter notebook (Python 3.4), but it fails with the following error: OSError: broken data stream when reading image file I'm using the following code: from PIL import Image im = Image.open("/path/to/image.jpeg") im.show() It works fine both in the interactive Python shell and using Python 2.7 instead of 3.4. I've followed these steps already: Using Pillow with Python 3 Anyone an idea what's going on?
Looks like you're not pointing to the directory where your photo is stored. import os defaultWd = os.getcwd() defaultWd # Sets your curretn wd os.chdir(defaultWd + '\\Desktop') # Points to your photo--e.g., on Desktop os.getcwd() # Shows change in wd from PIL import Image im = Image.open("Mew.jpg") im.show() # Will plot to your default image viewing software And another way if you don't want to change current wd: im = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg") im.show() And if you want to plot inline: from matplotlib.pyplot import imshow %matplotlib inline inlinePic = Image.open(os.getcwd() + "\\Desktop\\Mew.jpg") imshow(inlinePic) Note: You may also want to simply try typing 'jpg' instead of 'jpeg' as you did above, if your image is in your current working directory. Also, if PIC is not installed, you'll get this error NameError: name 'Image' is not defined.
The problem was related to another import: I was importing Tensorflow before PIL, which caused the problem. Same issue as this one: https://github.com/scikit-image/scikit-image/issues/2000. Changing the order of the imports solved it.