hiding system command results in ruby

2019-04-20 19:28发布

问题:

How easy is it to hide results from system commands in ruby? For example, some of my scripts run

system "curl ..." 

and I would not prefer to see the results of the download.

回答1:

You can use the more sophisticated popen3 to have control over STDIN, STDOUT and STDERR separately if you like:

Open3.popen3("curl...") do |stdin, stdout, stderr, thread|
  # ...
end

If you want to silence certain streams you can ignore them, or if it's important to redirect or interpret that output, you still have that available.



回答2:

Easiest ways other than popen:

  1. Use %x instead of system. It will automatically pipe

    rval = %x{curl ...}       #rval will contain the output instead of function return value
    
  2. Manually pipe to /dev/null. Working in UNIX like system, not Windows

    system "curl ... > /dev/null"
    


回答3:

The simplest one is to redirect stdout :)

system "curl ... 1>/dev/null"
# same as
`curl ... 1>/dev/null`


回答4:

To keep it working with system without modifying your command:

system('curl ...', :err => File::NULL)

Source