RをCGI上で実行

コマンドの基本

R --vanilla --slave --args 12 < test.R

サンプルRスクリプト
test.R

args=commandArgs(trailingOnly=T)
cat(args[1]);

test.R に読み込みと実効権限をつけておけばよい.

chmod a+x test.R
chmod a+r test.R

plot関数をdevをpng(file="test.rb")に変更

CGIでは、Rscriptコマンドを使う必要があるみたい
http://d.hatena.ne.jp/benikujyaku/20120116/1326721281

CGIのデバックはこれをつかう
http://blog.tofu-kun.org/071220192353.php

全角スペースに注意。
標準エラー出直で system でデバッグできる。

zipはデフォルトではhttpdは出力してくれない。
http://q.hatena.ne.jp/1283689839
zip -r コマンドをつけないとフォルダを圧縮しない

Rが文字化けする問題
http://qiita.com/y_benjo/items/a9376a96487d59cc9604

apache文字コードrubyスクリプないで調整する必要あり.、
環境変数をいじると解決
ENV["LANG"]="ja_JP.UTF-8"


zipがへんなファイルもまとめて圧縮する問題
system("cd xxx; zip -r yyy.zip yyy")
ディレクトリを直近まで移動してからzip

エラーを表示させる.

#!/usr/local/bin/ruby
require 'cgi'
require 'fileutils'

cgi=CGI.new
def error_cgi
        print "Content-Type:text/html;charset=EUC\n\n"
        print "*** CGI Error List ***<br />"
        print "#{CGI.escapeHTML($!.inspect)}<br />"
        $@.each {|x| print CGI.escapeHTML(x), "<br />"}

end

begin
        puts "Content-type: text/html charset=UTF-8\n\n"

        id1=Time.now.to_i.to_s
        output_dir="tmpdir/"+id1
        puts output_dir
        FileUtils.mkdir(output_dir)
end


データベース連携

#!/usr/local/bin/ruby
require 'rubygems'
require 'cgi'
require 'fileutils'
require 'sqlite3'

cgi=CGI.new
def error_cgi
        print "Content-Type:text/html;charset=EUC\n\n"
        print "*** CGI Error List ***<br />"
        print "#{CGI.escapeHTML($!.inspect)}<br />"
        $@.each {|x| print CGI.escapeHTML(x), "<br />"}

end


begin



        puts "Content-type: text/html charset=UTF-8\n\n"

        db=SQLite3::Database.new("syoku.sqlite3")

        a=db.execute("select * from update_info")
        #puts "hello"
        #print a[0][1]
        puts "<p>Update Information</p>"
        puts "<table border=1>"
        puts "<tr><td>update_date</td><td>"+a[0][0]+"</td></tr>"
        puts "<tr><td>update_flg</td><td>"+a[0][1].to_s+"</td></tr>"
        puts "</table>"
end