[CMake] Finding Python Modules with CMake
Mark Moll
mmoll at rice.edu
Mon Jan 3 10:49:34 EST 2011
On Jan 3, 2011, at 2:17 AM, Todd Gamblin wrote:
> Is there a way in CMake, once I find the python interpreter, to query for the availability of a particular module? e.g. say I want to make sure that the host's python installation has PyQt4, or numy, or something like that. Do I have to manually run the interpreter, try to import it, and check the return code, or is there a builtin for that?
>
> Something like this would be handy for the python modules:
>
> http://www.gnu.org/software/autoconf-archive/ax_python_module.html
>
> Again, I couldn't find much in the docs for this.
>
Yes. I wrote this function (which relies on PYTHON_EXEC pointing to the python executable):
function(find_python_module module)
string(TOUPPER ${module} module_upper)
if(NOT PY_${module_upper})
if(ARGC GREATER 1 AND ARGV1 STREQUAL "REQUIRED")
set(${module}_FIND_REQUIRED TRUE)
endif()
# A module's location is usually a directory, but for binary modules
# it's a .so file.
execute_process(COMMAND "${PYTHON_EXEC}" "-c"
"import re, ${module}; print re.compile('/__init__.py.*').sub('',${module}.__file__)"
RESULT_VARIABLE _${module}_status
OUTPUT_VARIABLE _${module}_location
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT _${module}_status)
set(PY_${module_upper} ${_${module}_location} CACHE STRING
"Location of Python module ${module}")
endif(NOT _${module}_status)
endif(NOT PY_${module_upper})
find_package_handle_standard_args(PY_${module} DEFAULT_MSG PY_${module_upper})
endfunction(find_python_module)
You can then write:
find_python_module(PyQt4 REQUIRED)
--
Mark Moll
More information about the CMake
mailing list