如何在VScode中设置jupyter的运行文件路径?

问题描述 投票:0回答:3

当我在VScode中使用jupyter扩展并在jupyter中运行一行代码以使用相对路径保存文件时,我在另一个文件中找到了该文件(iris_tree.dot)。就像我在另一个文件路径中调试/运行代码一样。如何设置jupyter跑步者的正确路径?

#%%
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
)
python visual-studio-code jupyter
3个回答
1
投票

我是此扩展程序的开发人员之一。默认情况下,我们遵循工作目录的VSCode模式而不是Jupyter模式。这意味着我们使用当前打开的工作区文件夹的根目录作为启动jupyter笔记本的当前工作目录。这可能会让你感到困惑。

要解决此问题,您可以在笔记本代码中设置cwd,如redhatvicky所述,或者您可以在以下VSCode设置中更改默认的当前工作目录。

Python - >数据科学 - > Notebook文件根目录

由于您可以在每个工作区更改该设置,因此在仅包含文件的工作区中工作时,它始终默认为特定位置。


0
投票

你的问题似乎很混乱,我无法发表评论。请关注这个link。根据你的问题,我认为问题是你需要通过CTRL + SHIFT + P选择正确的python解释器,然后选择Python: Select Interpreter来选择正确的conda环境或conda解释器。否则,您可以尝试执行以下代码以在任何其他命令之前更改目录:

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

0
投票

通常,您可以使用“os.chdir(NEW_PATH)”更改工作目录

另一个建议是,您可以设置位置以保存代码本身的图像。

以下是可能对您有帮助的代码。

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")
© www.soinside.com 2019 - 2024. All rights reserved.