File: class/Workbook/Exercises/Lab11/environ.c

/*
 * A C extension module for Python, called "environ".
 * Wrap the C library's getenv/putenv routines for use in
 * Python programs. Inspired by an idea from Andy Bensky.
 */

#include <Python.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

static PyObject *                                 /* returns object */
wrap_getenv(PyObject *self, PyObject *args)       /* self not used */
{                                                 /* args from python */
    char *varName, *varValue;
    PyObject *returnObj = NULL;                         /* null=exception */

    if (PyArg_Parse(args, "s", &varName))               /* Python -> C */
        if ((varValue = getenv(varName)) != NULL)       /* call C getenv */
            returnObj = Py_BuildValue("s", varValue);   /* C -> Python */
        else 
            PyErr_SetString(PyExc_SystemError, "Error calling getenv");
    else
        PyErr_SetString(PyExc_TypeError, "Usage: getenv(varName)");
    return returnObj; 
}

static PyObject *
wrap_putenv(PyObject *self, PyObject *args)
{
    char *varName, *varValue, *varAssign;
    PyObject *returnObj = NULL;

    if (PyArg_Parse(args, "(ss)", &varName, &varValue)) 
    {
        varAssign = malloc(strlen(varName) + strlen(varValue) + 2);
        sprintf(varAssign, "%s=%s", varName, varValue);
        if (putenv(varAssign) == 0) {
            Py_INCREF(Py_None);                   /* success */
            returnObj = Py_None;                  /* reference None */
        }
        else
            PyErr_SetString(PyExc_SystemError, "Error calling putenv");
    }
    else
        PyErr_SetString(PyExc_TypeError, "Usage: putenv(varName, varValue)");
    return returnObj;
}

static struct PyMethodDef environ_methods[] = {
    {"getenv", wrap_getenv},
    {"putenv", wrap_putenv},        /* name, address */
    {NULL, NULL}
};

void initenviron()                  /* on first import */
{
    (void) Py_InitModule("environ", environ_methods);
}



[Home page] Books Code Blog Python Author Train Find ©M.Lutz