Fixed: Python NameError, fixed AttributeError and got this? - python

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.

Related

Module has no attribute error in python3

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?

Python: AttributeError: 'module' object has no attribute, which is untrue

What I want to do:
I want to import a python module (pocketsphinx) and use the output from the Decoder attribute. However when I try to use it, I'm informed that module attribute 'Decoder' doesn't exist.
decoder = Decoder(configSwitches)
It does exist, though, which is what makes it so strange.
What I've done so far:
When I pull up a python console and input import pocketsphinx, it imports without any issue. Running pocketsphinx.file returns:
'/usr/local/lib/python2.7/dist-packages/pocketsphinx-0.0.8-py2.7-linux-armv7l.egg/pocketsphinx/__init__.pyc'
Looking in '/usr/local/lib/python2.7/dist-packages/pocketsphinx-0.0.8-py2.7-linux-armv7l.egg/pocketsphinx/__init__.py', I see: from pocketsphinx import * and that's it.
When I go back up to /usr/local/lib/python2.7/dist-packages/pocketsphinx/pocketsphinx.py and open it in a text editor, I see that pocketsphinx.py does indeed have a Decoder class with a healthy number of defined methods.
My Ask:
What other steps can I take to diagnose what's wrong with my use of the pocketsphinx module?
Here's the example code I was trying to run before really digging into the project:
import pocketsphinx
hmmd = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/en-us"
lmdir = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/en-us.lm.bin"
dictp = r"/home/michael/Desktop/sphinxASR/pocketsphinx-5prealpha/model/en-us/cmudict-en-us.dict"
fileName = r'/home/michael/Desktop/sphinxASR/voice_message.wav'
if __name__ == "__main__":
wavFile = open(fileName, "rb")
speechRec = pocketsphinx.Decoder(hmm=hmmd, lm=lmdir, dictionary=dictp)
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
print(result)
Stack trace:
Traceback (most recent call last):
File "/home/michael/PycharmProjects/27test/getHypTest.py", line 14, in <module>
speechRec = pocketsphinx.Decoder(lm=lmdir, dictionary=dictp)
AttributeError: 'module' object has no attribute 'Decoder'
By looking at the pocketsphinx example code, it seems that your import should be:
from pocketsphinx.pocketsphinx import *
My first step diagnosing this issue would be to type the following, so that I can see what is being imported:
import pocketsphinx
dir(pocketsphinx)
You should import Decoder from pocketsphinx.
Instead of
import pocketsphinx
try:
from pocketsphinx.pocketsphinx import Decoder

Import Error using cPickle in Python

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.

AttributeError when importing random

I'm having some issues importing random into my python program. I've read through other threads on this topic and for others, it seemed to stem from the file being named random.py.
My file is not named random.py. I have used print(random.file) to see where it is importing from, and it seems to be importing from C:\Python27\lib\random.pyc
I have tried moving that file out of the folder and it still does not work.
Here is the error:
Traceback (most recent call last):
File "C:/Python27/Projects/Test.py", line 4, in <module>
r1 = random.randomint(20,400)
AttributeError: 'module' object has no attribute 'randomint'
I have also tested in both powershell and the interpreter.
Here is the code snippet:
import random
import getpass
r1 = random.randomint(20,400)
r2 = random.randomint(20,400)
p = getpass.getpass(prompt='Please enter the correct value: %d * %d: ' %(r1,r2))
if p == (r1*r2):
print "Correct"
else:
print "Incorrect"
Can anyone help me out?
Edit: I'm an idiot. Thanks.
Correct name of the function is random.randint not random.randomint.
>> import random
>> random.randint(20,400)
76
AttributeError raise cause of error in function spelling. You should use randint instead of randomint.
Ha I had this too.. I wrote a python file to generate random numbers... but called it random.py so it did not work!... once I renamed it AND deleted random.pyc it worked fine

Writing and importing custom modules/classes

I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.

Categories

Resources