How to call shell commands from Ruby

前端 未结 20 2043
旧时难觅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:52

    Some things to think about when choosing between these mechanisms are:

    1. Do you just want stdout or do you need stderr as well? Or even separated out?
    2. How big is your output? Do you want to hold the entire result in memory?
    3. Do you want to read some of your output while the subprocess is still running?
    4. Do you need result codes?
    5. Do you need a Ruby object that represents the process and lets you kill it on demand?

    You may need anything from simple backticks (``), system(), and IO.popen to full-blown Kernel.fork/Kernel.exec with IO.pipe and IO.select.

    You may also want to throw timeouts into the mix if a sub-process takes too long to execute.

    Unfortunately, it very much depends.

提交回复
热议问题