Reputation: 241
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.
Upvotes: 6
Views: 14306
Reputation: 241
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
Upvotes: 17
Reputation: 1
I found it in the python extension settings within VS Code
Python › Terminal: Execute In File Dir
Upvotes: 0
Reputation: 1
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))
Upvotes: 0
Reputation: 84
I think, os.chdir(path)
can be a solution in your case.
https://docs.python.org/3/library/os.html#os.chdir
Upvotes: 0