printf in python

Ivan Illarionov ivan.illarionov at gmail.com
Wed Jun 4 16:10:51 CEST 2008


On Mon, 02 Jun 2008 00:32:33 -0700, gianluca wrote:

> Hy, I've a problem with may python library generated with swig from C
> code. I works and I can access all function but a  simèple function that
> print a string don't work's.
> The function is like this:
> int PrintTEST()
> {
>      printf("TEST ");
>      return 1;
> }
> 
> If I call the function (myDLL.PrintTEST() ) the function print only the
> returned value, not the string "TEST". Could anybody help me?
> 
> Thanks
> 
> Gianluca

Hi!

Here's "Hello world" in Python C API:

1. create 'hello.c' file with the following content:
#include <Python.h>

PyObject* 
hello(PyObject* self)
{
    printf("Hello world!\n");
    Py_RETURN_NONE;
}

static PyMethodDef functions[] = {
    {"hello",    (PyCFunction)hello, METH_NOARGS},
    {NULL, NULL, 0, NULL},
};

DL_EXPORT(void)
init_hello(void)
{
    Py_InitModule("_hello", functions);
}

2. create 'buildme.py' file with this content:
import os
import sys
from distutils.core import Extension, setup

os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.argv = [sys.argv[0], 'build_ext', '-i']
setup(ext_modules = [Extension('_hello', ["hello.c"])])

3. run "python buildme.py"

That's all.
>>> from _hello import hello
>>> hello()
Hello world!


-- Ivan



More information about the Python-list mailing list