我正在尝试从Python程序生成Rust进程,并将Python的标准输出重定向到其标准输入。我使用了以下功能:
process = subprocess.Popen(["./target/debug/mypro"], stdin=subprocess.PIPE)
并尝试使用以下方法写入子进程:
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)]))) #Write bytes of Json representation of previous track
我没有收到任何错误,但Rust中的标准输入似乎没有任何输入,标准输出根本不打印任何内容。
这是我目前正在运行的Rust代码的版本:
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"};
}
答案 0 :(得分:1)
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)]))
默认情况下不添加换行符,因此在Rust方面,我从未到达在read_line
上进行处理阻止的行的末尾。
手动添加它可以使一切顺利进行。
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)])+ "\n") )
答案 1 :(得分:0)
这可能是Python方面的问题
subprocess.run(["cargo run -- " + str(r)], shell=True)
这假设您有一个数字文件描述符,该描述符在fork
和exec
之间保持打开状态。产生进程可能会关闭文件描述符,因为它们被标记为CLOEXEC
或由于exec
之前的显式清理代码。
在尝试将数字文件描述符作为字符串参数传递之前,应确保它们在新进程中保持有效。
更好的方法是使用一些进程生成API,它允许您显式映射新进程中的文件描述符以打开句柄或生成与stdin / out绑定到管道的进程的API。