【问题标题】:VS Code and python debugger returning error but can run in the terminalVS Code 和 python 调试器返回错误但可以在终端中运行
【发布时间】:2019-04-19 07:20:50
【问题描述】:

我正在尝试运行我为一些绘图制作的代码,并且我可以在终端和 spyder 上完全运行它(我想从 spyder 切换到 VS 代码完成数据分析)但我一直收到一个错误,说我的 CSV找不到文件,而如果我直接在终端或 spyder 上运行此文件,则不会出现此类错误

因此,如果我尝试使用 VS Code 中的运行单元运行我的代码,我会收到以下错误:

import pandas as pd...
import pandas as pd...
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
 in 
      4 
      5 
----> 6 LNA_w2Path_PAC_AND_PSP = pd.read_csv('../../Results/CSV/LNA_w2Path_PAC_AND_PSP.csv')
      7 LNA_w2Path_PAC_AND_PSP.columns = LNA_w2Path_PAC_AND_PSP.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('/', '').str.replace('=','_').str.replace(';','')
      8 plt.figure()

~/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, delim_whitespace, low_memory, memory_map, float_precision)
    700                     skip_blank_lines=skip_blank_lines)
    701 
--> 702         return _read(filepath_or_buffer, kwds)

对不起,这里没有包装代码,显然 markdown 不支持这一点。 我要运行的代码是:

#%% #for jupyter notebook 

import pandas as pd
from matplotlib import pyplot as plt
import numpy as np


LNA_w2Path_PAC_AND_PSP = pd.read_csv('../../Results/CSV/LNA_w2Path_PAC_AND_PSP.csv')
LNA_w2Path_PAC_AND_PSP.columns = LNA_w2Path_PAC_AND_PSP.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('/', '').str.replace('=','_').str.replace(';','')
plt.figure()
plt.plot(LNA_w2Path_PAC_AND_PSP.net18net049_h_0__pac_db20vv_harmonic_0_x/1E9, LNA_w2Path_PAC_AND_PSP.net18net049_h_0__pac_db20vv_harmonic_0_y, linewidth=2.0)
plt.ylabel("$\mathrm{Harmonic \ response \ (dB)}$")
plt.xlabel("$\mathrm{Frequency \ (GHz)}$")
plt.title("Harmonic response of LNA+2-Path Filter")
plt.grid(True, which="both")
plt.show()

如果我只是运行python3 myfile.py,它就可以正常工作。

编辑

我的.json 文件如下所示:

{
    "git.autofetch": true,
    "python.pythonPath": "/home/theis/anaconda3",
    "window.zoomLevel": 2,
    "editor.find.addExtraSpaceOnTop": false,
    "editor.suggestSelection": "first",
    "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
    "python.jediEnabled": false,
    "workbench.colorTheme": "Dracula Soft",
    "python.linting.pylintEnabled": false,
    "python.linting.enabled": false,
    "languageTool.language": "en-US",
    "julia.enableTelemetry": true,
    "python.terminal.executeInFileDir": true
}

EDIT2

所以我将"cwd": "${fileDirname}" 添加到我的launch.json 并尝试在调试器中运行此代码并使用jupyter notebook 扩展:

#%%

import os
print("Hello World!")
print(os.getcwd())

调试器返回:

Hello World!
/home/theis/code/N_path_intership/PlottingCode/python

jupyter notebook 扩展返回:

Hello World!
/home/theis/code/N_path_intership/PlottingCode

【问题讨论】:

  • 可能您的调试器的当前工作目录与您的默认运行终端不同
  • 我如何设置两者相同?

标签: python python-3.x visual-studio-code


【解决方案1】:

也许这个答案可以帮助你: https://stackoverflow.com/a/49275867/9628974

这是关于更改 VSCode 设置以在文件的 firectory 中执行 python。

【讨论】:

  • 这已经设置好了(我已经在 EDIT 中添加了 .json 文件)
【解决方案2】:

在调试菜单中,点击设置小图标打开launch.json。您的文件应如下所示:

{
    "version": "0.2.0",
    "configurations": [
    {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
    }, 

    //... other settings, but I modified the "Current File" setting above ...
}

您可以添加一个cwd 键(表示当前工作目录)并将其设置为您想要的:

{
    "version": "0.2.0",
    "configurations": [
    {
            "name": "Python: Current File (Integrated Terminal)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${fileDirname}/<WhateverYouWant>"
    }, 

    //... other settings, but I modified the "Current File" setting above ...
}

它应该可以通过正确的路径解决您的问题。

【讨论】:

  • 我真的应该在 fileDirname 之后添加一些东西,即:"${fileDirname}/myfolder",因为据我所知,fileDirname 已经完成了自己获取路径的工作。我添加了"cwd": "${fileDirname}",但没有成功。
猜你喜欢
  • 2020-10-27
  • 2021-08-16
  • 1970-01-01
  • 2022-10-03
  • 1970-01-01
  • 2021-02-15
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多