Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Cython print()在C printf()之前输出,即使是在C printf()之后_Python_C_Cython - Fatal编程技术网

Python Cython print()在C printf()之前输出,即使是在C printf()之后

Python Cython print()在C printf()之前输出,即使是在C printf()之后,python,c,cython,Python,C,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调用函数的“粘合代码”,counter.py是一个纯Python源代码文件。它的布局如下: coun

我要去接赛顿

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调用函数的“粘合代码”,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
101010
The binary representation of the number 42 is
但是如果我改变路线

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

然后对输出进行校正


这对我来说似乎很奇怪。我知道,如果我想打印Python函数的输出,我最好将其返回给C并存储在变量中,然后使用C的printf()而不是本机Python print()。但我很想知道发生这种情况的原因。毕竟,printf()语句是在say()语句之前到达的(我在gdb中仔细检查了这一点以确保)。感谢阅读。

我的第一个想法是,您可能需要一个类似于
fflush(stdout)的语句在那里。但这也可能只是一个问题,在什么“算”为最后一句话上没有新意。请看这里的讨论,显然C在最后一句话中没有换行符,做了一些古怪的事情。我有点不清楚你们是如何说函数显示二进制表示的@埃里克·卡尔森:我也这么想。在大多数机器上,默认情况下,换行符
fflush
,否则您必须自己完成。请参见
man setvbuf
printf("The binary representation of the number 42 is");
printf("The binary representation of the number 42 is\n");