Python.cmake 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # Filename: Python.cmake
  2. #
  3. # Description: This file provides support functions for building/installing
  4. # Python extension modules and/or pure-Python packages.
  5. #
  6. # Functions:
  7. # add_python_target(target [source1 [source2 ...]])
  8. # install_python_package(path [ARCH/LIB])
  9. # ensure_python_init(path [ARCH] [ROOT] [OVERWRITE])
  10. #
  11. #
  12. # Function: add_python_target(target [EXPORT exp] [COMPONENT comp]
  13. # [source1 [source2 ...]])
  14. # Build the provided source(s) as a Python extension module, linked against the
  15. # Python runtime library.
  16. #
  17. # Note that this also takes care of installation, unlike other target creation
  18. # commands in CMake. The EXPORT and COMPONENT keywords allow passing the
  19. # corresponding options to install(), but default to "Python" otherwise.
  20. #
  21. function(add_python_target target)
  22. if(NOT HAVE_PYTHON)
  23. return()
  24. endif()
  25. string(REGEX REPLACE "^.*\\." "" basename "${target}")
  26. set(sources)
  27. set(component "Python")
  28. set(export "Python")
  29. foreach(arg ${ARGN})
  30. if(arg STREQUAL "COMPONENT")
  31. set(keyword "component")
  32. elseif(arg STREQUAL "EXPORT")
  33. set(keyword "export")
  34. elseif(keyword)
  35. set(${keyword} "${arg}")
  36. unset(keyword)
  37. else()
  38. list(APPEND sources "${arg}")
  39. endif()
  40. endforeach(arg)
  41. string(REGEX REPLACE "\\.[^.]+$" "" namespace "${target}")
  42. string(REPLACE "." "_" underscore_namespace "${namespace}")
  43. string(REPLACE "." "/" slash_namespace "${namespace}")
  44. add_library(${target} ${MODULE_TYPE} ${sources})
  45. target_link_libraries(${target} PKG::PYTHON)
  46. if(BUILD_SHARED_LIBS)
  47. set_target_properties(${target} PROPERTIES
  48. LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/${slash_namespace}"
  49. OUTPUT_NAME "${basename}"
  50. PREFIX ""
  51. SUFFIX "${PYTHON_EXTENSION_SUFFIX}")
  52. if(PYTHON_ARCH_INSTALL_DIR)
  53. install(TARGETS ${target} EXPORT "${export}" COMPONENT "${component}" DESTINATION "${PYTHON_ARCH_INSTALL_DIR}/${slash_namespace}")
  54. endif()
  55. else()
  56. set_target_properties(${target} PROPERTIES
  57. OUTPUT_NAME "${basename}"
  58. PREFIX "libpython_${underscore_namespace}_")
  59. install(TARGETS ${target} EXPORT "${export}" COMPONENT "${component}" DESTINATION lib)
  60. endif()
  61. set(keywords OVERWRITE ARCH)
  62. if(NOT underscore_namespace MATCHES ".*_.*")
  63. list(APPEND keywords ROOT)
  64. endif()
  65. ensure_python_init("${PROJECT_BINARY_DIR}/${slash_namespace}" ${keywords})
  66. endfunction(add_python_target)
  67. #
  68. # Function: install_python_package(path [ARCH/LIB] [COMPONENT component])
  69. #
  70. # Installs the Python package which was built at `path`.
  71. #
  72. # Note that this handles more than just installation; it will also invoke
  73. # Python's compileall utility to pregenerate .pyc/.pyo files. This will only
  74. # happen if the Python interpreter is found.
  75. #
  76. # The ARCH or LIB keyword may be used to specify whether this package should be
  77. # installed into Python's architecture-dependent or architecture-independent
  78. # package path. The default, if unspecified, is LIB.
  79. #
  80. # The COMPONENT keyword overrides the install component (see CMake's
  81. # documentation for more information on what this does). The default is
  82. # "Python".
  83. #
  84. function(install_python_package path)
  85. set(type "LIB")
  86. set(component "Python")
  87. set(component_keyword OFF)
  88. foreach(arg ${ARGN})
  89. if(arg STREQUAL "ARCH")
  90. set(type "ARCH")
  91. elseif(arg STREQUAL "LIB")
  92. set(type "LIB")
  93. elseif(arg STREQUAL "COMPONENT")
  94. set(component_keyword ON)
  95. elseif(component_keyword)
  96. set(component "${arg}")
  97. set(component_keyword OFF)
  98. else()
  99. message(FATAL_ERROR "install_python_package got unexpected argument: ${ARGN}")
  100. endif()
  101. endforeach(arg)
  102. get_filename_component(package_name "${path}" NAME)
  103. set(custom_target "bytecompile_${package_name}")
  104. file(RELATIVE_PATH relpath "${PROJECT_BINARY_DIR}" "${path}")
  105. if(PYTHON_EXECUTABLE)
  106. add_custom_target(${custom_target} ALL)
  107. add_custom_command(
  108. TARGET ${custom_target}
  109. WORKING_DIRECTORY "${PROJECT_BINARY_DIR}"
  110. COMMAND "${PYTHON_EXECUTABLE}" -m compileall -q "${relpath}")
  111. add_custom_command(
  112. TARGET ${custom_target}
  113. WORKING_DIRECTORY "${PROJECT_BINARY_DIR}"
  114. COMMAND "${PYTHON_EXECUTABLE}" -OO -m compileall -q "${relpath}")
  115. endif()
  116. ensure_python_init("${path}")
  117. set(dir ${PYTHON_${type}_INSTALL_DIR})
  118. if(dir)
  119. install(DIRECTORY "${path}" DESTINATION "${dir}"
  120. COMPONENT "${component}"
  121. FILES_MATCHING REGEX "\\.py[co]?$")
  122. endif()
  123. endfunction(install_python_package)
  124. #
  125. # Function: ensure_python_init(path [ARCH] [ROOT] [OVERWRITE])
  126. #
  127. # Makes sure that the directory - at `path` - contains a file named
  128. # '__init__.py', which is necessary for Python to recognize the directory as a
  129. # package.
  130. #
  131. # ARCH, if specified, means that this is a binary package, and the build tree
  132. # might contain configuration-specific subdirectories. The __init__.py will be
  133. # generated with a function that ensures that the appropriate configuration
  134. # subdirectory is in the path.
  135. #
  136. # ROOT, if specified, means that the directory may sit directly adjacent to a
  137. # 'bin' directory, which should be added to the DLL search path on Windows.
  138. #
  139. # OVERWRITE causes the __init__.py file to be overwritten if one is already
  140. # present.
  141. #
  142. function(ensure_python_init path)
  143. set(arch OFF)
  144. set(root OFF)
  145. set(overwrite OFF)
  146. foreach(arg ${ARGN})
  147. if(arg STREQUAL "ARCH")
  148. set(arch ON)
  149. elseif(arg STREQUAL "ROOT")
  150. set(root ON)
  151. elseif(arg STREQUAL "OVERWRITE")
  152. set(overwrite ON)
  153. else()
  154. message(FATAL_ERROR "ensure_python_init got unexpected argument: ${arg}")
  155. endif()
  156. endforeach(arg)
  157. set(init_filename "${path}/__init__.py")
  158. if(EXISTS "${init_filename}" AND NOT overwrite)
  159. return()
  160. endif()
  161. file(WRITE "${init_filename}" "")
  162. if(arch AND NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
  163. # ARCH set, and this is a multi-configuration generator
  164. set(configs "${CMAKE_CONFIGURATION_TYPES}")
  165. # Debug should be at the end (highest preference)
  166. list(REMOVE_ITEM configs "Debug")
  167. list(APPEND configs "Debug")
  168. string(REPLACE ";" "', '" configs "${configs}")
  169. file(APPEND "${init_filename}" "
  170. def _fixup_path():
  171. try:
  172. path = __path__[0]
  173. except (NameError, IndexError):
  174. return # Not a package, or not on filesystem
  175. import os
  176. abspath = os.path.abspath(path)
  177. newpath = None
  178. for config in ['${configs}']:
  179. cfgpath = os.path.join(abspath, config)
  180. if not os.path.isdir(cfgpath):
  181. continue
  182. newpath = cfgpath
  183. if config.lower() == os.environ.get('CMAKE_CONFIGURATION', '').lower():
  184. break
  185. if newpath:
  186. __path__.insert(0, newpath)
  187. _fixup_path()
  188. del _fixup_path
  189. ")
  190. endif()
  191. if(root AND WIN32 AND NOT CYGWIN)
  192. # ROOT set, and this is Windows
  193. file(APPEND "${init_filename}" "
  194. def _fixup_dlls():
  195. try:
  196. path = __path__[0]
  197. except (NameError, IndexError):
  198. return # Not a package, or not on filesystem
  199. import os
  200. relpath = os.path.relpath(path, __path__[-1])
  201. dll_path = os.path.abspath(os.path.join(__path__[-1], '../bin', relpath))
  202. if not os.path.isdir(dll_path):
  203. return
  204. os_path = os.environ.get('PATH', '')
  205. os_path = os_path.split(os.pathsep) if os_path else []
  206. os_path.insert(0, dll_path)
  207. os.environ['PATH'] = os.pathsep.join(os_path)
  208. _fixup_dlls()
  209. del _fixup_dlls
  210. ")
  211. endif()
  212. endfunction(ensure_python_init)