Running another ruby script from a ruby script

后端 未结 7 1004
终归单人心
终归单人心 2020-12-01 04:48

In ruby, is it possible to specify to call another ruby script using the same ruby interpreter as the original script is being run by?

For example, if a.rb runs b.rb

7条回答
  •  醉话见心
    2020-12-01 05:04

    The require trick is a good idea, assuming the script in question doesn't choke trying to redefine any constants you may have set, or calling methods on objects you may have runtime monkey patched to no longer honor their standard contracts.

    In either case, the problem is less the approach than it is the code in the scripts themselves. Show good manners, put your constants in a namespace, and don't monkey patch the runtime desctructively.

    To ensure the script in question doesn't mess with the runtime of your calling script, and to guard against the chance it might call Kernel/Process.exit() somewhere, try the following

    pid=Process.fork do
        require 'script.rb'
        Process.exit
    end
    ignored, status = Process.waitpid2(pid, Process::WNOHANG)
    puts "script.rb PID #{pid} exited, exit status: #{status.exitstatus}" 
    

    For more advanced things like writing to its stdin stream or reading from its stdout or stderr streams, use the Open4 gem.

提交回复
热议问题