Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send output to stderr?

Tags:

rust

stdio

One uses this to send output to stdout:

println!("some output") 

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

like image 682
tshepang Avatar asked Dec 21 '14 10:12

tshepang


People also ask

How do I redirect to stderr?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.

How do I redirect stdout and stderr to the same file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator. We have created a file named “sample.


2 Answers

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) } 
like image 51
Shepmaster Avatar answered Oct 25 '22 16:10

Shepmaster


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

  • write! and writeln! to write a formatted string to a &mut Writer
  • format! to just generate a formatted String

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(); } 
like image 24
Francis Gagné Avatar answered Oct 25 '22 17:10

Francis Gagné