Instantly share code, notes, and snippets.

Embed
What would you like to do?
python c module example
#include <Python.h>
static PyObject *SpamError;
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
if (sts < 0) {
PyErr_SetString(SpamError, "System command failed");
return NULL;
}
return PyLong_FromLong(sts);
}
static PyMethodDef SpamMethods[] = {
{"system", spam_system, METH_VARARGS,
"Execute a shell command."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initspam(void)
{
PyObject *m;
m = Py_InitModule("spam", SpamMethods);
if (m == NULL)
return;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
}
@myersguo

This comment has been minimized.

Owner

myersguo commented Mar 29, 2018

gcc spammify.c -fPIC -I/usr/include/python2.7 -shared -o spam.so

import spam
status = spam.system("ls -l")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment