5

I'm using VSCODE as my editor and using Python 3.7 I have this kind of folder structure

project
|-- util
   | -- drivers.py
   | -- data.py
   | -- __init__.py
|-- test
   | -- driver_test.py
   | -- __init__.py
main.py

I want to import drivers.py from util folder into driver_test.py I tried to do basic import like this

from util.drivers import Driver

which didn't work since it couldn't find util module, then I used another approach by adding a folder to sys.path. like this

# driver_test.py
sys.path.append(os.path.abspath('./util'))
import drivers

I got very confused with several output errors. When I run my unittest from console I'm getting error that drivers are not found

import drivers
ModuleNotFoundError: No module named 'drivers'

And if i run test file in vscode editor by right click and Run current test file, the error output is different that selenium driver is not found which is included inside drivers.py file

from selenium import webdriver
ModuleNotFoundError: No module named 'selenium'

Selenium module is actually working fine and I just wanted to right several unittest for it and most. What I'm doing wrong and how can this be solved? And is it possible to include a module without using sys.path just by using import.

Andrew
  • 1,507
  • 1
  • 22
  • 42
  • How are you running your code? And which version of python? – Code-Apprentice Jun 28 '19 at 15:51
  • You might need to set PYTHONPATH as described [here](https://stackoverflow.com/questions/19917492/how-to-use-pythonpath). – Code-Apprentice Jun 28 '19 at 15:52
  • 1
    @Alexander adding `__init__.py` to test folder didn't help, and i''m running my tests from vscode by right click and as well tried via console – Andrew Jun 28 '19 at 15:55
  • If you want to modify `sys.path`, you don't add packages to it, but _directories that contain packages_ instead. In your case, I think `sys.path.append(os.path.abspath('.'))`will already do, but it's more robust to calculate the path relative to the `__file__` attribute. For example, `sys.path.append(os.path.abspath(os.path.join(__file__, os.pardir)))` - this way the path won't change if you e.g. run the tests from another directory etc. – hoefling Jun 28 '19 at 23:42

1 Answers1

1

You might want to set your PYTHONPATH, to the project directory. More on that in this discussion on the StackOverflow forums or on the official Python website.

peki
  • 669
  • 7
  • 24
  • i'm wondering why did `sys.path` didn't work and keep showing an error with selenium module not found – Andrew Jun 28 '19 at 15:58
  • 1
    @Andrew it is quite possible that VSCode is using a different Python Interpreter, with different modules installed in its directory. Open the Command Pallet (Ctrl + Shift + P) and select "Python: Select Interpreter". Check that it's the version of Python you're looking for. As a worst case scenario, reinstall the module via PIP, in regards to the Selenium related error. – peki Jun 28 '19 at 16:03