简体   繁体   中英

Printing continuously from Python script to C program

I'm looking at sending data to a C program for use with RTAI FIFO communication, and from my understanding there is no RTAI support to communicate directly from a Python script into kernel space, hence my solution.

I am using subprocess to handle these communications however it is not working.

My Python script:

import subprocess
from random import seed
from random import random
p = subprocess.Popen(['./data_reciever'], 
                        stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

while True:

    seed(1)
    network_data = f"{random()}, {random()}, {random()}".encode()
    print(network_data, "from py")
    p.stdin.write(network_data)
    p.stdin.flush()

My C code:

#include <stdio.h>

int main(void){

    while(1){
        char data;
        scanf("%c", &data);
        printf("%c", data);
    }

    return(0);

}

I think that my problem lies either with the stdin.write or my scanf as my python print is printing to terminal but my C program is not.

I have tried many of the similar examples on here but I have not been able to get them to work, any help would be appreciated.

I don't have a ton of experience with Popen , but it seems to be because you're saying that the stdout of the process will be piped, but then you don't try to pipe the data out. Removing stdout=subprocess.PIPE, from the argument list fixes it for me.

p = subprocess.Popen(['./data_reciever'], 
                     stdin=subprocess.PIPE, stderr=subprocess.STDOUT)

Also, you shouldn't seed in the loop. That's why your random data is all the same.

The C loop can be simplified a bit too:

while(1){
    char data = getchar();
    printf("%c", data);
}

Although that's not relevant to the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM