Cython print()在C printf()之前输出,即使之后放置也是如此

时间:2017-02-21 23:36:40

标签: python c cython

我正在尝试接收Cython。

import counter

cdef public void increment():
    counter.increment()

cdef public int get():
    return counter.get()

cdef public void say(int times):
    counter.say(times)

这是我用来从counter.py调用函数的“粘合代码”,这是一个纯Python源代码文件。它的布局如下:

count = 0

def increment():
    global count

    count += 1

def get():
    global count

    return count

def say(times):
    global count

    print(str(count) * times)

我已成功编译并运行此程序。功能很好。然而,当我测试这个程序时,发生了一件非常奇怪的事情:

int main(int argc, char *argv[]) {
    Py_Initialize();

    // The following two lines add the current working directory
    // to the environment variable `PYTHONPATH`. This allows us
    // to import Python modules in this directory.
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");

    PyInit_glue();

    // Tests
    for (int i = 0; i < 10; i++)
    {
        increment();
    }

    int x = get();
    printf("Incremented %d times\n", x);

    printf("The binary representation of the number 42 is");
    say(3);

    Py_Finalize();
    return 0;
}

我希望程序能够产生这个输出:

Incremented 10 times
The binary representation of the number 42 is
101010

然而,它打印出来:

Incremented 10 times
101010
The binary representation of the number 42 is

但如果我改变了行

printf("The binary representation of the number 42 is");

printf("The binary representation of the number 42 is\n");

然后输出被纠正。

这对我来说很奇怪。我理解如果我想打印Python函数的输出,我也可以将它返回到C并将其存储在变量中,并使用C的printf()而不是本机Python print()。但我很想知道这种情况发生的原因。毕竟,在say()语句之前到达了printf()语句(我在gdb中对此进行了双重检查以确保)。谢谢你的阅读。

0 个答案:

没有答案