Executing a specific function.

Martin v. Loewis martin at v.loewis.de
Fri Mar 29 13:13:53 EST 2002


Michael Saunders <michael at amtec.com> writes:

> I had seen this API but it requires a "callable". Isn't a callable a
> PyObject pointer to a callable function?

Correct. It could be anything callable, though: a class, a type, an
instance with an __call__ method, any other object with a tp_call
slot.

> How do I build the "callable". All I have is a Python file,
> "myfile.py" and the name of a function to call "myPthonFunction".

Always think of how to write things in Python, then translate to
C. Everything you can do in Python can be (more or less) literally
translated.

In the specific case, I'd guess you'll do

import myfile
result = myfile.myPythonFunction()

Translating this to C, you'll do:

module = PyImport_Import("myfile");
result = PyObject_CallMethod(module, "myPythonFunction", "");

Don't forget to check for exceptions! If you would not have
PyObject_CallMethod, you would do

function = PyObject_GetAttrString(module, "myPythonFunction");
result = PyObject_CallFunction(function, "");

In C, you can do things that you can't, directly, do from Python.
E.g. if you can't guarantee that myfile is on sys.path, there is no
need to add it to sys.path - just use one of the functions that create
modules from source code.

HTH,
Martin




More information about the Python-list mailing list