How to read input and execute in loop?

I want to read input from user and execute commands.

Here's my code:

use std::io;
use std::ffi::{OsStr,OsString};
use std::process::Command;

fn main() {
loop {
let mut cmd = String::new();
io::stdin().read_line(&mut cmd);
let cmd = OsString::from(cmd);
let output = Command::new(cmd.as_os_str()).output().expect("FAILED");
print!("{}", String::from_utf8_lossy(&output.stdout));
}
}

However, when I run it, and type something like /bin/uname
it spits strange error:
thread 'main' panicked at 'FAILED: Error { repr: Os { code: 2, message: "No such file or directory" } }', /checkout/src/libcore/result.rs:906:4
note: Run with RUST_BACKTRACE=1 for a backtrace.

I passed OsStr to Command::new, because it accepts argument that implements the trait AsRef

If I change inner argument to slice, like "/bin/uname" it works without runtime errors.

What's my mistake? Thanks.
How should I format my question, so that code is rendered as code not as a plain text?
rustc 1.22.1 (05e2e1c41 2017-11-22)

However, when I run it, and type something like /bin/uname
it spits strange error:

Your issue is that read_line() includes the newline. You can do

let cmd = OsString::from(cmd.trim_right());

By the way, it is not necessary to explicitly construct an &OsStr or even an OsString. Command::new would work with any of &String, &str, &OsString, &OsStr, or &Path, because String/str/OsString/OsStr/Path all implement AsRef<OsStr>.

let mut cmd = String::new();
io::stdin().read_line(&mut cmd);
let output = Command::new(cmd.trim_right()).output().expect(“FAILED”);

How should I format my question, so that code is rendered as code not as a plain text?

Discourse uses Github-flavored markdown, which has fenced code-blocks.

```rust
fn main() { }
```

fn main() { }

You can also use `single backticks` for inline code.

2 Likes