简体   繁体   English

使用 os.getcwd() 时,如何将 Visual Studio 代码中的 Python 和 Python 转换为 output sem?

[英]How do I get Python and Python in Visual Studio code to output the sem when using os.getcwd()?

I wanted to make it easier to edit my code on different devices with different usernames, so I decided to change how my code knows where my files are.我想让使用不同用户名在不同设备上编辑我的代码变得更容易,所以我决定改变我的代码知道我的文件位置的方式。 Instead of using the entire file path, I decided to use os.getcwd but when I run it in Visual Studio Code I only get C:\Users\Name while when I run it with just python I get C:\Users\Name\Yuna-Discord-Bot .我决定使用os.getcwd而不是使用整个文件路径,但是当我在 Visual Studio Code 中运行它时,我只得到C:\Users\Name而当我只使用 python 运行它时,我得到C:\Users\Name\Yuna-Discord-Bot And for both I am using the same code:对于两者,我都使用相同的代码:

import os

test=(os.getcwd())
print(test)
input("Enter to close")

Is there any way to get them to get Visual Studio Code to the same as just python, or vice versa?有什么方法可以让他们将 Visual Studio Code 设置为与 python 相同,反之亦然?

os.getcwd() returns the directory where the running file is located if you run the file directly in the terminal or double-click . os.getcwd()返回运行文件所在目录,如果直接在终端运行文件或双击运行文件。

However if you run the file in vscode it should be noted that no matter where the file you are running, the cwd you get will still be the workspace instead of the folder where the file is located (even the file is in the deep directory).但是如果你在vscode中运行该文件需要注意的是,无论你运行的文件在哪里,你得到的cwd仍然是工作空间而不是文件所在的文件夹(即使文件在深层目录中) .

It is determined by the way vscode retrieves files.由vscode检索文件的方式决定。

This is also the reason for the running error in your comments, because your {filePath} is different for the different running way.这也是你评论中运行错误的原因,因为不同的运行方式你的{filePath}是不同的。

You can try interactive Window which is more suitable for your needs.您可以试试交互式Window,哪个更适合您的需求。

在此处输入图像描述

or you can use debug mode, and add the following line to your launch.json:或者您可以使用调试模式,并将以下行添加到您的 launch.json:

"cwd": "${fileDirname}"

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM