Python Error : Importing library : ModuleNotFoundError: No module named 'InitProject'

Question:

I am setting up a python project using RobotFramework and it is throwing No module named error even if I have added a Library entry in init.resource.

Also, I created an empty init.py in the folder in which the file exists so that the python file can be located.

My project structure is as below:

enter image description here

My Code is as below:

init.robot

*** Settings ***
Library  MyLibrary.py
Test Setup       Setup
Test Teardown    Do Teardown

HelloVariable.robot

*** Settings ***
Resource  init.resource

*** Test Cases ***
My First Robot Test
    Say Hello From Library
    Log To Console  ${Data}

init.resource

*** Settings ***
Library  test.py
Library  MyLibrary.py
Library  InitProject/ProtoFolder/ProtoService.py

MyLibrary.py

# mylibrary.py
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
import json

from InitProject.ProtoFolder.ProtoService import *

class MyLibrary:
    def __init__(self):
        self.data = None

    @keyword("Setup")
    def setup(self):
        logger.console("Setting up test environment...")
        self.data = {"key1": "value1", "key2": "value2"}
        BuiltIn().set_test_variable("${Data}", self.data)

        with open('/InitProject/ProtoFolder/RobotFramework/test.json') as f:
            data = json.load(f)

        logger.console(data)

    @keyword("Do Teardown")
    def teardown_test_environment(self):
        logger.console("Tearing down test environment...")
        self.data = None
        ProtoService.proto_methods()

ProtoService.py

from robot.api import logger
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn


class ProtoService:

    def proto_methods(self):
        logger.console("Proto Method Called")

Actual Error:

er/RobotFramework/MyLibrary.py' failed: ModuleNotFoundError: No module named 'InitProject'
Traceback (most recent call last):
  File "/Users/user/Python/pythonProject4/InitProject/ProtoFolder/RobotFramework/MyLibrary.py", line 7, in <module>
    from InitProject.ProtoFolder.ProtoService import *
PYTHONPATH:
Asked By: JavaMan

||

Answers:

The code works after I add following however, I don’t think it’s a clean solution (or if there is a way to replace /Users/user/Python with an in-built variable).

import sys
sys.path.append('/Users/user/Python/pythonProject4/')

from InitProject.ProtoFolder.ProtoService import ProtoService
Answered By: JavaMan