简体   繁体   English

如何让 VSCode 从代码所在的位置运行你的代码

[英]How to make VSCode run your code from the location of the code

I keep on getting Module Not Found errors in Python and by printing out os.getcwd() , I found that VSCode seems to be running things from the workspace folder (the top-level folder in the editor) rather than the folder that the code is in. Thus, it can't find the the modules because all of my relative import and path-changing code doesn't work.我在 Python 中不断收到Module Not Found错误,并通过打印os.getcwd() ,我发现 VSCode 似乎是从工作区文件夹(编辑器中的顶级文件夹)而不是代码所在的文件夹中运行的是。因此,它找不到模块,因为我所有的相对导入和路径更改代码都不起作用。

I did some research and found the option "python.terminal.executeInFileDir": true in settings, which seems like it should change this, but when I press F5 , the code still seems to be run out of the workspace folder.我做了一些研究,在设置中找到了选项"python.terminal.executeInFileDir": true ,这似乎应该改变它,但是当我按下F5时,代码似乎仍然超出了工作区文件夹。

How can I get the code to be run out of the same folder that the file is in when I run my code?当我运行我的代码时,如何让代码从文件所在的同一文件夹中运行出来?

When pressing F5 , you're using the debugger .F5时,您正在使用调试器

The debugger's settings are separate from the "python.terminal.executeInFileDir": true , and can be changed by creating a launch.json file (or editing the existing one) as described in more detail here .调试器的设置与"python.terminal.executeInFileDir": true是分开的,并且可以通过创建launch.json文件(或编辑现有文件)来更改,如此处更详细描述那样。

Specifically, you will want to add "cwd": "${file}/.." to your launch.json file.具体来说,您需要将"cwd": "${file}/.."添加到您的launch.json文件中。 This will set the directory for debugging to be the encapsulating folder of the file you are running.这会将调试目录设置为您正在运行的文件的封装文件夹。

And you can add "cwd": "${fileDirname}" in the lanuch.json file.您可以在 lanuch.json 文件中添加"cwd": "${fileDirname}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VScode运行代码选择 - VScode run code selection 如何在 vscode 中运行几行选定的代码? - How to run a few selected lines of code in vscode? 如何防止 VSCode 代码运行器扩展在我运行时打开第二个代码终端 - How to prevent VSCode code runner extension from opening second code terminal when I run it 即使使用 selenium 和 python 发生错误,如何使您的代码运行 - How to make your code run even if error occurs using selenium and python 如何使用用户界面为python代码指定“输入”和“输出”的位置,以及如何从UI本身运行代码? - How to give the location of “Input” and “Output” for a python code using User Interface and run the code from UI itself? 如何在VSCode中每次运行代码清除output? 我在 VSCode 中使用终端运行 - How to clear the output everytime run code in VSCode? I'm using terminal in VSCode to run 如何在 VSCode 的终端中运行我的代码? - How do I run my code in the terminal in VSCode? 再次运行代码时如何清除 vscode 终端? - how to clear the vscode terminal when I run the code again? 如何在 VSCode 中运行 python3 代码? /bin/sh: 1: python: 未找到 - How to run python3 code in VSCode? /bin/sh: 1: python: not found 如何使代码块从python中的raw_input运行 - How to make a block of code run from a raw_input in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM