Python.cmake 7.3 KB

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