Rust exec external command python Input And Output

I start python from rust as external command and want to piped the output and input, but it seems does not work...

code here:

use std::process::{Command,Stdio};
use std::string;
use std::io::{Write,BufReader,BufRead,BufWriter,Error, ErrorKind, Read};
use std::thread::spawn;
use std::path::Path;
use std::convert::From;

fn main() 
{
    let mut child = Command::new("python").
    stdout(Stdio::piped()).
    stdin(Stdio::piped()).
    spawn();

    if child.is_ok()
    {
        let mut process = child.as_mut().unwrap();
        let mut pipedOut = process.stdout.as_mut().unwrap();
        let mut pipedIn = process.stdin.as_mut().unwrap();
        let mut reader = BufReader::new(pipedOut);
        let mut exit = false;
        pipedIn.write_all(b"print \"python test\";");
        while (!exit)
        {
            let mut line = String::new();
            if reader.read_line(&mut line).unwrap() > 0
            {
                println!("from rust read: {}",line);
            }
        }
    }
}

You need to close the pipe before python will start executing the code.

close the pipe? pipedIn?

Yes. The python process keeps waiting for more input until you close the stdin pipe. You can close it by dropping it, and to do that you can use Option::take instead of Option::as_mut to take ownership of the pipe like this:

// use take() to take ownership of the pipe instead of borrowing it
let pipedIn = process.stdin.take().unwrap();
pipedIn.write_all(b"print \"python test\";").unwrap();
drop(pipedIn);
// now go read from pipedOut

If i close the pipe, and how to do the next input?

You will need to start another python process.

hmm....Ok, the external command keeps runing, read the output from the pipedOut and input through the pipedIn, so , start another py process is not the solution...

Python will not start executing piped code until you close the pipe, and the pipe cannot be reopened again. Perhaps you can run some python script instead, which executors your code with eval?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.