Last active
August 24, 2018 21:58
-
-
Save aaronang/3b375b1ad506254bb3ee1ab0100d86e9 to your computer and use it in GitHub Desktop.
Calling a Python script from C++ π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
if __name__ == '__main__': | |
print("Hello World!") | |
print(sys.argv) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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