cython_helper.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from __future__ import division, absolute_import, print_function, unicode_literals
  2. __USE_CYTHON_NO = 0 # Do not use Cython.
  3. __USE_CYTHON_TRY = 1 # Try to use Cython, if available.
  4. __USE_CYTHON_FORCE = 2 # Use Cython. Abort if not available.
  5. __USE_CYTHON_VERBOSE = 3 # Use Cython. Abort if not available. Be verbose.
  6. __useCython = None
  7. def cythonModuleName(modname):
  8. elems = modname.split(".")
  9. elems[0] = elems[0] + "_cython"
  10. return ".".join(elems)
  11. def __checkCython():
  12. global __useCython
  13. import os
  14. if __useCython is None:
  15. try:
  16. __useCython = int(os.getenv("AWLSIM_CYTHON",
  17. str(__USE_CYTHON_NO)))
  18. if __useCython not in (__USE_CYTHON_NO,
  19. __USE_CYTHON_TRY,
  20. __USE_CYTHON_FORCE,
  21. __USE_CYTHON_VERBOSE):
  22. raise ValueError
  23. except ValueError:
  24. __useCython = __USE_CYTHON_NO
  25. def shouldUseCython(modname=None):
  26. __checkCython()
  27. if __useCython == __USE_CYTHON_VERBOSE and modname:
  28. print("Awlsim-cython: Importing '%s' instead of '%s'" %\
  29. (cythonModuleName(modname), modname))
  30. return __useCython != __USE_CYTHON_NO
  31. def cythonImportError(modname, message):
  32. global __useCython
  33. import sys, os
  34. def perr(msg):
  35. if sys.stderr:
  36. sys.stderr.write(msg)
  37. sys.stderr.flush()
  38. if __useCython == __USE_CYTHON_TRY:
  39. perr("WARNING: Failed to import awlsim CYTHON module '%s': %s\n"
  40. "--> Falling back to standard Python modules...\n" %\
  41. (modname, message))
  42. __useCython = __USE_CYTHON_NO
  43. elif __useCython in (__USE_CYTHON_FORCE, __USE_CYTHON_VERBOSE):
  44. perr("\n\nERROR: Failed to import awlsim CYTHON module '%s': %s\n\n"
  45. "Python interpreter: %s\n"
  46. "PYTHONPATH=\"%s\"\n\n"
  47. "Aborting.\n" %\
  48. (modname, message, sys.executable, os.environ.get("PYTHONPATH", "")))
  49. sys.exit(1)