Suppressing the output of a command run using 'system' method while running it in a ruby script

后端 未结 8 1221
醉梦人生
醉梦人生 2020-12-29 20:13

I am not sure if this makes sense but I am thinking if there is a way to suppress the output shown for a command when run using the system method in ruby? I mea

相关标签:
8条回答
  • 2020-12-29 21:07

    As an addendum, I've been surprised a few times when I've used backticks and saw output "slipping past" my variables when running scripts from the command line.

    Invariably, the issue is that the text I'm seeing is actually coming from stderr rather than stdout. So, to wrangle that text into stdout as well, remember to append 2>&1 to the command you're trying to run.

    I hope that's helpful to someone. I just wasted twenty minutes re-learning this lesson :)

    0 讨论(0)
  • 2020-12-29 21:10
    • define null_device, it's operating systems dependent: windows 7 and newer use nul, while *nix systems uses /dev/null
    • run the command
    • redirect it's standard and error output to null_device
    • then use the exit code, or the backtick method as mentioned by @mikej to determine the output

    as follows:

     null_device = Gem.win_platform? ? "/nul" : "/dev/null"
    
     do method
       system "run command 1>#{null_device} 2>#{null_device} "
       p ($? == 0)
     end
    
    0 讨论(0)
提交回复
热议问题