如何在 Python 参数中传递 Ruby 实例变量



我正在构建一个Rails应用程序,用于接收用Python处理的CSV文件。我正在做一些简单的测试,并设法在我的Rails应用程序中执行一个Python脚本,并在浏览器中输出结果。

现在,我想传递上传到 rails 应用程序的 CSV 文件,作为我的 Python 脚本的参数。

这是我目前尝试的:

upload_excel_controller.rb

require 'json'
class UploadExcelController < ApplicationController
require 'csv'
def index
end
def import
rowarray = Array.new
myfile = params[:file]
@rowarraydisp = CSV.read(myfile.path)
@result = JSON.parse(`python lib/assets/python_scripts/python_test.py @rowarraydisp`)
end
end

python_test.py

import json, sys
arg = sys.argv[1]
def main():
return(arg)
if __name__ == "__main__":
json.dump(main(), sys.stdout)

索引.html.erb

<%= form_tag({:action => :import}, multipart: true) do %>
<%= file_field_tag :file %>
<%= submit_tag( "Import" ) %>
<% end %>

import.html.erb

<% @result.each do |substring| %>
<%= substring %>
<p>End of this string, check next line for the other one!
<% end %>
<p>End of script</p>

当我运行这个时,我收到此错误:undefined method 'each' for "@rowarraydisp":String.

似乎@rowarraydisp是作为字符串传递的。

像这样尝试

%x[python lib/assets/python_scripts/python_test.py #{@rowarraydisp}]

最新更新