python模块导入问题,大神求解释

不是simaguo 发布于 2015/08/19 21:10
阅读 807
收藏 0

【DevOps必读】产品经理与程序员之间如何破局?>>>

 

刚开始代码

from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))

    def end_element(self, name):
        print('sax:end_element: %s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0" encoding="UTF-8"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)

然后报错

    from xml.parsers.expat import ParserCreate
ImportError: No module named parsers.expat

打印sys.path


['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-i386-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']




然后上面改为



#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
sys.path.append("/usr/lib/python2.7/xml/parsers/")

from expat import ParserCreate


class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))

    def end_element(self, name):
        print('sax:end_element: %s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0" encoding="UTF-8"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)


就好了.小白问一句,刚开始的那段代码

from xml.parsers.expat import ParserCreate

为什么找不到对应的模块呢



加载中
0
s
shenxianghong
你调用的模块的路径不在系统环境中(PATH)
0
铂金胖子
铂金胖子
你的xml模块怎么安装的?用pip吗?
0
cztchoice
cztchoice

我想问,你试过 

from xml import parsers.expat.ParserCreate

这种方法吗?
0
z
zengsun
你仔细查看一下这些目录,是否缺少了__init__.py文件。如果缺少了,那么python不会认为这个目录是模块的。
返回顶部
顶部