【问题标题】:How do I read the output of a curl into a ruby variable?如何将 curl 的输出读入 ruby​​ 变量?
【发布时间】:2014-05-05 16:46:17
【问题描述】:

假设我有以下curl 电话:

"curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate"

我正在尝试获取 curl 调用的输出。例如200 OK404 ERROR 状态。

所以,如果我这样做:

a = `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

a 我什么也得不到

但是,如果我这样做了

puts `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

然后我可以看到输出。如何将其读入变量。如果可能的话,我更喜欢没有像 OPEN3 这样的导入的答案。

【问题讨论】:

  • 你试过:`a = curl "blah.blah" - 有谁知道如何逃避反引号?
  • 变量中的也是反引号?或者只是为变量添加一个反引号? a = curl "blah.blah"`` ??
  • 那是另一个问题。我认为`

标签: ruby curl stdout puts


【解决方案1】:

我不知道为什么

a = `curl  -v --insecure -X POST -H 'Host: api.test.com' -H 'Tester #{@@test_name}' -d 'token=#{token_raw}' https://teststage.BLAHBLAH:token/terminate`

不适合你。

这是我通过更简单的测试得到的结果:

RUBY_VERSION # => "1.9.3"

`curl --version`
# => "curl 7.30.0 (x86_64-apple-darwin13.0) libcurl/7.30.0 SecureTransport zlib/1.2.5\nProtocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp \nFeatures: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz \n"

a = `curl http://echo.jsontest.com/hello/world`

a # => "{\"hello\": \"world\"}\n"

更新

我错过了您的部分问题,没有意识到您正在寻找标题。

试试这个:

a = `curl -I http://echo.jsontest.com/hello/world`
a.lines.first # => "HTTP/1.1 200 OK\r\n"

希望对您有所帮助。

【讨论】:

  • 所以,我的更新实际上是如果我收到 404 错误,我会得到一些随机 JSON。如果有效,则为空白。这就是我的工作方式。
  • 技术上没有。但我想我可以忍受它。谢谢。
  • 哦,重新阅读您的问题后。我误解了其中的一部分。我会编辑。
【解决方案2】:

您可能只想使用Ethon 与 libcurl 进行交互,而不是调用 shell 接口,特别是如果您不愿意使用 Ruby 提供的工具来更轻松地与 shell 和其他进程交互(您知道,比如Open3)。

注意:Ruby 标准库(包括 Open3)是 Ruby 的一部分并随它一起分发。这绝不是一个导入,但如果你真的不想使用 require 方法出于某种原因,IO 无需加载额外代码即可使用,并提供 Open3 使用的低级接口。

【讨论】:

  • 哦,真的吗?谢谢你。
【解决方案3】:

试试这个:

HTTP_RESP_CODE=$(curl -s -o out.html -w '%{http_code}' http://www.example.com)

echo $HTTP_RESP_CODE

这适用于我的ruby

HTTP_RESP_CODE=`curl -s -o out.html -w '%{http_code}' http://www.example.com`
print HTTP_RESP_CODE

【讨论】:

  • t.ruby:1: `$(' 不允许作为全局变量名 t.ruby:1: 语法错误,意外的输入结束 @@r = $(curl -v --insecure -X POST ...
  • @gran_profaci 不知道。您可以尝试将我的示例 curl 命令放入 `...` 而不是 $(...)
  • 同样的错误。这显然是一个语法问题。
  • @gran_profaci 我刚刚用 ruby​​ 检查了代码(请参阅更新的答案),它可以工作。可能是您的问题出在其他地方!
猜你喜欢
  • 2011-04-30
  • 2010-10-30
  • 1970-01-01
  • 2023-04-06
  • 2018-07-16
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多