6

I am new to rust and cargo, and I am trying to do something very simple!

I have something like this (in build.rs):

use std::process::Command;

fn main() {
    Command::new("echo 123");
}

And I want to see the output of the command echo 123. I want 123 to get printed to the build output (this is mostly to debug what I am doing) and wont be part of the final project.

I have tried cargo build --verbose - this does not work.

I can't extrapolate an answer from there posts (and some others like it):

I feel this must be simple to do - but I have been stuck for hours looking on the web and not finding the answer.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
code_fodder
  • 15,263
  • 17
  • 90
  • 167

3 Answers3

3

Just building a Command with Command::new does not execute it yet. It just starts a builder pattern. To actually execute it, you have to use the methods spawn, output or status. Example:

Command::new("echo")
    .arg("123")
    .spawn()
    .expect("failed to spawn process");

It's very unfortunate that this doesn't produce a warning. Someone recently tried to add the #[must_use] attribute to Command, which would make your code procude a warning. The PR closed for now but it seems like it will be added eventually.

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
  • Thanks, good to know about the command not running! - But I still do not get any output here (even if I copy/paste your answer in). I added the argument `> test.out` - and no `test.out` file was generated. I also tried with state and output... any clues? – code_fodder May 10 '21 at 07:13
  • @code_fodder Oops, I kinda forgot about that part of the question. As mentioned in the first issue you linked, `cargo build -vv` does show the output of the build script. The output is also shown with a normal `cargo build` if the build script exits with a non 0 exit code. So `std::process::exit(1)` will also show the output. (Of course, only use that if there is an actual error.) – Lukas Kalbertodt May 10 '21 at 07:39
  • ah ha, great thanks. I Was still trying `--verbose` :) – code_fodder May 10 '21 at 09:13
  • Is there any way to debug build.rs file? – Saeed Masoomi Mar 08 '22 at 14:31
3

We can use a macro and it worked form me, but there is a warning, since it uses cargo to display. but that is fine for me. I found below code from git hub discussion: Cargo doesn’t display output from a command in build.rs #985

macro_rules! p {
    ($($tokens: tt)*) => {
        println!("cargo:warning={}", format!($($tokens)*))
    }
}

fn main() {
    p!("BUILD.rs -> Starting ...");
}
0

Specifying -vv option with cargo, lets you see the output from the build scripts. For more information, refer this.

So, you can store the output of the command in a string, and then possibly write out using println.

Krishna
  • 33
  • 5