0
  • VSCode Version: 1.41.1
  • OS Version:Ubuntu 18.04

Steps to Reproduce:

# tree:
.
├── demo1
│   ├── __init__.py
│   └── test.py
├── __init__.py
├── auto.py
# auto.py
def func():
    print("1")
# test.py
from auto import func

func()

Use examples to solve problems that arise in a project Run the test.py file, and I get "ModuleNotFoundError: No module named 'func'" I used 'CTRL '+ left mouse button in test.py to jump to func The same code can be run in pycharm

Derte Trdelnik
  • 2,656
  • 1
  • 22
  • 26
ResistanceTo
  • 63
  • 1
  • 8
  • working directory has to be the root of the file tree, i do not know how to set it in visual studio code (imported modules are imported relative to the working directory when you just run a file) – Derte Trdelnik Jan 03 '20 at 08:06
  • Please note, that importing from outside the package is almost always a bad idea. It involves messing with relative imports, which is, well... messy. Always try to structurize your project to avoid such problems. See https://www.python.org/dev/peps/pep-0008/#imports – Maciej B. Nowak Jan 03 '20 at 08:44

3 Answers3

3

If you run test.py directly then you need to add the parent folder to PYTHONPATH. Try:

import sys
sys.path.append("..\<parent_folder>")
from auto import func

Otherwise, if you merely want to import test.py in another .py file, you can use relative import of python

from . import auto #another dot '.' to go up two packages
auto.func()

Reference

Will
  • 166
  • 1
  • 9
  • Thank you. I just transferred from pycharm to vscode. Previous projects could run without introducing sys, but this one had problems – ResistanceTo Jan 06 '20 at 03:10
0

Simple one-line solution

from ... import auto

and call the function by using auto.func().

Richard
  • 106,783
  • 21
  • 203
  • 265
Rahul kuchhadia
  • 289
  • 4
  • 10
0

Add this in test.py, before import:

import sys
sys.path.insert(0, "/path/to/project/root/directory")

For me it's not a good file organization. A better practice might be as below:

Let your project file tree be like:

.
├── __init__.py
├── lib
│   ├── auto.py
│   └── __init__.py
└── test.py

And write test.py like:

from lib.auto import func

func()
ZhouZhuo
  • 196
  • 2
  • 5