Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

python - Cython: ImportError: No module named 'myModule': how to call a cython module containing a cimport to another cython nodule?

I'm trying to import a cython module data.pyx into another cython module user.pyx. Everything compile fine, but when I try to call user.pyx in a python module, I am getting the error 'ImportError: No module named data'.

Everything is in the same directory.

package/
    __init__.py   #empty
    setup.py      
    data.pxd
    data.pyx
    user.pyx

My setup.py

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext


ext_modules = [
    Extension("data", ["data.pyx"]),
    Extension("user", ["user.pyx"],include_dirs = ['myPackageDir'])
    ]

setup(
  name = 'app',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules  
)

Running the following test.py will raised the error.

import user     #this line raised the 'ImportError: No module named data' below
user.doSomething()

The exception I get is

Traceback:
 File "test.py", line 1, in <module>
    import package.user
  File "user.pyx", line 1, in init user (user.c:3384)
ImportError: No module named data

How can I make the import work? Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I encounter this problem again in an another project. To solve it, here is what I did:

  • all import and cimport statement must be fully qualified
  • all the python code must be contained in a rootFolder
  • the setup.py must be at the same level than the rootFolder
  • all folder in the rooFolder including the rootFolder must contains a __init__.py
  • in your setup.py the extension's include_dirs must contains '.'

I created a simple project which illustrates this here.
This page helped me created it.
But my project is simpler and I think it would have helped me a lot if I had it.
My project also illustrate how to automatically build all cython files in a project.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...