Search code examples
pythonrustipcfile-descriptorpipelining

How can I redirect outputs from a Python process into a Rust process?


I am trying to spawn a Rust process from a Python program and redirect Python's standard output into its standard input. I have used the following function:

process = subprocess.Popen(["./target/debug/mypro"], stdin=subprocess.PIPE)

and tried to write to the subprocess using:

process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)]))) #Write bytes of Json representation of previous track

I am not getting any errors but standard input in Rust doesn't seem to take any input and standard output isn't printing anything at all.

Here's the version of the Rust code I am currently running:

extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io;
use std::env;
use std::str;

fn main(){
    let mut buffer = String::new();
    let stdin = io::stdin();
    //stdin.lock();
    stdin.read_line(&mut buffer).unwrap();
    println!{"{}", buffer};
    println!{"ok"};      

}

Solution

  • process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)])) does not add a newline character by default, so on the Rust side I was never getting to the end of the line which was making the process block on read_line.

    Adding it manually made everything work smoothly.

    process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)])+ "\n") )