I create a python console app that includes imports of a custom class I'm using. Everytime I run my app I get the error ModuleNotFoundError: "No module named 'DataServices'.
Can you help?
Provided below is my folder structure:
ETL
Baseball
Baseball_DataImport.py
DataServices
DataService.py
ConfigServices.py
PageDataMode.py
SportType.py
Here is the import section from the Baseball_DataImport.py file. This is the file when I run I get the error:
from bs4 import BeautifulSoup
import scrapy
import requests
import BaseballEntity
import mechanize
import re
from time import sleep
import logging
import time
import datetime
from functools import wraps
import json
import DataServices.DataService - Error occurs here
Here is my DataService.py file:
import pymongo
import json
import ConfigServices
import PageDataModel
#from SportType import SportType
class DataServices(object):
AppConfig: object
def __init__(self):
AppConfig = ConfigServices.ConfigService()
#print(AppConfig)
#def GetPagingDataBySport(self,Sport:SportType):
def GetPagingDataBySport(self):
#if Sport == SportType.BASEBALL:
pagingData = []
pagingData.append(PageDataModel.PageDataModel("", 2002, 2))
pagingData.append(PageDataModel.PageDataModel("", 2003, 2))
return pagingData
It might seem that your structure is:
Baseball
Baseball_DataImport.py
Dataservices
Dataservice.py
Maybe you need to do from Dataservices.Dataservice import DataServices
Edit:
I created the folder structure, and the method I showed you works:
Here's the implementation
Dataservice.py only contains:
class DataServices():
pass
Did you try copieing the Dataservice.py into the Projectfolder with the main.py?
Related
e.g.
import os as my_os
import my_os.path
ModuleNotFoundError: No module named 'my_os'
but the following script is ok
import os
import os.path
You can't do that in Python.
import statements are importing from Python file names.
You aren't renaming the file of os to my_os, therefore this wouldn't work.
As mentioned in the documentation:
The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.
Tried the similar way as os.py did:
import json as my_json
from my_json.decoder import * # ModuleNotFoundError: No module named 'my_json'
import sys
import json.decoder as my_decoder
sys.modules['my_json.decoder'] = my_decoder
from my_json.decoder import * # it's ok now
How do I import from a higher level directory in python?
For example, I have:
/var/www/PROJECT/subproject/_common.py
/var/www/PROJECT/subproject/stuff/routes.py
I want to import variable A in _common.py to routes.py
# routes.py
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from _common import A
but I get the error:
ImportError:cannot import name 'A'
Change file directory:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../../project")))
from _common import A
OLD VERSION
To solve the issue replace ".." with os.pardir:
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
from _common import A
NEW VERSION
The code above does not solve the problem in the question because the true problem lies in the project structure not in the particular line. The problem is circular import. The problem became clear after the full traceback has been provided. Here is the simple way to reproduce the issue - consider 3 files...
main.py:
import a
a.py:
import b
A = 'A'
b.py:
from a import A
... the error is:
ImportError: cannot import name 'A'
OR
b.py:
import a
BB = a.A
... the error is:
AttributeError: module 'a' has no attribute 'A'
The solution to the problem has been discussed many times - search on SO
So I have this directory structure:
proj/
|
---/subDirA
|
---__init__.py
---fileA.py
|
---/subDirB
|
---__init__.py
---fileB.py
|
---start.py
So what I'm trying to do is from fileB.py import a function in FileA.py. So I tried this:
from subDirA.fileA import funct
When I do this I get the following error:
ImportError: cannot import name funct
But If I do this instead:
from subDirA.fileA import *
I dont get the error.. Can some one explain why am I getting this error?
I also tried the following without any success: (using absolute_import)
from .subDirA.fileA import funct
(The real function name is send_message())
UPDATE
Here are the real imports for better reference, in File A I have the following imports:
import pika
import logging
import tasks
import ConfigParser
and here I have a function def:
def send_message():
and in FileB I have:
from celery.utils.log import get_task_logger
from jsonpath_rw import parse
import dateutil.parser
import json
from pikahelper.rabbit import * # Tried using send_message and it exploded, weird..
##
# SubDirA/FileA.py => pikahelper/rabbit.py ;)
##
Also I'm calling start.py which also calls SubDirA/FileA.py for another function..
In Blender 2.62 I was using this script to display a point:
import bpy
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from add_utils import AddObjectHelper, add_object_data
data0=[]
data0.append((float(69.3456), float(36.4562), float(26.8232)))
me0 = bpy.data.meshes.new( name = "point cloud0")
me0.from_pydata( data0, [], [] )
me0.update()
add_object_data(bpy.context, me0, [])
After having updated to Blender 2.67a the execution returns a failure and the following error is reported in the console window:
ImportError: No module named 'add_utils'
Do you have any clue why this should not work anymore?
Thank you :)
Add the missing bpy_extras import at the start of the script
import bpy
import bpy_extras
from bpy.props import FloatVectorProperty, IntProperty, FloatProperty
from bpy_extras import object_utils.object_data_add
from bpy_extras import AddObjectHelper
The API for add_object_data appears to have changed to object_data_add so you'll need to change that in the script too.
object_data_add(bpy.context, me0, [])
I have a module that I am testing that depends on another module that won't be available at the time of testing. To get around this, I wrote (essentially):
import mock
import sys
sys.modules['parent_module.unavailable_module'] = mock.MagicMock()
import module_under_test
This works fine as long as module_under_test is doing one of the following import parent_module, import parent_module.unavailable_module. However, the following code generates a traceback:
>>> from parent_module import unavailable_module
ImportError: cannot import name unavailable_module
What's up with this? What can I do in my test code (without changing the import statement) to avoid this error?
Alright, I think I've figured it out. It appears that in the statement:
from parent_module import unavailable_module
Python looks for an attribute of parent_module called unavailable_module. Therefore, the following set up code fully replaces unavailable_module within parent_module:
import mock
import sys
fake_module = mock.MagicMock()
sys.modules['parent_module.unavailable_module'] = fake_module
setattr(parent_module, 'unavailable_module', fake_module)
I tested the four import idioms of which I am aware:
import parent_module
import parent_module.unavailable_module
import parent_module.unavailable_module as unavailabe_module
from parent_module import unavailable_module
and each worked with the above set up code.