Skip to content

Commit 55349d3

Browse files
committed
[09/27/2022] 增加自动设置环境变量的代码
增加自动设置环境变量的代码
1 parent 1d7838d commit 55349d3

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

README.md

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,54 @@ Usage
3232

3333
Complete minimal example:
3434
```cpp
35+
#include <string>
36+
#include <vector>
37+
#include <memory>
38+
#include <sstream>
39+
40+
#define PY_MAJOR_VERSION 3
3541
#include "matplotlibcpp.h"
3642
#define plt matplotlibcpp
3743

44+
std::string to_strip(const std::string &str,
45+
const std::string &whitespace = " \n\r\t\f\v") {
46+
size_t from = str.find_first_not_of(whitespace);
47+
48+
if (from == std::string::npos) {
49+
return "";
50+
}
51+
size_t to = str.find_last_not_of(whitespace);
52+
assert(to != std::string::npos);
53+
54+
return str.substr(from, (to - from) + 1);
55+
}
56+
57+
std::string COMMAND(const std::string &cmd) {
58+
using pipe_ptr = std::unique_ptr<FILE, decltype(pclose) *>;
59+
pipe_ptr pipe(popen(cmd.c_str(), "r"), pclose);
60+
if (pipe == nullptr) {
61+
std::cout << "error: failed to execute: " << cmd << std::endl;
62+
return "";
63+
}
64+
65+
const int BUF_SIZE = 1023;
66+
char buf[BUF_SIZE + 1];
67+
buf[BUF_SIZE] = '\0';
68+
std::stringstream out;
69+
while (fgets(buf, BUF_SIZE, pipe.get()) != NULL) {
70+
out << buf;
71+
}
72+
pclose(pipe.release());
73+
74+
return out.str();
75+
}
76+
3877
int main() {
3978
// 增加环境变量设置可以免除在运行的时候手动的增加
79+
const std::string PYTHON_VERSION =
80+
to_strip(COMMAND("python3 --version | cut -d ' ' -f2 | cut -d '.' -f-2"));
4081
const std::string PYTHONHOME =
41-
std::string(getenv("CONDA_PREFIX")) + "/lib/python3.7m";
82+
std::string(getenv("CONDA_PREFIX")) + "/lib/python" + PYTHON_VERSION;
4283
const std::string PYTHONPATH = PYTHONHOME + ":" + PYTHONHOME +
4384
"/site-packages:" + PYTHONHOME +
4485
"/lib-dynload";
@@ -64,7 +105,7 @@ g++ minimal.cpp -std=c++11 -I/usr/include/python3.7 -lpython3.7 -o minimal
64105
```bash
65106
g++ minimal.cpp \
66107
-std=c++11 \
67-
-I${CONDA_PREFIX}/include/python3.7m \
108+
-I${CONDA_PREFIX}/include/python3.7 \
68109
-I${CONDA_PREFIX}/lib/python3.7/site-packages/numpy/core/include \
69110
-L${CONDA_PREFIX}/lib
70111
-lpython3.7m \

0 commit comments

Comments
 (0)