hiding system command results in ruby

为君一笑 提交于 2019-12-06 19:05:20

问题


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:


To keep it working with system without modifying your command:

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

Source




回答4:


The simplest one is to redirect stdout :)

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


来源:https://stackoverflow.com/questions/10922044/hiding-system-command-results-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!