wolverine99
wolverine99

Reputation: 67

CMake to run script

I am trying to create a CMake build that will run several python scripts before building software, if at all. As a starting point, I wanted to create a CMake project that would only run a single python script. I am having trouble getting the script to execute. Here is what I have in my project.

test.py

open('script_output.txt', 'a').close()

CMakeLists.txt

cmake_minimum_required (VERSION 2.6)
project (module)

add_custom_command(OUTPUT script_output.c
           COMMAND python test.py)

add_custom_target(release ALL DEPENDS script_output.c)

It seems to try and run Visual Studio compiler, which I don't want and does not run python script script_output.py, which I do want. What am I doing wrong here?

Upvotes: 2

Views: 7791

Answers (1)

Kevin
Kevin

Reputation: 18243

While add_custom_command will run during your code compilation (after CMake completes), execute_process will run during the CMake configuration stage.

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

# Skip compiler check by enabling no languages.
project(TestProj NONE)

# Tell CMake to run python from the directory where this CMakeLists file exists.
execute_process(COMMAND python test.py
    WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR})

# If you have more than one script to run, use a 
# separate execute_process command, to ensure sequential execution.
execute_process(COMMAND python test2.py
    WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR})

Additionally, you can specify RESULT_VARIABLE or OUTPUT_VARIABLE with the execute_process command to set CMake variables based on the return codes or standard output from the executed process; this could be helpful for influencing subsequent CMake behavior.

Also, if you really want to disable CMake's initial compiler check, you can disable the languages by specifying NONE in the project command.

Upvotes: 3

Related Questions