Last active
December 6, 2019 14:42
-
-
Save noskill/e5fbeb09b658102cfdedf1693e894103 to your computer and use it in GitHub Desktop.
embed python with console
This file contains hidden or 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 <Python.h> | |
| #include <iostream> | |
| // adapted from https://github.com/guowei8412/upp-mirror/blob/0325a2fab45b0b65b8bda7d293d4e03412145826/bazaar/PyTest/main.cpp | |
| void SimpleCall() | |
| { | |
| std::cout << "Invoking a python statement:" << std::endl; | |
| PyRun_SimpleString( "from time import time,ctime\n" | |
| "print('Today is',ctime(time()))\n"); | |
| } | |
| void StartConsole() | |
| { | |
| PyRun_SimpleString( "import code\n" | |
| "code.interact()\n"); | |
| } | |
| int main(int argc, char ** argv) | |
| { | |
| std::cout << "Starting Python..." << std::endl; | |
| Py_Initialize(); | |
| SimpleCall(); | |
| StartConsole(); | |
| PyCompilerFlags cf; | |
| cf.cf_flags = 0; | |
| PyObject *m, *d; | |
| m = PyImport_AddModule("__main__"); | |
| d = PyModule_GetDict(m); | |
| //this runs an interactive console loop on stdin | |
| int ret = PyRun_InteractiveLoopFlags(stdin, "<stdin>", &cf); | |
| std::cout << "DONE." << std::endl; | |
| } | |
| // compile with | |
| // g++ -I /usr/include/python3.7 main.cpp -L/usr/lib/x86_64-linux-gnu/ -lpython3.7m -g | |
| ~ | |
| ~ | |
| ~ | |
| ~ | |
| ~ | |
| ~ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment