首页 > 解决方案 > Problem using pipe with c++ and python in a loop

问题描述

I want to make a pipe between C++ and Python. The goal is to compute some numbers in C++ and as I'm computing them I want to send them to Python in real time.

So far i can send just an int from C++ to Python using this.

stdout.cpp:

#include <iostream>
int main () {
    int x = 59;
    cout << x;

    return 0;
}


stdin.py:

import sys
import pickle
import fileinput

file2write=open("filename",'w')

stdout = sys.stdin.readlines()
      
file2write.write(str(stdout))

file2write.close()


So far it runs ok and I cand check "filename" and see that python is writing 59 there. But I can't do this in a loop. What I want is something that could process something like

stdout.cpp:

#include <iostream>
int main () {
    int x = 59;
    
    while(1){
        cout << x << "\n";
    }
    return 0;
}


And be able to add each line to the file in python as the program is running. The goal is to do this in an infinite loop and write to the file as the program is running. But when I do something like this the file "filename" ends empty.

What should I do?

标签: pythonc++pipe

解决方案


推荐阅读