如何通过管道将数据从C程序传送到Python程序?

2 投票
1 回答
4720 浏览
提问于 2025-04-18 06:25

我之前在一个C程序里做一些数字计算,还维护了一个图形界面。现在我想继续在C里进行数字计算,但把数据发送到Python。然后,Python会根据发送过来的值来创建和更新图形界面。

有没有人能告诉我怎么把一个变量或数组从C程序发送到Python程序,然后在Python里打印出来的代码?

谢谢!

1 个回答

-1

考虑一下:

fifo.c

#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>

int main (void)
{
    // Array to send
    int arr[] = {2,4,6,8};
    int len = 4;

    // Create FIFO
    char filename[] = "fifo.tmp";

    int s_fifo = mkfifo(filename, S_IRWXU);
    if (s_fifo != 0)
    {
        printf("mkfifo() error: %d\n", s_fifo);
        return -1;
    }

    FILE * wfd = fopen(filename, "w");
    if (wfd < 0)
    {
        printf("open() error: %d\n", wfd);
        return -1;
    }

    // Write to FIFO
    for (int i=0; i<len; i++)
    {
        int s_write = fprintf(wfd, "%d ", arr[i]);

        if (s_write < 0)
        {
            printf("fprintf() error: %d\n", s_write);
            break;
        }
    }

    // Close and delete FIFO
    fclose(wfd);
    unlink(filename);
}

fifo.py

filename = "fifo.tmp"

# Block until writer finishes...
with open(filename, 'r') as f:
    data = f.read()

# Split data into an array
array = [int(x) for x in data.split()]

print array

你首先会运行写入程序(c),这个程序会一直等着,直到读取程序(python)打开并读取数据。然后再运行读取程序,这样两个程序就会结束。

$ python fifo.py
[2, 4, 6, 8]

注意事项:

  • 如果能加一些更好的错误处理会更好,比如如果命名的fifo存在,可能是因为c程序没有正常退出。
  • 这样做有点低效,因为你把整数值转换成字符串再发送。虽然我用这种方式是因为用空格分隔比较简单,但你可以考虑直接发送整数值,然后在读取那边用固定宽度来解析。

撰写回答