我在Ruby中使用IO.popen
来在循环中运行一系列命令行命令。 然后我需要在循环之外运行另一个命令。 直到循环中的所有命令均已终止,循环外部的命令才能运行。
我如何让程序等待发生? 目前最后的命令运行得太快了。
一个例子:
for foo in bar IO.popen(cmd_foo) end IO.popen(another_cmd)
所以所有的cmd_foos
需要在another_cmd
运行之前返回。
我认为你需要把循环中的IO.popen
调用的结果赋值给变量,并且继续调用read()
,直到eof()
变为true。
那么你知道所有的程序都已经完成了执行,你可以启动another_cmd
。
使用块形式并阅读所有内容:
IO.popen "cmd" do |io| # 1 array io.readlines # alternative, 1 big String io.read # or, if you have to do something with the output io.each do |line| puts line end # if you just want to ignore the output, I'd do io.each {||} end
如果您不读取输出,则可能是因为连接其他进程和进程的管道已满并且没有人读取该进程而阻塞进程。
显然,执行此操作的规范方法是:
Process.wait(popened_io.pid)
for foo in bar out = IO.popen(cmd_foo) out.readlines end IO.popen(another_cmd)
读取输出到一个变量,然后调用out.readlines
做到了。 我认为out.readlines
必须等待进程结束才能返回。
感谢Andrew Y为我指出正确的方向。
我建议你使用Thread.join
来同步最后的popen
调用:
t = Thread.new do for foo in bar IO.popen(cmd_foo) end end t.join IO.popen(another_cmd)
你需要popen
的输出吗? 如果不是,你想使用coreel#system
还是其他一些命令?