How to send output to stderr?

2020-02-08 23:27发布

One uses this to send output to stdout:

println!("some output")

I think there is no corresponding macro to do the same for stderr.

标签: rust stdio
5条回答
The star\"
2楼-- · 2020-02-08 23:35

After Rust 1.19

As of Rust 1.19, you can use the eprint and eprintln macros:

fn main() {
    eprintln!("This is going to standard error!, {}", "awesome");
}

This was originally proposed in RFC 1896.

Before Rust 1.19

You can see the implementation of println! to dive into exactly how it works, but it was a bit overwhelming when I first read it.

You can format stuff to stderr using similar macros though:

use std::io::Write;

let name = "world";
writeln!(&mut std::io::stderr(), "Hello {}!", name);

This will give you a unused result which must be used warning though, as printing to IO can fail (this is not something we usually think about when printing!). We can see that the existing methods simply panic in this case, so we can update our code to do the same:

use std::io::Write;

let name = "world";
let r = writeln!(&mut std::io::stderr(), "Hello {}!", name);
r.expect("failed printing to stderr");

This is a bit much, so let's wrap it back in a macro:

use std::io::Write;

macro_rules! println_stderr(
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

fn main() {
    let name = "world";
    println_stderr!("Hello {}!", name)
}
查看更多
家丑人穷心不美
3楼-- · 2020-02-08 23:37

print! and println! are convenience methods for writing to standard output. There are other macros with the same formatting features available for different tasks:

To write to the standard error stream, you can use e.g. writeln! like this:

use std::io::Write;

fn main() {
    let mut stderr = std::io::stderr();
    writeln!(&mut stderr, "Error!").unwrap();
}
查看更多
Luminary・发光体
4楼-- · 2020-02-08 23:41

It's done so:

use std::io::Write;

fn main() {
    std::io::stderr().write(b"some output\n");
}

You can test it by sending the program output to /dev/null to ensure it works (I ignore the warning):

$ rustc foo.rs && ./foo > /dev/null
foo.rs:4:5: 4:42 warning: unused result which must be used, #[warn(unused_must_use)] on by default
foo.rs:4     io::stderr().write(b"some output\n");
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
some output

Similarly, one can do the following for stdout:

use std::io::Write;

fn main() {
    std::io::stdout().write(b"some output\n");
}

I think this means println! is just a convenience: it's shorter and it also allows some formatting. As an example of the latter, the following displays 0x400:

println!("0x{:x}", 1024u)
查看更多
家丑人穷心不美
5楼-- · 2020-02-08 23:45

While not answering the precise question, maybe it’s of interest that there’s a log crate which specifies an interface for leveled logging that other crates (e.g. env_logger) can fulfill.

The output of such logging will be sent to stderr, and there are additional benefits for users, such as specifying the log level.

This is how using such a logger could look like:

#[macro_use]
extern crate log;
extern crate env_logger;

fn main() {
    env_logger::init().unwrap();
    error!("this is printed by default");
}

(Example adapted from http://burntsushi.net/rustdoc/env_logger/index.html#example)

查看更多
干净又极端
6楼-- · 2020-02-08 23:54

Goal

stderr!("Code {}: Danger, Will Robinson!  Danger!", 42);

Notes

The other answers generate an unused import warning with the latest nightly, so here's a modern macro that Just Works TM.

Code

macro_rules! stderr {
    ($($arg:tt)*) => (
        use std::io::Write;
        match writeln!(&mut ::std::io::stderr(), $($arg)* ) {
            Ok(_) => {},
            Err(x) => panic!("Unable to write to stderr (file handle closed?): {}", x),
        }
    )
}
查看更多
登录 后发表回答