Create a gist now

Instantly share code, notes, and snippets.

@codito /pyembed.c
Last active Nov 19, 2017

What would you like to do?
A simple embedded python interpreter
// Demo a simple embedded python interpreter
// See this post for context: http://codito.in/notes-on-vim-python-interop
//
// Compile with: gcc $(python-config --cflags --ldflags) pyembed.c -o pyembed
// Tested on python 3.6 in arch linux
//
// See https://docs.python.org/3/c-api/init.html for details of APIs.
//
#include <Python.h>
void run_command();
int main()
{
Py_SetPythonHome(L"/usr");
Py_Initialize();
if (!Py_IsInitialized()) {
printf("Failed to initialize python interpreter.");
}
run_command("import sys; print(sys.version)\n");
run_command("import sys; print(sys.prefix); print(sys.base_prefix)\n");
run_command("import sys; print(sys.path)\n");
run_command("from distutils.sysconfig import get_python_lib; print(get_python_lib())\n");
return 0;
}
void run_command(const char* cmd)
{
// print header
printf("\n");
printf("\x1B[32m-- %s", cmd);
// print command output
printf("\x1B[0m```\n");
PyRun_SimpleString(cmd);
printf("\x1B[0m```\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment