简体   繁体   English

如果使用Ruby找到字符串,如何从$ stdout中搜索特定字符串并将整个$ stdout存储在文本文件中?

[英]how to search particular string from $stdout and store whole $stdout in text file if string is found using Ruby?

I want to search particular string that will be there in $stdout that I print on console using http.set_debug_output($stdout) . 我想使用http.set_debug_output($ stdout)搜索将在控制台上打印的$ stdout中存在的特定字符串。 I want to search string "Access-Control-Allow-Origin: *\\r\\n" from $stdout and if string found want to store $stdout in text file. 我想从$ stdout搜索字符串“ Access-Control-Allow-Origin:* \\ r \\ n”,如果找到的字符串想在文本文件中存储$ stdout。

$stdout has some special restrictions in ruby. $stdout对红宝石有一些特殊限制。 By default it is opened for reading only (obviously), so to seek/read lines that you've written, you have to replace it as a File . 默认情况下,它是打开的(只读)(显然),因此要查找/读取您编写的行,必须将其替换为File This will suffice: 这样就足够了:

$stdout = File.new("stdout", "w+")
puts "some string"

Kernel#puts will use $stdout by default, so this sets you up perfectly. 默认情况下, Kernel#puts将使用$stdout ,因此这对您来说非常理想。 What you have to implement is checking, it can be a little tricky, but here's one way to approach it. 您需要实现的是检查,这可能会有些棘手,但这是实现它的一种方法。

$stdout = File.new("stdout", "w+")
puts "some string"
old = $stdout
$stdout = IO.try_convert(STDOUT)
old.rewind
old.lines.each do |line|
  puts 'contains requested data' if line == "some string\n"
end

Few things to note on the comparison, puts places \\n automatically at the end of your string. 比较时需要注意的几件事是,将\\n自动放在字符串的末尾。 To escape that \\n so it matches the previous input, you have to put it in the "" quotes. 要转义\\n以使其与先前的输入匹配, 必须将其放在""引号中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM