How to call shell commands from Ruby

前端 未结 20 2050
旧时难觅i
旧时难觅i 2020-11-22 01:10

How do I call shell commands from inside of a Ruby program? How do I then get output from these commands back into Ruby?

相关标签:
20条回答
  • 2020-11-22 02:02

    The answers above are already quite great, but I really want to share the following summary article: "6 Ways to Run Shell Commands in Ruby"

    Basically, it tells us:

    Kernel#exec:

    exec 'echo "hello $HOSTNAME"'
    

    system and $?:

    system 'false' 
    puts $?
    

    Backticks (`):

    today = `date`
    

    IO#popen:

    IO.popen("date") { |f| puts f.gets }
    

    Open3#popen3 -- stdlib:

    require "open3"
    stdin, stdout, stderr = Open3.popen3('dc') 
    

    Open4#popen4 -- a gem:

    require "open4" 
    pid, stdin, stdout, stderr = Open4::popen4 "false" # => [26327, #<IO:0x6dff24>, #<IO:0x6dfee8>, #<IO:0x6dfe84>]
    
    0 讨论(0)
  • 2020-11-22 02:03

    Don't forget the spawn command to create a background process to execute the specified command. You can even wait for its completion using the Process class and the returned pid:

    pid = spawn("tar xf ruby-2.0.0-p195.tar.bz2")
    Process.wait pid
    
    pid = spawn(RbConfig.ruby, "-eputs'Hello, world!'")
    Process.wait pid
    

    The doc says: This method is similar to #system but it doesn't wait for the command to finish.

    0 讨论(0)
提交回复
热议问题