Search code examples
pythonmodulejupyter-notebookjupyter-labopenai-gym

AI Gym environment: no module found error despite all steps correct


I am very sure that I followed the correct steps to register my custom environment in the AI Gym. But I face a problem when one __ init__.py file is not recognizing a folder and gives no module found error. I use Anaconda Jupyterlab through OneDrive so that it is synced and I work from any device.

The path is C-> Users-> myname->OneDrive-> My_code->gym_mycode

  1. gym_mycode--> envs folder and a first __ init__.py file
  2. Inside envs-->another second __ init__.py, custom_env, and some other files

Contents of my first __ init__ are:

from gym.envs.registration import register
register(id="PyABCD-v0", entry_point="gym_mycode.envs:CustomEnv_class")

Contents of my second __ init__ inside the envs folder are:

from gym_mycode.envs.custom_env import CustomEnv_class

This second one gives me the error No module named 'gym_mycode'. How is it possible that it is not recognizing the gym_mycode folder? Is it because I am operating this whole thing inside OneDrive and not some Anaconda specific folder?

I run the first init first and then the second init inside the envs. Hope this order of running is correct.

Edit As asked, below is the current dir and traceback.

os.getcwd() is C:\Users\HP\OneDrive\My_code\gym_mycode\envs

ModuleNotFoundError                       Traceback (most recent call last)
Input In [23], in <cell line: 6>()
      3 import sys
      4 sys.path.append('C:\\Users\\HP\\OneDrive\\My_code\\gym_mycode')
----> 6 from gym_mycode.envs.custom_env import CustomEnv_class

ModuleNotFoundError: No module named 'gym_mycode'

Solution

  • Code may runs in different folder (current working directory - check os.getcwd()) and then import search module gym_mycode in different folder.

    You may need to add folder /full/path/to/My_code to sys.path before import gym_mycode

    Common mistake is to add path to file but it has to be path to folder.

    import sys
    sys.path.append("/full/path/to/My_code")      # add at the end of list
    #sys.path.insert(0, "/full/path/to/My_code")  # add at the beginning of list
    
    import gym_mycode