I am using Pickle in Python2.7. I am getting error while using cPickle.load() method. The code and error is shown below. Can someone guide me through this?
Code:
#! usr/bin/python
import cPickle
fo = open('result','rb')
dict1 = cPickle.load(fo)
Error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 7, in <module>
dicts = cPickle.load(fo)
ImportError: No module named options
It seems like you can not do
import options
but when you or someone else did
cpickle.dump(xxx, open('result', 'rb'))
there was an object with a class or function of a module options that existed at this point in time, in xxx.
Solution
You can open the file binarily and replace options with the module you replaced the old module options with.
You probably created the file in your package like in module package.main by executing the file main.py or something like it, having a module options in the same directory.
Now you do import package.main, try to read the file and options is now called package.options and the module options can not be found.
How did you create this file? How do you load it now? cPickle/pickle does not transfer source code - so if you use a function you need the module when you load it.
Related
My directory looks like this
When I start directly with PyCharm it works.
But when I try to start the script with a commandline I get this error messsage
> python .\PossibilitiesPlotter.py
Traceback (most recent call last):
File "C:\Users\username\PycharmProjects\SwapMatrixPlotter\possibilitiesplotter\PossibilitiesPlotter.py", line 7, in <module>
from plotterresources.PlotterProps import PlotterProps
ModuleNotFoundError: No module named 'plotterresources'
This is how the import looks from my main class PossibilitesPlotter.py
import sys
sys.path.append("plotterresources/PlotterProps.py")
from csv import reader
from pathlib import Path
from plotterresources.PlotterProps import PlotterProps
from possibilitiesplotter.PossibilitiesGraph import PossibilitiesGraph
from possibilitiesplotter.PossibilitiesModel import PossibilitiesModel
class PossibilitiesPlotter:
As a workaround, add the following line to PossibilitesPlotter.py:
sys.path.append("../plotterresources/PlotterProps.py")
This will add the directory one level above the commandline pwd to the PATH variable. So this is always relative to the location of the calling script/shell.
Thus in general:
NEVER append to the PATH/PYTHONPATH variable from within modules. Instead restructure your module. For more details, take a look at the documentation on Packaging Python Projects
I have a question about my new python project. It is the first time that I use different folders for my project.
I have the following structure:
project
src
securityFunc
__init__.py
createCredentialsXML.py
main.py
I work in PyCharm environment.
After pressing Play i get the error message:
Traceback (most recent call last):
File "C:\project\src\main.py", line 1, in <module>
from securityFunc import *
File "C:\project\src\securityFunc\__init__.py", line 1, in <module>
from createCredentialsXML import *
ModuleNotFoundError: No module named 'createCredentialsXML'
My main function looks like this:
from securityFunc import *
if __name__ == '__main__':
generate_key()
__init__.py:
from createCredentialsXML import *
createCredentialsXML.py:
def generate_key():
key = base64.urlsafe_b64encode(os.urandom(2048))
with open("../key/secret.key", "wb") as key_file:
key_file.write(key)
I tried using Path or sys.path to fix the problem. But it does not work.
Can you please tell me how to fix the problem?
Since you're doing a relative import, you need to add a . before your module name:
from .createCredentialsXML import *
The dot means the module is found in the same directory as the code importing the code.
You can read more about it here
createCredentialsXML.py works in the module securityFunc; you must specify the scope of the import. Using
from securityFunc.createCredentialsXML import *
in securityFunc.__init__.py should work.
contents of io.py
class IO:
def __init__(self):
self.ParsingFile = '../list'
def Parser(self):
f = open(ParsingFile, 'r')
print(f.read())
contents of main.py
import sys
sys.path.insert(0, "lib/")
try:
import io
except Exception:
print("Could not import one or more libraries.")
exit(1)
print("Libraries imported")
_io_ = io.IO()
When I run python3 main.py I get the following error:
Libraries imported
Traceback (most recent call last):
File "main.py", line 11, in <module>
_io_ = io.IO()
AttributeError: module 'io' has no attribute 'IO'
Any idea what's going wrong?
My file was called io. It seems that there already exists a package called io which caused the confusion.
Your package name (io) conflicts with the Python library's package with the same name, so you actually import a system package.
You can check this by printing io.__all__.
Changing io.py to something else is probably the best way to go to avoid similar problems. Otherwise, you can use an absolute path.
try
from io import IO
That worked for me when trying to import classes from another file
this has more information:
Python module import - why are components only available when explicitly imported?
I have three database-related classes that I want to combine into a package, in the following structure:
adodb_pyodbc /
__init__.py # empty
PyConnection.py
PyRecordset.py
PyField.py
This package is in my Lib/site-packages folder.
In an earlier iteration of this attempt, I did not use the "Py" prefix, and I got an error complaining that module.__init__() takes only two arguments, and three were being passed into it. Someone suggested that the name "Recordset" might be conflicting with something else, so I changed it.
The classes work when the files are in the same folder as the project that is using them. In that case, I can just use:
PyRecordset.py:
from PyConnection import PyConnection
from PyField import PyField
class PyRecordset: pass
DerivedSet.py
from PyRecordset import PyRecordset
class DerivedRecordset(PyRecordset): pass
But the same files don't work when they are located inside a package. My test program begins with this line:
from adodb_pyodbc import PyConnection as Connection
And when I run it I get this error message:
C:\Python35\python.exe "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py"
Traceback (most recent call last):
File "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py", line 8, in <module>
from Level3_CoilsSet import Level3_CoilsSet
File "C:\Customers\Nucor Crawfordsville\Scripts\64 bit\Testing\Level3_CoilsSet.py", line 1, in <module>
from adodb_pyodbc import PyRecordset as Recordset
File "C:\Python35\lib\site-packages\adodb_pyodbc\PyRecordset.py", line 9, in <module>
from PyConnection import PyConnection
ImportError: No module named 'PyConnection'
But when editing PyRecordset.py inside PyCharm, it appears to be able to find the PyConnection.py file.
I tried using relative addressing inside PyConnection.py:
from . import PyConnection
from . import PyField
But that puts me back to the __init__() error:
C:\Python35\python.exe "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py"
Traceback (most recent call last):
File "C:/Customers/Nucor Crawfordsville/Scripts/64 bit/Testing/cpsa_simulator.py", line 8, in <module>
from Level3_CoilsSet import Level3_CoilsSet
File "C:\Customers\Nucor Crawfordsville\Scripts\64 bit\Testing\Level3_CoilsSet.py", line 3, in <module>
class Level3_CoilsSet(Recordset):
TypeError: module.__init__() takes at most 2 arguments (3 given)
How am I supposed to do this?
Thanks very much for your help. In the meantime, I'm going to take those files out of the package and put them back in my test project. I've wasted far too much time on this question.
When you one to use PyConnection from outside of the package you have to either import it from the module where it was defined:
from adodb_pyodbc.PyConnection import PyConnection as Connection
Or, more conveniently, import it in the package init file adodb_pyodbc/__init__.py:
from .PyConnection import PyConnection
And then, from the outside, you can just do:
from adodb_pyodbc import PyConnection as Connection
FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.