【问题标题】:Sinatra executing ls on sever sideSinatra 在服务器端执行 ls
【发布时间】:2015-08-30 15:39:48
【问题描述】:

我正在尝试使用 Sinatra 在 Chrome 中显示 ls 的结果。但是资源管理器进入了“正在连接...”循环。

我的代码是:

require 'rubygems' if RUBY_VERSION < "1.9"
require 'sinatra/base'

#This is the webservice to launch the gamma project
#Using Request at the principal webpage
class MyApp < Sinatra::Base
  get '/' do
    result = exec "ls"
    puts result 
  end   
end

我不确定puts,我认为这可能不是合适的方法。可能会发生什么,我该如何解决?

PS:在资源管理器中我使用了localhost.com:4567/

【问题讨论】:

    标签: html ruby web-services sinatra


    【解决方案1】:

    使用反引号 ( ` ) 而不是 Kernel#exec 命令。前者返回一个字符串,然后您可以在 ruby​​ 进程中使用该字符串。后者将您的执行上下文扔到一个新进程中,并且没有返回值。

    get '/' do
      result = %x`ls`
      puts result
    end
    

    请注意,对puts 的调用看起来不太好,您可能需要对其进行格式化或进一步解析/操作它。但至少你会得到一些你可以使用的东西。

    【讨论】:

      【解决方案2】:

      正如@pgblu 指出的那样,您应该使用反引号。 https://stackoverflow.com/a/18623297/1279355

      第二件事,puts 仅将结果打印到您的 shell/日志, 但要在您的 chrome 中查看结果,您需要:

      get '/' do
        result = %x`ls`
        return result
      end
      

      get '/' do
        result = %x`ls`
        result
      end
      

      如您所见,返回是可选的,如果没有返回,Sinatra 只会显示最后一个变量/操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-17
        • 1970-01-01
        • 2021-10-28
        • 1970-01-01
        • 1970-01-01
        • 2014-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多