如何在Rust中获得std::process::command后面的命令?
我正在传阅这类事件的实例。在执行命令之前,我想记录整个命令。例如,如果给我一个这样构造的命令实例: let command=command::newsh .arg-c 阿杰乔先生你好 我想写一条日志消息,如:如何在Rust中获得std::process::command后面的命令?,rust,Rust,我正在传阅这类事件的实例。在执行命令之前,我想记录整个命令。例如,如果给我一个这样构造的命令实例: let command=command::newsh .arg-c 阿杰乔先生你好 我想写一条日志消息,如: Executing command: 'sh' '-c' 'echo hello' 不过,API看起来相当有限。有没有办法做到这一点 使用std::process::命令; fn干线{ 让mut command=command::newls; command.arg-l; println
Executing command: 'sh' '-c' 'echo hello'
不过,API看起来相当有限。有没有办法做到这一点
使用std::process::命令;
fn干线{
让mut command=command::newls;
command.arg-l;
println!{:?},命令;
}
输出:ls-l
使用std::process::命令;
fn干线{
让mut command=command::newls;
command.arg-l;
println!{:?},命令;
}
输出:ls-l您希望访问命令结构中的私有字段。设计无法访问专用字段 但是,当为结构实现调试特性时,将使用{:?}格式选项“打印”私有成员 要以编程方式访问这些私有成员,请使用以下格式!宏。这将返回一个std::字符串并接受{:?}格式选项。这只会起作用,因为已为命令实现了调试特性
fn main() {
let mut command = Command::new("ls");
command.arg("-l");
let command_string: String = std::format!("{:?}", command);
// Print the command_string to standard output
println!("cmd: {}", command_string);
// split the command string accordinig to whitespace
let command_parts = command_string.split(' ');
// print the individual parts of the command_string
for (index, part) in command_parts.enumerate() {
println!("part[{}]: {}", index, part);
}
}
输出:
$> test_prog
cmd: "ls" "-l"
part[0]: "ls"
part[1]: "-l"
$>
您希望访问命令结构中的私有字段。设计无法访问专用字段 但是,当为结构实现调试特性时,将使用{:?}格式选项“打印”私有成员 要以编程方式访问这些私有成员,请使用以下格式!宏。这将返回一个std::字符串并接受{:?}格式选项。这只会起作用,因为已为命令实现了调试特性
fn main() {
let mut command = Command::new("ls");
command.arg("-l");
let command_string: String = std::format!("{:?}", command);
// Print the command_string to standard output
println!("cmd: {}", command_string);
// split the command string accordinig to whitespace
let command_parts = command_string.split(' ');
// print the individual parts of the command_string
for (index, part) in command_parts.enumerate() {
println!("part[{}]: {}", index, part);
}
}
输出:
$> test_prog
cmd: "ls" "-l"
part[0]: "ls"
part[1]: "-l"
$>
但是没有办法手动访问命令部分来控制格式?我已经简化了这个问题,在我的用例中,我希望通过编程方式访问命令片段。这似乎不可能。我会接受这个答案,但是伙计,API中的一个不幸的遗漏。但是没有办法手动访问命令部分来控制格式?我已经简化了这个问题,在我的用例中,我想通过编程方式访问命令片段。这似乎不可能。我会接受答案的,但是伙计,API中的一个不幸的遗漏。这通常不起作用,split“”可以在参数中的空格上拆分。您需要正确地重新分析字符串,考虑引号-非常难看。这通常不起作用,拆分“”可以拆分参数中的空格。您需要正确地重新解析字符串,考虑引用-非常难看。