Skip to content

Instantly share code, notes, and snippets.

@codito
Last active March 16, 2024 20:29
Show Gist options
  • Save codito/88c0f1f82056b437e672c73c820e6c6d to your computer and use it in GitHub Desktop.
Save codito/88c0f1f82056b437e672c73c820e6c6d to your computer and use it in GitHub Desktop.
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