Skip to content

Instantly share code, notes, and snippets.

@myersguo
Created March 29, 2018 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myersguo/ea12aa987c888431ad097bb18ff06b64 to your computer and use it in GitHub Desktop.
Save myersguo/ea12aa987c888431ad097bb18ff06b64 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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