test_numpy.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <pybind11/embed.h>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <string>
  5. #include <iostream>
  6. namespace py = pybind11;
  7. int main() {
  8. try {
  9. // Initialize the Python interpreter
  10. py::scoped_interpreter guard{};
  11. // Path to the script
  12. const std::string script_path = "./test_numpy.py";
  13. // Open the script file
  14. std::ifstream file(script_path);
  15. if (!file.is_open()) {
  16. std::cerr << "Could not open " << script_path << " script file." << std::endl;
  17. return 1;
  18. }
  19. // Read and execute the script into a string
  20. std::stringstream buffer;
  21. buffer << file.rdbuf();
  22. std::string script = buffer.str();
  23. py::exec(script);
  24. std::cout << "Numpy script executed successfully." << std::endl;
  25. }
  26. catch (const py::error_already_set& e) {
  27. // Catch and print Python exceptions
  28. std::cerr << "Python error: " << e.summary() << std::endl;
  29. return 1;
  30. }
  31. catch (const std::exception& e) {
  32. // Catch and print other C++ exceptions
  33. std::cerr << "C++ exception: " << e.what() << std::endl;
  34. return 1;
  35. }
  36. return 0;
  37. }