Skip to content

Commit c867271

Browse files
author
Tage Johansson
committed
Initial simple Python module.
1 parent 0387c12 commit c867271

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Modules/bocmodule.c

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#define PY_SSIZE_T_CLEAN // Not necessary since Python 3.13
2+
#include <Python.h>
3+
4+
// SpamError exception
5+
static PyObject *SpamError = NULL;
6+
7+
static int
8+
spam_module_exec(PyObject *m)
9+
{
10+
if (SpamError != NULL) {
11+
PyErr_SetString(PyExc_ImportError,
12+
"cannot initialise spam module more than once");
13+
return -1;
14+
}
15+
SpamError = PyErr_NewException("spam.error", NULL, NULL);
16+
if (PyModule_AddObjectRef(m, "SpamError", SpamError)) {
17+
return -1;
18+
}
19+
20+
return 0;
21+
}
22+
23+
static PyObject *
24+
spam_system(PyObject *self, PyObject *args)
25+
{
26+
const char *command;
27+
28+
if (!PyArg_ParseTuple(args, "s", &command)) {
29+
return NULL;
30+
}
31+
32+
int sts = system(command);
33+
if (sts < 0) {
34+
PyErr_SetString(SpamError, "System command failed");
35+
return NULL;
36+
}
37+
38+
return PyLong_FromLong(sts);
39+
}
40+
41+
static PyMethodDef spam_methods[] = {
42+
{ "system", spam_system, METH_VARARGS, "Execute a shell command." },
43+
{ NULL, NULL, 0, NULL } // Sentinel
44+
};
45+
46+
static PyModuleDef_Slot spam_module_slots[] = {
47+
{ Py_mod_exec, spam_module_exec },
48+
{ 0, NULL }
49+
};
50+
51+
static struct PyModuleDef spam_module = {
52+
.m_base = PyModuleDef_HEAD_INIT,
53+
.m_name = "spam",
54+
.m_size = 0, // non-negative
55+
.m_methods = spam_methods,
56+
.m_slots = spam_module_slots,
57+
};
58+
59+
PyMODINIT_FUNC
60+
PyInit_spam(void)
61+
{
62+
return PyModuleDef_Init(&spam_module);
63+
}

0 commit comments

Comments
 (0)