Skip to content

Instantly share code, notes, and snippets.

@mjkillough
Last active March 17, 2024 09:09
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mjkillough/630ef274387429680577963f630b2691 to your computer and use it in GitHub Desktop.
Save mjkillough/630ef274387429680577963f630b2691 to your computer and use it in GitHub Desktop.
Generating and using a virtualenv from CMake
cmake_minimum_required(VERSION 3.6)
project(CmakeVirtualenv)
enable_testing()
# Find Python and Virtualenv. We don't actually use the output of the
# find_package, but it'll give nicer errors.
find_package(PythonInterp 2.7 REQUIRED)
find_program(VIRTUALENV virtualenv)
if(NOT VIRTUALENV)
message(FATAL_ERROR "Could not find `virtualenv` in PATH")
endif()
set(VIRTUALENV ${VIRTUALENV} -p python2.7)
# Generate the virtualenv and ensure it's up to date.
add_custom_command(
OUTPUT venv
COMMAND ${VIRTUALENV} venv
)
add_custom_command(
OUTPUT venv.stamp
DEPENDS venv requirements.txt
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/requirements.txt requirements.txt
COMMAND ./venv/bin/pip install -r requirements.txt --upgrade
)
# Build command line to run py.test.
set(PYTEST
${CMAKE_CURRENT_BINARY_DIR}/venv/bin/python2
${CMAKE_CURRENT_BINARY_DIR}/venv/bin/py.test
)
add_custom_target(Tests ALL
DEPENDS venv.stamp
SOURCES requirements.txt
)
add_test(NAME run_tests
COMMAND ${PYTEST} ${CMAKE_CURRENT_SOURCE_DIR}/test_sample.py
)
@Renari
Copy link

Renari commented Apr 23, 2021

Tried doing this with python3 venv and wasn't able to get it to work sadly. Running commands like this ./venv/bin/pip install -r requirements.txt --upgrade were trying to install globally.

# setup venv if it doesn't exist
IF (NOT EXISTS "${CMAKE_BINARY_DIR}/venv")
    FIND_PACKAGE(Python3)
    EXECUTE_PROCESS(COMMAND ${Python3_EXECUTABLE} "-m" "venv" "venv"
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR})
    UNSET(${Python3_EXECUTABLE})
ENDIF ()
# activate python venv
SET(ENV{VIRTUAL_ENV} "${CMAKE_BINARY_DIR}/venv")
FIND_PACKAGE(Python3)

@orgonth
Copy link

orgonth commented Sep 9, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment