Shelve import module error python 2.7 - python-2.7

I try to import a custom Class Instance that I shelved but I am getting an:
Import Error: No module named MyModule
All my python modules are located within a directory that contains __init__.py
Here is my puttoshelve.py template to perform the shelve:
from MyModule import MyModule
import shelve
import copy
mymodule = MyModule()
cmymodule = copy.deepcopy(mymodule)
pathtomyshelve ="/some/path/shelve"
cshelve = shelve.open(pathtomyshelve)
cshelve['object'] = cmymodule
cshelve.close()
this actually perform a shelve. If I run an ipython session within the same import shelve and:
from MyModule import MyModule
import shelve
pathtomyshelve ="/some/path/shelve"
shelve_p = shelve.open(pathtomyshelve)
obj = shelve_p['object']
obj
then I get:
{'object': <MyModule.MyModule object at 0x2139510>}
BUT
When I use my outofshelve.py to retrieve my object, which is basically the same code that I ran from the ipython console, I receive:
Import Error: No module named MyModule
What am I missing here? (complete error below)
File "/home/pierre/.qgis2/python/plugins/sig40/sig40_ZR_dialog.py", line 100, in __init__
self.mymodule = shelve_p['object']
File "/usr/lib/python2.7/shelve.py", line 122, in __getitem__
value = Unpickler(f).load()
File "/usr/lib/python2.7/dist-packages/qgis/utils.py", line 454, in _import
mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named MyModule

I had he same Problem when i tried to use my own Logwriter.
I found that solution. (But it is python 3. so the code may change a bit)
cDir = os.path.dirname(os.path.abspath("logWriter.py"))
sys.path.append(os.path.dirname(cDir))
import logClasses.logWriter as log
My Folder Structure is like that
logClasses
init.py
logWriter.py
mailClasses
init.py
sendMail.py <-- This uses the logWriter.py
I hope that solution work for you like it did for me

Related

Django+Cython import cython module in django app views [duplicate]

This question already has an answer here:
Python Package "No module named..."
(1 answer)
Closed 2 years ago.
a newbie to django and Cython. I am creating an app in django and need to import function in views.py from cythonized module. following is views.py inside my app.
from django.shortcuts import render
import sys
import numpy as np
import random
import math
from cython_node_val import node_val
def home(request):
return render(request,'Home.html',{"name":"user"})
def shortest_path1(request):
K=int(request.POST['number of layers'])
if ((K%2!=0) or (K < 0)):
return render(request,"shortest_path1.html",{'shortest_path1':"K must be an even integer"})
else:
......
Node_val=node_val(Hash,C,K) #node_val is from cython_node_val which is a .pyx file, Hash C and K
are defined in body after else statement.
sPath=np.zeros((K,3))
sPath[K-1,:]=Node_val[n-1,:]
for m in range(K-2,-1,-1):
sPath[m,:]=Node_val[int(sPath[m+1,1])]
return render(request,"shortest_path1.html",{'shortest_path1':sPath[:,3]})'''
the directory of my project is like following:
my app directory looks like this
cython_node_val.pyx works fine when importing into a normal .py file, but when doing the same inside views.py in my app it throws me following error
File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\urls.py", line 9, in <module>
from . import views
File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\views.py", line 6, in <module>
from cython_node_val import node_val
ModuleNotFoundError: No module named 'cython_node_val'
I believe if views.py is a python file and we can do operations, it should pull cython_node_val and associated functions. Where am i wrong?
Thanks for your time.
Use os.getcwd() to debug where you are running from your script views.py:
import os
print(os.getcwd())
ModuleNotFoundError: No module named 'cimport'
Then adjust the path to your needs
Is usually an error when you are trying to reference something that isn't in the python running path script + the path that you are giving inside your script.

ModuleNotFoundError for model class in django

I ran into the following ModuleNotFoundError error.
File "C:\django-project\CodingWithMitchBlog\demoproject\Blog\api\urls.py", line 3, in <module>
from demoproject.Blog.api.views import api_detail_BlogPost_view
ModuleNotFoundError: No module named 'demoproject.Blog'
'Blog' is my appname.
This is my project structure.
This might be due to incorrect import statements used in the files. If the import statements has the projectname prefixed try removing it and run again.
For example change:
from demoproject.Blog.models import ModelClass
to
from Blog.models import ModelClass
in the urls.py file

Getting an error in django-admin.py

I have installed django 1.6 using pip on Windows 7. When I try to run django-admin.py, I get this error
C:\django-admin.py startproject test007
Traceback (most recent call last):
File "C:\Python27\Scripts\django-admin.py", line 2 in ?
from django.core import management
File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 55
except ImportError as e:
^
SyntaxError: invalid syntax
in the \management__init__.py, the imports are
import collections
import os
import sys
from optparse import OptionParser, NO_DEFAULT
import imp
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.core.management.color import color_style
from django.utils.importlib import import_module
from django.utils import six
# For backwards compatibility: get_version() used to be in this module.
from django import get_version
Here's the relevant block from the same file
parts = app_name.split('.')
parts.append('management')
parts.reverse()
part = parts.pop()
path = None
# When using manage.py, the project module is added to the path,
# loaded, then removed from the path. This means that
# testproject.testapp.models can be loaded in future, even if
# testproject isn't in the path. When looking for the management
# module, we need look for the case where the project name is part
# of the app_name but the project directory itself isn't on the path.
try:
f, path, descr = imp.find_module(part, path)
except ImportError as e:
if os.path.basename(os.getcwd()) != part:
raise e
else:
if f:
f.close()
while parts:
part = parts.pop()
f, path, descr = imp.find_module(part, [path] if path else None)
if f:
f.close()
return path
in which the same line 55 from the traceback is in the try/except block towards the bottom. I've uninstalled and reinstalled but, to no avail.
It works when I give the/full/path/to/django-admin.py but it shouldn't be required.

python error when importing from __init__ file

I have a package installed in my site-packages dir. Folder structure looks like this
MyPkg\
__init__.py
LogUtils\
__init__.py
logwrapper.py
Shortcuts\
__init__.py <-----this references LogUtils
somefile.py
When I do help ('modules') I see MyPkg listed. But I get the following error in IDLE:
>>> import MyPkg
>>> from MyPkg import LogUtils
>>> from MyPkg import Shortcuts
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
from MyPkg import Shortcuts
File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\__init__.py", line 1, in <module>
from GoToUrl import go_to_url
File "C:\Python27\lib\site-packages\MyPkg\Shortcuts\GoToUrl.py", line 1, in <module>
from LogUtils import logger, log
ImportError: No module named LogUtils
Why would LogUtils import fine standing alone, but throw an error when being imported via an init file??
Seems to me you are lacking some backslashes
MyPkg\
__init__.py
LogUtils\
__init__.py, \
logwrapper.py
Shortcuts\
__init__.py, \
somefile.py
As you see yourself, you are not importing the same module:
>>> from MyPkg import LogUtils
vs.
from LogUtils import logger, log
The first imports a package called MyPkg.LogUtils, the second imports a package called LogUtils. Whether they exist or not depends on your python paths, but in general, if the first one works, change the second one to
from MyPkg.LogUtils import logger, log

Export django settings to my python file

I am trying to make logparser.py in django project which parses the data coming from different servers.
And on running the command on terminal :
$ python logparser.py
This error is coming :
Traceback (most recent call last):
File "logparser.py", line 13, in <module>
SMTP_CONF = settings.SMTP_CONF
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in _setup
self._wrapped = Settings(settings_module)
File "/home/arya/.virtualenv/Devel/.virtualenvs/hu/local/lib/python2.7/site-packages/django/conf/__init__.py", line 134, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'hma.settings' (Is it on sys.path?): No module named hma.settings
my logparser.py contains:
import re
import os
import fnmatch
import gzip
import bz2
from collections import defaultdict
from django.core.mail import send_mail
from django.core.mail.backends import smtp
import smtplib
from email.mime.text import MIMEText
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hma.settings")
from django.conf import settings
SMTP_CONF = settings.SMTP_CONF
def send_email(self,fromaddress,toaddresses,content,subject):
smtp_server = SMTP_CONF["SERVER"]
smtp_username = SMTP_CONF["USERNAME"]
smtp_password = SMTP_CONF["PASSWORD"]
smtp_port = SMTP_CONF["PORT"]
msg = MIMEText(content, 'html', _charset='utf-8')
msg['Subject'] ='Alert message for bad and internal server error'
msg['From'] = fromaddress
msg['To'] = toaddresses
server = smtplib.SMTP(smtp_server,smtp_port)
server.starttls()
server.login(smtp_username,smtp_password)
server.send_mail(fromaddress,toaddresses,msg.as_string())
server.quit()
return True
I know I am doing wrong something with command [python manage.py], but i need to run like this. Any solution for this exporting django settings to separate python file??
Well, This is the exact Usecase why Django provided an ability to create custom commands. You can use all the features of django, in your script, Its like your script will be running inside a Django Container. Here is the Documentation https://docs.djangoproject.com/en/dev/howto/custom-management-commands/.
In case you don't want to use custom management commands though there is also a simple way to run your code within Django's context. Simply put the following at the beginning of your python file, you want to run:
from django.conf import settings
from django.core import management
management.setup_environ(settings)