Reputation: 122
I've tried to import a module for testing but received this error:
Traceback (most recent call last): File "BaseTest.py", line 8, in from .main.pageobjects.FBPage import * ModuleNotFoundError: No module named 'main.main'; 'main' is not a package
the project tree looks like this:
/- ProjectDir
/- .src
/- .src.main
/- .src.main.core
/- .src.main.core.BaseCode <- base code to be extended as parent
/- .src.main.core.pageobjects
/- .src.main.core.pageobjects.Module <- a module that inherit from BaseCode
/- .src.tests
/- .src.tests.BaseTest <- main testing module
/- .src.tests.results
I basically did this inside my BaseTest module:
from .main.pageobjects.Module import *
What am I doing here wrong? :)
Upvotes: 4
Views: 8078
Reputation: 166
You have to import specific class (or classes) under the Module. See the code snippet below.I have explained the logic below the code.
from src.main.core.pageobjects.Module.module1 import Module1
from src.main.core.pageobjects.Module.module2 import Module2
Inside the Module, I created two python files: module 1 and module 2; in module1, I created a class - Module1; in module2, I created a class - Module 2; and then I used the below code snippet to import the two classes in the package
src.tests.BaseTest
Click the link for the project structure screenshot. How to import a module from different directory with Python 3? See the python codes for module1, module2, and logintest under BaseTest Module.
class Module1(object): def init(self): print('This is a module 1 example')
def print_info(self):
print("this is module 1 print statement")
class Module2(object): def init(self): print('This is a module 2 example')
def print_info(self):
print("this is module 2 print statement")
from src.main.core.pageobjects.Module.module1 import Module1
from src.main.core.pageobjects.Module.module2 import Module2
m1=Module1()
m2=Module2()
m1.print_info()
m2.print_info()
Run the logintest.py and see the result. The result is from module1 and module2 in the src.main.core.pageobjects.Module package.
C:\Python36\python.exe C:/Users/SeleniumMaster/PycharmProjects/ProjectDir/src/tests/BaseTest/logintest.py
This is a module 1 example
This is a module 2 example
this is module 1 print statement
this is module 2 print statement
Process finished with exit code 0
Upvotes: 4
Reputation: 168
You have to create a file called: __init__.py
in /- .src.main.core.pageobjects. then in BaseTest.py add:
import sys
import os
os.chdir('../main/core/pageobjects')
current_dir = os.getcwd()
sys.path.append(current_dir)
from Module import *
do_something
the code above adds this path (/- .src.main.core.pageobjects) to the PYTHONPATH environment variable. Python uses PYTHONPATH variable to search for the modules that are imported , so once you add the full path , you can access the Module
everywhere.
Upvotes: 2