I'm just starting with Python and do have more experience with C#\Java. So what makes my head hurt is how do I import my Python modules to another custom module? I've already tried couple of things:
SO: Python can't find my module
SO: Cant import my own modules
SO: Import Error: no module named when importing my own module
and several more, but those generally sugget me to use relative imports (using appropriate number of .
before import statement). It seems fragile to me because as far as I know imports are relative and resolved depending on where file.py
was executed.
So here is my project structure in PyCharm:
Project
├───lib
│ ├───__init__.py
│ ├───pages
│ │ ├───__init__.py
│ │ ├───pageA.py
│ │ └───pageB.py
│ └───actions
│ ├───__init__.py
│ ├───actionA.py
│ └───actionB.py
├───tests
│ ├───__init__.py
│ ├───base_test.py
│ └───search_test.py
└───main.py
In my search_test.py
I do import module from lib.actions.actionA import ActionA
, in actionA.py
I'm importing module like from lib.pages.pageA import PageA
. And here is my main.py
:
import unittest
from tests.search_test import SearchTest
def create_test_suite():
test_suite = unittest.TestSuite()
test_suite.addTest(SearchTest())
return test_suite
if __name__ == 'main':
suite = create_test_suite()
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
When I run this within PyCharm it works perfectly. But now I need to run it from console:
D:\Projects\Python Projects> python -m unittest project_name.main
and I'm facing ImportError: no module named 'lib'
. With this:
D:\Projects\Python Projects\project_name> python main.py
nothing happens.
What can I do? Should I stick to relative pattern or there is some kind of Java-like packages importing?