[Tutor] Python and C

Michael P. Reilly arcege@shore.net
Wed, 12 Apr 2000 19:05:55 -0400 (EDT)


> I'm a novice at Python. CAn anyone tell me how to do
> the following:
> 
> 1) Calling a C function within Python

You need to wrap the arguments and return value in the Python/C API,
you can do this with SWIG (http://www.swig.org/) or with the C API
itself (http://www.python.org/doc/current/ext/ext.html).

For example you have a header file with,
  char *get_user_fullname(char *username);

Then you might have the Python/C function:
  PyObject *get_py_user_fullname(PyObject *unused, PyObject *args)
    { char *username, *result;

      if (!PyArg_ParseTuple(args, "s", &username))
        return NULL; /* indicate exception (already set by ParseTuple) */
      result = get_user_fullname(username);
      if (result == NULL) {
        PyErr_SetString(PyExc_ValueError, "invalid username");
        return NULL;
      }
      return Py_BuildValue("s", result);
    }

The PyArg_ParseTuple() function works like scanf(), but on a Python
tuple and Py_BuildValue() is the reverse.  I also raise an exception
explicitly, and pass an exception through (from PyArg_ParseTuple).

> 2) Use arguments to access a directory ( I need to do
> a search within the directory)

You will want to look at the "os" standard module, which has a function
to retrieve the filenames in a directory.  There is also the "glob"
standard module.
  os -    http://www.python.org/doc/current/lib/module-os.html
  os.path http://www.python.org/doc/current/lib/module-os.path.html
  glob -  http://www.python.org/doc/current/lib/module-glob.html

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Engineer | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------