I'm trying to learn Python's SAX module from O'Reilly's Python and XML. I'm trying to run the following sample code, but I keep getting an error and I can't figure out why.
The first file is handlers.py:
class ArticleHandler(ContentHandler):
"""
A handler to deal with articles in XML
"""
def startElement(self, name, attrs):
print "Start element:", name
The second file is art.py, which imports the first file:
#!/usr/bin/env python
# art.py
import sys
from xml.sax import make_parser
from handlers import ArticleHandler
ch = ArticleHandler( )
saxparser = make_parser( )
saxparser.setContentHandler(ch)
saxparser.parse(sys.stdin)
When I try to run art.py, I get the following:
% python art.py < article.xml
Traceback (most recent call last):
File "art.py", line 7, in <module>
from handlers import ArticleHandler
File "~/handlers.py", line 1, in <module>
class ArticleHandler(ContentHandler):
NameError: name 'ContentHandler' is not defined
I'm probably missing something obvious. Can anybody help?
Thanks!
You have to import ContentHandler in handlers.py as follows:
from xml.sax.handler import ContentHandler
This should do it.
Related
I'm getting this error when trying to import a module from the Prov package.
Here is the contents of my file:
#!/usr/bin/env
import sys
egg_path='/Library/Python/2.7/site-packages/prov-1.5.0-py2.7.egg/prov'
sys.path.append(egg_path)
#... rest of code
import model as prov
def main():
# Create a new provenance document
d1 = ProvDocument() # d1 is now an empty provenance document
# Declaring namespaces for various prefixes used in the example
d1.add_namespace('now', 'http://www.provbook.org/nownews/')
d1.add_namespace('nowpeople', 'http://www.provbook.org/nownews/people/')
d1.add_namespace('bk', 'http://www.provbook.org/ns/#')
# Entity: now:employment-article-v1.html
e1 = d1.entity('now:employment-article-v1.html')
# Agent: nowpeople:Bob
d1.agent('nowpeople:Bob')
And here is the output:
Traceback (most recent call last):
File "prov.py", line 6, in <module>
import model as prov
File "/Library/Python/2.7/site-packages/prov-1.5.0-py2.7.egg/prov/model.py", line 25, in <module>
from prov import Error, serializers
ImportError: cannot import name Error
Any ideas or fixes? I installed Prov using easy_install prov.
You need to rename your module file prov.py. It prevents import of the third-party library because the module name conflicts.
Make sure prov.pyc is removed.
I found the error. The name of my file that I was trying to import into was also called prov.py . It was a circular dependency issue.
Thank you guys for such quick responses!
I have this:
import sys, struct, random, subprocess, math, os, time
from m_todo import ToDo
(rest)
Which results in:
Traceback (most recent call last):
File "6.py", line 2, in <module>
from m_todo import ToDo
ImportError: cannot import name ToDo
My m_todo module:
import os
class ToDO:
'''todo list manager'''
def __init__(self):
pass
def process(self):
'''get todo file ready for edition'''
print(os.path.exists('w_todo.txt'),'\t\t\tEDIT THIS')
I read some similar questions, which suggested something about circular references, but it is not the case.
I also saw a suggestion about using relative imports, but trying that resulted in another error:
Traceback (most recent call last):
File "6.py", line 2, in <module>
from .m_todo import ToDo
SystemError: Parent module '' not loaded, cannot perform relative import
This is like the third time I use Python, so it might be a silly mistake, but it's causing me some confusion since I'm importing other modules in the same way without any issues.
So... what's going on here?
Your class is called ToDO (note the capitalisation), not ToDo.
Either fix your import:
from m_todo import ToDO
or the classname:
class ToDo:
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.
I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py
python code:
def hello_func():
print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()
error message:
Traceback (most recent call last):
File "C:/Python33/hello_module.py", line 9, in <module>
import hello_module
File "C:/Python33\hello_module.py", line 10, in <module>
hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.
You can put the function in a separate file, then import that:
File foo.py:
def def hello_func():
print ("Hello, World!")
File bar.py:
import foo
foo.hello_func()
and run bar.py as a script.
If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.
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.