2011-06-08 52 views
0

我有一個使用erb模板生成Latex文檔的Ruby腳本。 .tex文件生成後,我想進行系統調用以編譯文檔pdflatex。下面是腳本的骨頭:在腳本完成之前執行Ruby系統調用

class Book 
    # initialize the class, query a database to get attributes, create the book, etc. 
end 

my_book = Book.new 
tex_file = File.open("/path/to/raw/tex/template") 
template = ERB.new(tex_file.read) 
f = File.new("/path/to/tex/output.tex") 
f.puts template.result 
system "pdflatex /path/to/tex/output.tex" 

system線使我互動TEX輸入模式下,如果該文件是空的。如果我刪除了該呼叫,則文檔將正常生成。我怎樣才能確保在生成文檔之後才能進行系統調用?與此同時,我只是使用一個調用ruby腳本的bash腳本,然後解決這個問題。

回答

5

File.new將打開一個新的流,直到您手動關閉它纔會關閉(保存到磁盤),直到腳本結束爲止。

這應該工作:

... 
f = File.new("/path/to/tex/output.tex") 
f.puts template.result 
f.close 
system "pdflatex /path/to/tex/output.tex" 

或者更友好的方式:

... 
File.open("/path/to/tex/output.tex", 'w') do |f| 
    f.puts template.result 
end 

system "pdflatex /path/to/tex/output.tex" 

File.open與塊將打開流,使流通過塊變量訪問(f在這例如)並在塊執行後自動關閉流。 'w'將打開或創建文件(如果文件已存在,內容將被刪除=>該文件將被截斷)

+0

當然!謝謝。 – michaelmichael 2011-06-08 15:58:13

+0

爲了完整起見,另一種方法(不太合適)是在'f.puts'後面加上'f.flush'。 – 2011-06-08 23:44:18

相關問題