ruby - 如何将curl 的输出读入ruby 变量?

标签 ruby curl stdout puts

假设我有以下 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  -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"

希望有帮助。

关于ruby - 如何将curl 的输出读入ruby 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675288/

相关文章:

ruby - 在 Ruby 中,如何反向 dns 查找 zeroconf/bonjour 计算机的主机名?

ruby 以四人为一组处理数组元素

python - 防止子进程的子进程写入标准输出

php - CURLOPT_NOPROXY 不影响 PHP

php - 如何从网站下载所有图片?

laravel - Laravel x Docker:如何从排队的作业中获取STDOUT日志?

python - 实时读取python STDOUT

ruby - 找不到 bundle 命令 mac

ruby - 都做吗?和任何?保证短路评估?

php - Python xml-rpc 与 PHP 客户端和 unicode 不工作