[英]Pipe between a C and a Python program
我目前正在尝试编写一个与硬件交互的 C 程序,我选择了这样,因为硬件制造商为此硬件提供了 C SDK。 However, I want this C program to output the data it receives from the hardware (a sensor for example) to a pipe so that I can write a Python program to pick up the data and parse it and do some analytical things with it. 我在 Raspberry Pi (Linux) 上运行这些程序。 如何在这两个不同的程序(Python 和 C)之间创建 pipe? 我可以通过 pipe 位置来做到这一点吗?
由于您只想在一个方向上 pipe 数据,因此您不需要在代码中创建 pipe。
最简单的方法是通过将数据写入 C 程序中的stdout
并从stdin
中的标准输入读取数据,让操作系统 pipe 为您提供数据。
你会像这样运行程序:
mycprog | python myscript.py
在 C 代码中,您将使用如下内容:
#include <stdio.h>
unsigned char buffer[BUFFER_SIZE];
/* read from sensor to buffer */
fwrite(sensor_buffer, sizeof(usigned char), BUFFER_SIZE, stdout);
在 Python 端,代码如下所示:
import sys
sensor_bytes = sys.stdin.read(BUFFER_SIZE)
您也可以使用popen
直接从 C 代码启动 Python 脚本,但这会使您的解决方案不那么灵活,如果您想将数据发送到另一个脚本或程序,则必须更改 Z0D61F83740CAD812F743E 代码。
最后,如果您不想依赖 shell,或者您想在不同的 shell 中运行两个程序,您可以使用mkfifo
创建一个名为 pipe 的程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.