简体   繁体   English

使用CMake查找python site-packages目录

[英]Finding python site-packages directory with CMake

I use CMake to build my application. 我使用CMake构建我的应用程序。 How can I find where the python site-packages directory is located? 如何找到python site-packages目录所在的位置? I need the path in order to compile an extension to python. 我需要路径才能编译扩展到python。

CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. 当我计划在Linux,Mac和Windows上部署我的应用程序时,CMake必须能够在所有三个主要操作系统上找到路径。

I tried using 我试过用

include(FindPythonLibs)
find_path( PYTHON_SITE_PACKAGES site-packages ${PYTHON_INCLUDE_PATH}/.. )

however that does not work. 但这不起作用。

I can also obtain the path by running 我也可以通过运行获取路径

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

on the shell, but how would I invoke that from CMake ? 在shell上,但我如何从CMake调用它?

SOLUTION: 解:

Thanks, Alex. 谢谢,亚历克斯。 So the command that gives me the site-package dir is: 那么给我网站包目录的命令是:

execute_process ( COMMAND python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" OUTPUT_VARIABLE PYTHON_SITE_PACKAGES OUTPUT_STRIP_TRAILING_WHITESPACE)

The OUTPUT_STRIP_TRAILING_WHITESPACE command is needed to remove the trailing new line. 需要OUTPUT_STRIP_TRAILING_WHITESPACE命令来删除尾随的新行。

您可以使用execute_process在cmake中执行外部进程(如果需要,可以将输出转换为变量,就像在这里一样)。

Slightly updated version that I used for lcm : 我用于lcm的稍微更新的版本:

execute_process(
  COMMAND "${PYTHON_EXECUTABLE}" -c "if True:
    from distutils import sysconfig as sc
    print(sc.get_python_lib(prefix='', plat_specific=True))"
  OUTPUT_VARIABLE PYTHON_SITE
  OUTPUT_STRIP_TRAILING_WHITESPACE)

This sets PYTHON_SITE to the appropriate prefix-relative path, suitable for use like: 这将PYTHON_SITE设置为适当的前缀相对路径,适合使用,如:

install(
  FILES ${mypackage_python_files}
  DESTINATION ${PYTHON_SITE}/mypackage)

(Please don't install to an absolute path! Doing so bypasses CMAKE_INSTALL_PREFIX .) (请不要安装到绝对路径!这样做会绕过CMAKE_INSTALL_PREFIX 。)

Since CMake 3.12 you can use FindPython module which populates Python_SITELIB and Python_SITEARCH variables for architecture independent and specific libraries, respectively. 从CMake 3.12开始,您可以使用FindPython模块,该模块分别为体系结构独立和特定库填充Python_SITELIBPython_SITEARCH变量。

Example: 例:

find_package(Python ${PYTHON_VERSION} REQUIRED COMPONENTS Development)
Python_add_library(foo MODULE
    src/foo.cc src/python_interface.cc
)
install(TARGETS foo DESTINATION ${Python_SITEARCH}/foo)

I suggest to use get_python_lib(True) if you are making this extension as a dynamic library. 如果您将此扩展名作为动态库,我建议使用get_python_lib(True) This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be /usr/lib64 instead of /usr/lib ) 如果你需要特定于平台的位置,那么第一个参数应该是真的(在64位linux机器中,这可能是/usr/lib64而不是/usr/lib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM