Skip to main content
 首页 » 编程设计

python之模块导入路径

2025年05月04日13shanyou

我无法测试运行我想使用的 cssparser。

测试.py:

from css.parse import parse 
 
data = """ 
    em { 
    padding: 2px;  
    margin: 1em; 
    border-width: medium; 
    border-style: dashed; 
    line-height: 2.4em; 
    } 
    p { color: red; font-size: 12pt } 
    p:first-letter { color: green; font-size: 200% } 
    p:first-line { color: blue }""" 
 
 
for rule in parse(data): 
    print (rule) 

..给出一个错误:

Traceback (most recent call last): 
  method <module> in test.py at line 1 
    from css.parse import parse 
  method <module> in test.py at line 6 
    from . import css, csslex, cssyacc 
  method <module> in test.py at line 8 
    from . import serialize 
  method <module> in test.py at line 6 
    from . import css 
ImportError: cannot import name css 

目录结构(/Users/nimbuz/Documents/python31):

/Users/nimbuz/Documents/python31/**csspy**/ 
| 
+-- css/ (*has __init__.py*) 
| 
+-- uri/ (*has __init__.py*) 
| 
+-- test.py 

print(sys.path) 显示:

['/Users/nimbuz/Documents/python31/csspy', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages'] 

请您参考如下方法:

这是我刚刚测试的几个步骤。

  • readme说是python 2.5,所以需要python 2.x系列

  • 我已经创建了一个文件夹 C:/TEST/

  • 我已经从 css-py svn 下载了所有文件到 C:/TEST/,所以 C:/TEST/css/ 和 C:/TEST/uri/ 文件夹现在存在。

  • 我已经下载了ply's tar gz file并将仅 ply文件夹提取到C:/TEST/css/中,所以C:/TEST/css/ply/ 文件夹现在存在。

  • 我已经在 C:/TEST/ 中创建了 test.py 内容

    from css.parse import parse 
    print dir(parse) 
    
  • 我运行它,结果是这样的,没有导入错误:

    C:\TEST>test.py

    ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__' , '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', ' __subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

希望这对您有所帮助。对不起,如果我的解释不好。