Skip to content

Instantly share code, notes, and snippets.

@aaronang
Last active August 24, 2018 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronang/3b375b1ad506254bb3ee1ab0100d86e9 to your computer and use it in GitHub Desktop.
Save aaronang/3b375b1ad506254bb3ee1ab0100d86e9 to your computer and use it in GitHub Desktop.
Calling a Python script from C++ 🐍
cmake_minimum_required(VERSION 3.12)
project(popen)
set(CMAKE_CXX_STANDARD 11)
add_executable(popen main.cpp)
install(FILES hello.py
DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
#!/usr/bin/env python3
import sys
if __name__ == '__main__':
print("Hello World!")
print(sys.argv)
#include <iostream>
#include <array>
std::string call(const std::string& command) {
std::array<char, 128> buffer{};
std::string result;
FILE *pipe = popen(command.c_str(), "r");
if (!pipe) {
std::cerr << "Couldn't start command." << std::endl;
return nullptr;
}
while (fgets(buffer.data(), 128, pipe) != nullptr) {
result += buffer.data();
}
int code = pclose(pipe);
return result;
}
int main() {
std::cout << call("/usr/bin/python hello.py world") << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment