3

I think an example would be the best way to demonstrate my problem:

Lets say I have a source directory named src. This directory has two files, a CMakeLists.txt file and a python file named blah. In the same place where src is stored, there is a folder named build. Now, I would like to be able to run cmake and make it compile my python file blah and place it into my build directory. Currently, my CMakeLists.txt is just copying the uncompiled code straight into my build directory using the call:

CONFIGURE_FILE(${PATH_TO_SOURCE}/blah.py ${PATH_TO_BUILD}/blah.py COPYONLY)

Then I run make in the terminal to compile the actual file. This leaves the uncompiled python file in my build directory, which is no good. I've tried using ADD_EXECUTABLES, creating a custom target and using COMMAND, but my syntax must be off somewhere. Any help would be greatly appreciated!

1 Answer 1

4

CMake doesn't support Python out of the box, AFAIK. Because of this, you will need to write rule to build python files, something like that:

macro(add_python_target tgt)
  foreach(file ${ARGN})
    set(OUT ${CMAKE_CURRENT_BINARY_DIR}/${file}.pyo)
    list(APPEND OUT_FILES ${OUT})
    add_custom_command(OUTPUT ${OUT}
        COMMAND <python command you use to byte-compile .py file>)
  endforeach()

  add_custom_target(${tgt} ALL DEPENDS ${OUT_FILES})
endmacro()

After defining it, you can use it this way:

add_python_target(blabla blah.py)

If you want to make adjustmenets or need more information, see CMake documentation.

Sign up to request clarification or add additional context in comments.

3 Comments

I actually almost got this working another way.. ADD_CUSTOM_TARGET(output ALL /usr/bin/python -m /src/py_compile blah.py COMMAND /bin/mv /src/blah.py /build The only thing is I rather just have this all in one command. Is there any optiion I can specify to py_compile to have it place the compiled file inside of the build directory. I'm just not sure whether or not my src directory will have write priveledges.
You can set WORKING_DIRECTORY argument in add_custom_target call to ${CMAKE_CURRENT_BINARY_DIR} and python will output it's file there. Other way - replace /src/py_compile with ${CMAKE_CURRENT_BINARY_DIR/py_compile`.
I came across this: Welcome to CMake Python Distributions’s documentation!. Would this help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.