How to change VS code working directory to the running file directory
Asked Answered
P

4

5

I've been trying to set the default working directory in VS Code, when a workspace is not open, to the directory where the file being executed is. This is the normal behaviour in other IDEs, like Python IDlE. I need this so my students can run a program from whatever folder they have it in, and it can open files referred to by their program using relative reference. They always have the file in the same directory as the running file (for example an MP3 that they want to open during their program).

I've read for hours lots of documentation, both in VS Code and Stackoverflow, without success.

I know that setting a workspace to that folder will solve it, but is not a viable solution for us, as they will be opening files from different locations all of the time.

I've tried changing the terminal.integrated.cwd in the settings.json file to take by default the directory where the file being executed is (like in IDlE), without success. I can't find the string that I need to include in terminal.integrated.cwd for this. I've tried the following strings ".", ".", ".\", ""

I've also tried this:

"terminal.integrated.cwd": "${fileDirname}"

But when I run the following piece of code to see if the working directory has changes, after reset of VS code:

import os
cwd = os.getcwd()
print("Current working directory: {0}".format(cwd))

It still shows me the working directory as c:\users\my_user_name And not the one where the file running this code is.

Could someone please tell me what can I do next? Thank you.

Pearman answered 1/6, 2021 at 8:46 Comment(0)
P
15

Murphy's law, 5 minutes after posting the question (and after hours of research) I come across this post with a solution that works perfectly. Settings--> Python>Terminal>Execute In File Dir

Pearman answered 1/6, 2021 at 9:27 Comment(0)
P
0

I think, os.chdir(path) can be a solution in your case.

https://docs.python.org/3/library/os.html#os.chdir

Pallas answered 1/6, 2021 at 8:56 Comment(0)
C
0

Instead of depending on IDE settings, you can code it and make it platform independent.

import pathlib
file = pathlib.Path(__file__).parent.resolve() / input("Enter image name: ")
image1 = cv2.imread(str(file))
Chaoan answered 27/2, 2023 at 16:11 Comment(0)
E
0

I found it in the python extension settings within VS Code

Python › Terminal: Execute In File Dir

  • When executing a file in the terminal, whether to use execute in the file's directory, instead of the current open folder.

Extension Settings Here:

Elidiaelie answered 19/11, 2023 at 14:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.