I looked up a lot of threads but none solved my issue
I have the following dir in my project
my_proj
folder_one
__init__.py
file_one.py
folder_two
__init__.py
file_two.py
__init__.py
main.py
I am trying to import from file_two.py
the FileTwo
class:
file_one.py:
from folder_two.file_two import FileTwo
But i get the following error when I try to run the file_one.py
file:
ModuleNotFoundError: No module named 'folder_two'
I tried the following:
- Adding
PYTHONPATH
to .env file - Adding
"python.envFile": "${workspaceFolder}/.env"
to settings.json - Adding
"terminal.integrated.env.osx"
to settings.json - Adding
"python.analysis.extraPaths"
to settings.json - Adding
"python.autoComplete.extraPaths"
to settings.json - Adding
__init__.py
to every folder exists in my project
When I print the sys.path
from file_one.py
I get the path: /my_proj/folder_one
instead of /my_proj
How can I add the /my_proj
root directory of my project to sys.path (not permanently) so I could run any python file in my project and still access all files?
CodePudding user response:
The import line be modified as from folder_two.file_two import FileTwo
, notice that .py
is removed.
Then in the root directory, python main.py
should work.
Also, if file_one.py has a main function, then you can launch with
python -m folder_one.file_one
. Noticed that .py
is not used.
Be aware to test the problems in terminal first. There are more tricky parts in IDEs, e.g. Pycharm
, since they might automatically change working directories or do something else that is not so obvious.
CodePudding user response:
How do you modified the "terminal.integrated.env.osx"
? Like this?
"terminal.integrated.env.osx": {
"PYTHONPATH": "${workspaceFolder};",
},
And what you have added in the .env
file? Like this(just an example, an absolute path)?
PYTHONPATH=c:\\Work\\python3.10
The PYTHONPATH environment variable specifies additional locations where the Python interpreter should look for modules. In VS Code, PYTHONPATH can be set through the terminal settings (terminal.integrated.env.*) and/or within an .env file.
When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.
When PYTHONPATH is set using an .env file, it will affect anything the extension does on your behalf and actions performed by the debugger, but it will not affect tools run in the terminal.
If needed, you can set PYTHONPATH using both methods.
You can refer to the official docs.