|
| 1 | +#ifndef _MATPLOTLIB_H |
| 2 | +#define _MATPLOTLIB_H |
| 3 | + |
| 4 | +#include <iostream> |
| 5 | +#include <sstream> |
| 6 | +#include <string> |
| 7 | + |
| 8 | +#ifdef _WIN32 |
| 9 | +#define __XXX_YYY_ZZZ_POPEN___ _popen |
| 10 | +#define __XXX_YYY_ZZZ_PCLOSE___ _pclose |
| 11 | +#else |
| 12 | +#include <memory> |
| 13 | +#define __XXX_YYY_ZZZ_POPEN___ popen |
| 14 | +#define __XXX_YYY_ZZZ_PCLOSE___ pclose |
| 15 | +#endif |
| 16 | + |
| 17 | +#define PY_MAJOR_VERSION 3 |
| 18 | +#include "matplotlibcpp.h" |
| 19 | + |
| 20 | +std::string |
| 21 | +__XXX_YYY_ZZZ_STRIP__(const std::string &str, |
| 22 | + const std::string &whitespace = " \n\r\t\f\v") { |
| 23 | + size_t from = str.find_first_not_of(whitespace); |
| 24 | + |
| 25 | + if (from == std::string::npos) { |
| 26 | + return ""; |
| 27 | + } |
| 28 | + size_t to = str.find_last_not_of(whitespace); |
| 29 | + assert(to != std::string::npos); |
| 30 | + |
| 31 | + return str.substr(from, (to - from) + 1); |
| 32 | +} |
| 33 | + |
| 34 | +std::string __XXX_YYY_ZZZ_COMMAND__(const std::string &cmd) { |
| 35 | + using pipe_ptr = std::unique_ptr<FILE, decltype(__XXX_YYY_ZZZ_PCLOSE___) *>; |
| 36 | + pipe_ptr pipe(__XXX_YYY_ZZZ_POPEN___(cmd.c_str(), "r"), |
| 37 | + __XXX_YYY_ZZZ_PCLOSE___); |
| 38 | + if (pipe == nullptr) { |
| 39 | + std::cout << "error: failed to execute: " << cmd << std::endl; |
| 40 | + return ""; |
| 41 | + } |
| 42 | + |
| 43 | + const int BUF_SIZE = 1023; |
| 44 | + char buf[BUF_SIZE + 1]; |
| 45 | + buf[BUF_SIZE] = '\0'; |
| 46 | + |
| 47 | + std::stringstream ss; |
| 48 | + while (fgets(buf, BUF_SIZE, pipe.get()) != NULL) { |
| 49 | + ss << buf; |
| 50 | + } |
| 51 | + |
| 52 | + if (__XXX_YYY_ZZZ_PCLOSE___(pipe.release()) != 0) { |
| 53 | + return ""; |
| 54 | + } |
| 55 | + |
| 56 | + return __XXX_YYY_ZZZ_STRIP__(ss.str()); |
| 57 | +} |
| 58 | + |
| 59 | +static bool __XXX_YYY_ZZZ_INIT__() { |
| 60 | + const std::string PYTHON_VERSION = __XXX_YYY_ZZZ_COMMAND__( |
| 61 | + "python3 --version | cut -d ' ' -f2 | cut -d '.' -f-2"); |
| 62 | + const std::string PYTHONHOME = |
| 63 | + std::string(getenv("CONDA_PREFIX")) + "/lib/python" + PYTHON_VERSION; |
| 64 | + const std::string PYTHONPATH = PYTHONHOME + ":" + PYTHONHOME + |
| 65 | + "/site-packages:" + PYTHONHOME + |
| 66 | + "/lib-dynload"; |
| 67 | + setenv("PYTHONHOME", PYTHONHOME.c_str(), 1); |
| 68 | + setenv("PYTHONPATH", PYTHONPATH.c_str(), 1); |
| 69 | + |
| 70 | + std::cout << "PYTHON_VERSION: " << PYTHON_VERSION << std::endl; |
| 71 | + std::cout << "PYTHONHOME : " << getenv("PYTHONHOME") << std::endl; |
| 72 | + std::cout << "PYTHONPATH : " << getenv("PYTHONPATH") << std::endl; |
| 73 | + |
| 74 | + return true; |
| 75 | +} |
| 76 | + |
| 77 | +static bool __UNUSED_XXX_YYY_ZZZ_INIT__ = __XXX_YYY_ZZZ_INIT__(); |
| 78 | + |
| 79 | +#endif |
0 commit comments