gpt4 book ai didi

ruby - 关于 ruby​​ popen

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:15 26 4
gpt4 key购买 nike

我正在学习ruby popen,我对一个简单的程序很感兴趣:

pipe = IO.popen("-","w+")
if pipe
pipe.puts "Get a job!"
STDERR.puts "Child says: #{pipe.gets.chomp}"
else
STDERR.puts "Dad says: #{gets.chomp}"
puts "OK"
end

然后产品看起来像这样:

Dad says: Get a job!
Child says: OK

但是,当我通过删除 STDOUT 更新代码时:

pipe = IO.popen("-","w+")
if pipe
pipe.puts "Get a job!"
puts "Child says: #{pipe.gets.chomp}"
else
puts "Dad says: #{gets.chomp}"
puts "OK"
end

然后结果变成这样:

Child says: Dad says: Get a job!

它错过了“OK”!那么,为什么?

最佳答案

如果没有 STDERR.puts 将输出写入标准输出。子进程中的标准输出是管道。写入标准输出的任何内容都不会打印出来,而是发送到管道。

子进程写入2行。

  1. 爸爸说:找份工作吧!
  2. 确定

父进程读取一行(爸爸说:找份工作!),然后打印出来。

Child says: Dad say: Get a job!
^^^^^^^^^^^^^^^^^^^ -- read from the pipe (stdout of child process).

如果您还想打印OK,请调用pipe.gets 两次或使用pipe.read 读取子项的所有输出:

pipe = IO.popen("-","w+")
if pipe
pipe.puts "Get a job!"
puts "Child says: #{pipe.read}"
else
puts "Dad says: #{gets.chomp}"
puts "OK"
end

关于ruby - 关于 ruby​​ popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21771894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com