How to call shell commands from Ruby

前端 未结 20 2462
旧时难觅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 01:42

    Given a command like attrib:

    require 'open3'
    
    a="attrib"
    Open3.popen3(a) do |stdin, stdout, stderr|
      puts stdout.read
    end
    

    I've found that while this method isn't as memorable as

    system("thecommand")
    

    or

    `thecommand`
    

    in backticks, a good thing about this method compared to other methods is backticks don't seem to let me puts the command I run/store the command I want to run in a variable, and system("thecommand") doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.

    See "Executing commands in ruby" and Ruby's Open3 documentation.

提交回复
热议问题