Search code examples
pythoncmakeprotocol-buffersgrpc

How can I create protobuffer from .proto file in python files using cmake?


I am using python language for my server in gRPC now I need to create the prpto files from cmake as my client in gRPC is written in c++ I have to run this command in CMAkeLISTS.txt file but when I try to run It , no file is created:

python3 -m grpc_tools.protoc -I ../protos --python_out=. -- 
pyi_out=. --grpc_python_out=. ../helloworld.proto

I want to add this command to CMakeLists.txt :

cmake_minimum_required(VERSION 3.15)

# Project
project(myproj)

# Protobuf
set(protobuf_MODULE_COMPATIBLE TRUE)
find_package(Protobuf CONFIG REQUIRED)
message(STATUS "Using protobuf ${protobuf_VERSION}")

# Protobuf-compiler
set(_PROTOBUF_PROTOC $<TARGET_FILE:protobuf::protoc>)

 # gRPC
 find_package(gRPC CONFIG REQUIRED)
 message(STATUS "Using gRPC ${gRPC_VERSION}")
 set(_GRPC_GRPCPP gRPC::grpc++)
 set(_GRPC_CPP_PLUGIN_EXECUTABLE $<TARGET_FILE:gRPC::grpc_cpp_plugin>)
 set(_GRPC_PY_TOOL $<TARGET_FILE:gRPC::grpc_tools::protoc>)

 # Proto file
get_filename_component(hw_proto "helloworld.proto" ABSOLUTE)
get_filename_component(hw_proto_path "${hw_proto}" PATH)

# Generated sources

set(hw_grpc_src_py "${CMAKE_CURRENT_BINARY_DIR}/helloworld_pb2_grpc.py")
set(hw_proto_src_py "${CMAKE_CURRENT_BINARY_DIR}/helloworld_pb2.py")
set(hw_proto_src_pyi "${CMAKE_CURRENT_BINARY_DIR}/helloworld_pb2.pyi")


find_package(PythonInterp REQUIRED)
find_package(Python3 REQUIRED)
add_custom_command(
  OUTPUT "${hw_grpc_src_py}" "${hw_proto_src_py}" "${hw_proto_src_pyi}"
  COMMAND python3 
  ARGS -m  "${_GRPC_PY_TOOL}"
   -I "${hw_proto_path}"
  --python_out "${CMAKE_CURRENT_BINARY_DIR}"
  --pyi_out "${CMAKE_CURRENT_BINARY_DIR}"
  --grpc_python_out "${CMAKE_CURRENT_BINARY_DIR}"
  "${hw_proto}"
  DEPENDS "${hw_proto}")

but it does not create the files, did I miss something? adding

add_custom_target(run ALL
DEPENDS "${hw_proto}")

also did not work. I also changed add_custome command to add_custom_command( OUTPUT "${hw_grpc_src_py}" "${hw_proto_src_py}" "${hw_proto_src_pyi}" COMMAND python3 ARGS -m "${_GRPC_PY_TOOL}" -I "${hw_proto_path}" --python_out "${CMAKE_CURRENT_BINARY_DIR}" --pyi_out "${CMAKE_CURRENT_BINARY_DIR}" --grpc_python_out "${CMAKE_CURRENT_BINARY_DIR}" "${hw_proto}" DEPENDS "${hw_grpc_src_py}") but also no files were generated.


Solution

  • Removing

    set(_GRPC_PY_TOOL $<TARGET_FILE:gRPC::grpc_tools::protoc>)
    

    and

    "${_GRPC_PY_TOOL}" 
    

    from add_custom_command and write it like :

    add_custom_command(
    OUTPUT "${hw_grpc_src_py}" "${hw_proto_src_py}" "${hw_proto_src_pyi}"
    COMMAND python3 
     ARGS -m  grpc_tools.protoc
    -I "${hw_proto_path}"
    --python_out "${CMAKE_CURRENT_BINARY_DIR}"
    --pyi_out "${CMAKE_CURRENT_BINARY_DIR}"
    --grpc_python_out "${CMAKE_CURRENT_BINARY_DIR}"
     "${hw_proto}"
     DEPENDS "${hw_proto}")
    

    solved the problem and the files are created.