How to run python interactive in current file's directory in Visual Studio Code?
问题
When executing "Run Selection/Line in Python Terminal"
command in VSCode, terminal's current working directory is the workspace root directory. How can we set current directory of terminal to the current file's directory when running the selection/line?
回答1
I used the option Run -> Add Configuration (or Open configuration, if available) This will open your current 'launch.json' file. Now you may add this line to the configuration wanted (in my case was Python):
"cwd": "${fileDirname}"
This line will make VSCode to run your stuff in the same folder as the file is being executed.
You can get more details in this link: https://code.visualstudio.com/docs/editor/variables-reference
Here is my full json file (just for reference):
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${fileDirname}"
}
]
}
回答2
Update following release 2019.10.44104
Following release 2019.10.44104 of the VS Code python extension, you can now set the python.dataScience.notebookFileRoot
to ${fileDirname}
to directly start the python interactive window in the directory of the file you're running.
Note that the root directory will not change if you then run code from another file unless you interrupt/restart the kernel (or close VS Code). On this aspect, see the following comment and the corresponding github issue.
For the Python Interactive Window, the setting you're looking for is python.dataScience.notebookFileRoot
. However, as explained in this answer to a similar question,
Always opening on the file location (without having to set
notebookFileRoot
to an absolute path per folder) is not supported via thenotebookFileRoot
setting. The VSCode variables such as${fileDirname}
are specific to task and debug configuration files (launch.json
andtask.json
).
See also the associated github issue.
As indicated, you can still set this setting to a specific absolute path, which might be enough if you're mainly working on a single project at a time.
Alternatively, you could also add the following code at the top of your script/notebook:
import os
os.chdir('absolute-path-to-workingDir')
标签:Code,run,python,current,file,directory From: https://www.cnblogs.com/chucklu/p/16905468.html