27

I'm trying to run Hadoopy, which has a file _main.pyx, and import _main is failing with module not found in __init__.py.

I'm trying to run this on OS X w/ standard python 2.7.

Dolan Antenucci
  • 15,432
  • 17
  • 74
  • 100

2 Answers2

52

Add this code before you try to import _main:

import pyximport
pyximport.install()

Note that pyximport is part of Cython, so you'll have to install that if it isn't already.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • I don't have that module installed. I downloaded some files from http://www.prescod.net/pyximport/, and then it says I need Pyrex.Distutils. Before I keep digging around for libraries, figured check to see if I'm missing something obvious (i.e. install cython or some other library/app/package) – Dolan Antenucci Sep 22 '11 at 02:21
  • 1
    @dolan: Yes, you'll need Cython. I assumed you already had it installed as your question was tagged with it. – icktoofay Sep 22 '11 at 02:22
  • To install Cython you have 3 options: 1. Run `pip install Cython` or 2. Goto http://cython.org., download it and run `python setup.py install` or 3. Run `pip install Cython --install-option="--no-cython-compile"` – tsveti_iko Aug 27 '18 at 12:29
  • 3
    This still results in a `has no attribute {function name}` for me. My `.pyx` is cythonized python from which I am able to get a `.so` and `.c` file. – mLstudent33 Oct 31 '19 at 02:30
  • 1
    hey @mLstudent33 , have you got the problem solved? – Amarpreet Singh Jun 02 '21 at 04:33
10

You need to make sure you have followed all steps:

  1. Install the Cython package using pip

    pip install Cython
    
  2. Create a Cython file bbox.pyx

    cimport cython
    import numpy as np
    cimport numpy as np
    
    DTYPE = np.float32
    ctypedef np.float32_t DTYPE_t
    
    @cython.boundscheck(False)
    def compare_bboxes(
           np.ndarray[DTYPE_t, ndim=2] boxes1,
           np.ndarray[DTYPE_t, ndim=2] boxes2):
     ...
    
  3. Create setup.py in the same directory

    from distutils.core import setup, Extension
    from Cython.Build import cythonize
    import numpy
    
    package = Extension('bbox', ['bbox.pyx'], include_dirs=[numpy.get_include()])
    setup(ext_modules=cythonize([package]))
    
  4. Build the Cython

    python3 setup.py build_ext --inplace
    
  5. Create your main python script run.py in the same directory

    import pyximport
    pyximport.install(setup_args={"script_args" : ["--verbose"]})
    from bbox import compare_bboxes
    
    def main(args):
       boxes1 = args.boxes1
       boxes2 = args.boxes2
       result = compare_bboxes(boxes1, boxes2)
    
  6. Run your main script in the same directory

    python run.py
    
tsveti_iko
  • 6,834
  • 3
  • 47
  • 39
  • 3
    nice answer; how to solve the case where the main script is not in the same directory of cython module? solved: add to main script: import pyximport pyximport.install() – mrtexaz Jan 28 '22 at 23:09