Created
August 19, 2020 20:28
-
-
Save gregyjames/64f8d5f8d0a1e9afe1cc186e6a9aa760 to your computer and use it in GitHub Desktop.
Embed Python in C++
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 "Python.h" | |
int main() | |
{ | |
//Initialize the python instance | |
Py_Initialize(); | |
//Run a simple string | |
PyRun_SimpleString("from time import time,ctime\n" | |
"print('Today is',ctime(time()))\n"); | |
//Run a simple file | |
FILE* PScriptFile = fopen("test.py", "r"); | |
if(PScriptFile){ | |
PyRun_SimpleFile(PScriptFile, "test.py"); | |
fclose(PScriptFile); | |
} | |
//Run a python function | |
PyObject *pName, *pModule, *pFunc, *pArgs, *pValue; | |
pName = PyUnicode_FromString((char*)"script"); | |
pModule = PyImport_Import(pName); | |
pFunc = PyObject_GetAttrString(pModule, (char*)"test"); | |
pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"Greg")); | |
pValue = PyObject_CallObject(pFunc, pArgs); | |
auto result = _PyUnicode_AsString(pValue); | |
std::cout << result << std::endl; | |
//Close the python instance | |
Py_Finalize(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment