如何将 Python 进程的输出重定向到 Rust 进程?
How can I redirect outputs from a Python process into a Rust process?
我正在尝试从 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"};
}
这可能是Python方面的问题
subprocess.run(["cargo run -- " + str(r)], shell=True)
这假设您有一个在 fork
和 exec
期间保持打开的数字文件描述符。生成进程可能会关闭文件描述符,因为它们被标记为 CLOEXEC
或由于 exec
.
之前的显式清理代码
在尝试将数字文件描述符作为字符串参数传递之前,您应该确保它们在新进程中仍然有效。
更好的方法是使用一些进程生成 API,它允许您显式地将新进程中的文件描述符映射到打开的句柄,或者使用 API 生成进程 [=24] =] 绑在管道上。
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)]))
默认情况下不添加换行符,所以在 Rust 方面,我永远不会到达使进程在 read_line
.[=13 上阻塞的行尾=]
手动添加使一切顺利。
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)])+ "\n") )
我正在尝试从 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"};
}
这可能是Python方面的问题
subprocess.run(["cargo run -- " + str(r)], shell=True)
这假设您有一个在 fork
和 exec
期间保持打开的数字文件描述符。生成进程可能会关闭文件描述符,因为它们被标记为 CLOEXEC
或由于 exec
.
在尝试将数字文件描述符作为字符串参数传递之前,您应该确保它们在新进程中仍然有效。
更好的方法是使用一些进程生成 API,它允许您显式地将新进程中的文件描述符映射到打开的句柄,或者使用 API 生成进程 [=24] =] 绑在管道上。
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)]))
默认情况下不添加换行符,所以在 Rust 方面,我永远不会到达使进程在 read_line
.[=13 上阻塞的行尾=]
手动添加使一切顺利。
process.stdin.write(str.encode(json.dumps(dictionnaire[str(index)])+ "\n") )