简体   繁体   中英

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 . 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?

os.getcwd() returns the directory where the running file is located if you run the file directly in the terminal or double-click .

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).

It is determined by the way vscode retrieves files.

This is also the reason for the running error in your comments, because your {filePath} is different for the different running way.

You can try interactive Window which is more suitable for your needs.

在此处输入图像描述

or you can use debug mode, and add the following line to your launch.json:

"cwd": "${fileDirname}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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