python - VS Code 和 python 调试器返回错误,但可以在终端中运行

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

我正在尝试运行我为一些图编写的代码,并且我可以在终端和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
}

编辑2:

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

#%%

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

调试器返回:

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

并且 jupyter 笔记本扩展返回:

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

最佳答案

在调试菜单中,单击小设置图标以打开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 ...
}

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

关于python - VS Code 和 python 调试器返回错误,但可以在终端中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55758072/

相关文章:

python - 在Docker上的pip安装上的CERTIFICATE_VERIFY_FAILED

Python:在具有最小 y 的对列表中获取最大对

python - 我应该在抽象方法的主体中放什么?

python - 计算从给定日期算起固定天数的日期

visual-studio-code - 如何在 Visual Studio Code 中调出 Chrome 控制台

python - 如何按行值过滤和分组条目

python - 500 服务器错误-导入错误 : No module named ssl

python - 如何将linux的find命令的 `maxdepth`选项模拟到python

c# - 使用 Visual Studio Code 在 Linux 上编写 C#

node.js - 如果 "posttest"脚本失败, yarn "test"脚本将不起作用