Created
July 24, 2020 22:29
-
-
Save dalmago/a9cca0071b9456658ab715daa89cb2af to your computer and use it in GitHub Desktop.
Uses the Python C-API to load a file called "my_sample_py_file.py" and runs its "my_sample_function" function
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 <filesystem> | |
#include <Windows.h> | |
#include <Python.h> | |
int main(int argc, char** argv) { | |
Py_SetPythonHome(L"C:\\python36"); | |
Py_SetProgramName(L"my_test_program"); | |
Py_Initialize(); | |
if (!Py_IsInitialized()) { | |
std::cout << "Error initializing Python" << std::endl; | |
return -1; | |
} | |
wchar_t* py_argv[1] = { L"my_test_program" }; | |
PySys_SetArgv(1, py_argv); | |
int ret = PyRun_SimpleString( | |
"import os, sys \n" | |
"sys.path.append(os.getcwd()) \n" | |
); | |
PyObject* py_module = PyImport_ImportModule("my_sample_py_file"); | |
if (!py_module) { | |
std::cout << "Could not find \"my_sample_file.py\"" << std::endl; | |
Py_Finalize(); | |
return -1; | |
} | |
PyObject* py_func = PyObject_GetAttrString(py_module, "my_sample_function"); | |
if (!py_func) { | |
std::cout << "Could not find \"my_sample_function\"" << std::endl; | |
Py_Finalize(); | |
return -1; | |
} | |
PyObject* py_return = PyObject_CallObject(py_func, NULL); | |
// do some more processing in here; could go back to Python code during this time | |
std::cout << "Sleeping for 10 seconds" << std::endl; | |
Sleep(10E3); | |
Py_Finalize(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Related to this Python file