Reputation: 13
I'm trying to understand the behaviour of VSCode in relation to running python scripts stored within sub packages of a project. If I have a project structure like the following:
proj/
util/
main/hello.py
test/
If hello.py imports from proj.util - and I use 'Run Python File in Terminal' to execute the script it fails with Module not found (proj.util) - because by default the project top level directory is not added to pythonpath. If I create an .env file in the root and add a definition for PYTHONPATH to include my project top level directory this file is equally not used when running via the option above.
If I create a default set of debug launches and use the 'debug-Python current file in terminal' - this will read the .env file and works as expected.
PyCharm automatically adds the top level project directory to sys.paths when running a script in the terminal - shouldn't VSCode provide such an option or am I missing something?
Current version is as follows, although I see the same behaviour under Windows.
Version: 1.30.1
Commit: dea8705087adb1b5e5ae1d9123278e178656186a
Date: 2018-12-18T22:23:23.072Z
Electron: 2.0.16
Chrome: 61.0.3163.100
Node.js: 8.9.3
V8: 6.1.534.41
OS: Linux x64 4.19.12-arch1-1-ARCH
Upvotes: 1
Views: 5566
Reputation: 3548
TLDR: Start your VS Code with the correct PYTHONPATH
My setup: Set project specific PYTHONPATH from .env automatically with direnv (https://direnv.net/) when changing into project directory. This also sets the needed virtual environment for the project. Start VS Code from command line, so that it uses the correct environment variables.
Alternative you could create a shell script setting the right environment variables and starting VS Code.
Disclaimer: I use absolute imports in my packages, this is not tested with relative imports.
Upvotes: 0
Reputation: 3906
Just add these lines to the top of the file which you want to execute
if __name__ == "__main__":
import os
import sys
sys.path.append(os.getcwd())
These script add the directory, where file in, to your path when executing directly which
__name__ == "__main__"
means.
Upvotes: 0
Reputation: 15980
When you have Python run your hello.py
, PVSC is using the terminal to run python proj/main/hello.py
. To Python that is the same as running python hello.py
from the proj/main
directory which means to the interpreter not even seeing the packages that hello.py
is contained within (hence why it has no concept of proj.util
).
The .env
file isn't used because once again the file is just a direct execution in the terminal and neither your terminal or Python reads the .env
file. But when you use the debugger we get to specify details like using your .env
file and hence why the debugger sets PYTHONPATH
as you expect.
Upvotes: 1