问题
I am trying to bring my (working/executable) project from PyCharm to VS Code. My folder structure looks like this (simplified):
root
|- .venv
|- src
|- helper
|- windows
|- main
|- __init__.py
|- main_window.py
|- __init__.py
I'm trying to execute the src/__init__.py file, which has the following code:
from PyQt5.QtWidgets import QApplication
from src.windows.main import MainWindow
import sys
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())
This works perfectly in PyCharm, but VS Code gives me the following error:
ModuleNotFoundError: No module named 'src'
I've tried numerous solutions from the internet (Stack Overflow and official VS Code documentation), including modifying settings.json and launch.json. Currently my JSONs look like this:
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"pythonPath": "${config:python.pythonPath}",
"env": {
"PYTHONPATH": "${workspaceFolder}\\src"
}
}
]
}
settings.json (User):
{
"workbench.iconTheme": "Monokai Classic Icons",
"editor.fontSize": 16,
"editor.letterSpacing": 1,
"editor.lineHeight": 27,
"editor.fontFamily": "'Roboto Mono', monospace",
"editor.fontWeight": "300",
"workbench.colorTheme": "Monokai Classic",
"window.zoomLevel": 0,
"terminal.integrated.fontFamily": "'Inconsolata', monospace",
"terminal.integrated.fontSize": 18,
"python.autoComplete.addBrackets": true,
"bracket-pair-colorizer-2.colors": [
"White"
]
}
settings.json (Workspace):
{
"python.pythonPath": "c:\\Users\\username\\PycharmProjects\\Snake_It_Off\\.venv\\Scripts\\python.exe",
"python.linting.pylintEnabled": false,
"python.linting.enabled": true,
"python.linting.pycodestyleEnabled": true
}
However, I'm still getting the error. Is this a VS Code issue? In PyCharm, I could just mark several folders as sources (and it automatically detected any folder containing __init__.py as a module). How do I correctly set up the project to be able to run it?
回答1:
I finally managed to solve my problem. I had to move my main executable file, src/__init__.py, outside of the src folder, since executing a script from withing a package can cause problems. Another important step was double-checking that my PYTHONPATH is set correctly by running the following code:
import sys
print(sys.path)
来源:https://stackoverflow.com/questions/58441104/how-do-i-set-up-imports-for-custom-modules-in-vs-code