SoFunction
Updated on 2024-11-16

pyx file Generate pyd file for cython call implementation

The pyx file is a c extension for python, the code has to conform to the cython specification and be written in whatever editor is available. I wrote it on eric4, and it turned out that it defaults to the python interpreter and suggests a bug, "syntax error".

The pyx file above is just a source code file. To be called and run by python, it is not enough to just write the source code. To be called by python and run, it is not enough just to write the source code. Specifically, it has to be converted into .c or .c++ files, and further converted into .pyd files.

The pyd file is the one that can be used directly. In order to achieve the above, a script has to be written as follows:

#!/usr/bin/python
#python version: 2.7.3
#Filename:  
# Run as: 
# python  build_ext --inplace 
 
import sys 
(0, "..") 
 
from  import setup 
from  import Extension 
from  import cythonize 
from  import build_ext
 
# ext_module = cythonize("") 
ext_module = Extension(
   "TestOMP",
  [""],
  extra_compile_args=["/openmp"],
  extra_link_args=["/openmp"],
  )
 
setup(
 cmdclass = {'build_ext': build_ext},
 ext_modules = [ext_module], 
)

This is entirely a python script that can be run under a python interpreter.

Under the console, the file was generated by running the following command 'python build_ext --inplace'.

Of course, at the same time there are some miscellaneous files, such as the 'lib' files under the 'build' directory.

This all hints that this is in a windows vistual studio environment.

Under linux+gcc, you have to generate the .so file, and the option "/openmp" has to be written as "-fopenmp".

write

File the above two steps, the equivalent of a python efficiency bottleneck module (which before you need to use the profile tool to locate) with more efficient code written in the form of python's c extension, the next step is to call them in python code. It is this calling script, as follows:

from TestOMP import Test 
Test()

This is easy enough to import and call. Under the console, type "python" and run it.

Addendum: python can't import Cython .pyx files?

Solution:

Add before importing the appropriate package:

import pyximport
()

If you run the program after the above installation is complete and the

No module named pyximport

Needed at this point:

pip install Cython 

That's it.

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more. If there is any mistake or something that has not been fully considered, please do not hesitate to give me advice.