阶段备份
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
#include <Python.h>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
|
||||
class pythonCpp
|
||||
{
|
||||
public:
|
||||
//二选一
|
||||
//使用程序自带的虚拟环境
|
||||
void activateVirtualEnv(const std::string& pyPath, const std::string& venvName);
|
||||
//使用安装好的python解释器
|
||||
void activatePythonEnv(wchar_t* envPath)
|
||||
{
|
||||
Py_SetPythonHome(envPath);
|
||||
}
|
||||
//END
|
||||
pythonCpp()
|
||||
{
|
||||
//activatePythonEnv(L"./Python312");
|
||||
activateVirtualEnv("./Python312","env");
|
||||
Py_Initialize();
|
||||
//PyRun_SimpleString("import os; print('PYTHONHOME:', os.getenv('PYTHONHOME'))");
|
||||
//PyRun_SimpleString("import sys; print('sys.path:', sys.path)");
|
||||
}
|
||||
~pythonCpp()
|
||||
{
|
||||
Py_Finalize();
|
||||
}
|
||||
//ONLY RELEASE
|
||||
bool runPythonScript_R(const std::string& scriptPath);
|
||||
//RECOMMAND
|
||||
bool runPythonScript(const std::string& scriptPath);
|
||||
bool runPythonScript(const std::string& scriptPath, const std::vector<std::string>& args)
|
||||
{
|
||||
PyObject* pArgs = PyList_New(args.size() + 1); // 加1是因为第一个参数是脚本路径
|
||||
PyList_SetItem(pArgs, 0, Py_BuildValue("s", scriptPath.c_str())); // 设置脚本路径
|
||||
|
||||
for (size_t i = 0; i < args.size(); ++i) {
|
||||
PyList_SetItem(pArgs, i + 1, Py_BuildValue("s", args[i].c_str()));
|
||||
}
|
||||
|
||||
PyObject* sys = PyImport_ImportModule("sys");
|
||||
PyObject* sys_argv = PyObject_GetAttrString(sys, "argv");
|
||||
Py_DECREF(sys_argv);
|
||||
PyObject_SetAttrString(sys, "argv", pArgs);
|
||||
Py_DECREF(pArgs);
|
||||
Py_DECREF(sys);
|
||||
|
||||
PyObject* obj = Py_BuildValue("s", scriptPath.c_str());
|
||||
FILE* file = _Py_fopen_obj(obj, "r+");
|
||||
if (file == NULL) {
|
||||
Py_DECREF(obj);
|
||||
return false;
|
||||
}
|
||||
PyRun_SimpleFile(file, scriptPath.c_str());
|
||||
Py_DECREF(obj);
|
||||
}
|
||||
};
|
||||
#pragma once
|
||||
Reference in New Issue
Block a user