在脚本完成之前执行Ruby系统调用

mic*_*ael 0 ruby erb pdflatex

我有一个Ruby脚本,使用erb模板生成Latex文档.生成.tex文件后,我想进行系统调用以编译文档pdflatex.以下是脚本的骨骼:

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"
Run Code Online (Sandbox Code Playgroud)

system行使我进入交互式tex输入模式,就像文档是空的一样.如果我删除了呼叫,则正常生成文档.如何确保在生成文档之后才进行系统调用?与此同时,我只是使用一个调用ruby脚本的bash脚本,然后pdflatex解决问题.

rob*_*nex 5

File.new直到脚本,直到您手动关闭它最终会打开一个新的流将不会被关闭(保存到磁盘).

这应该工作:

...
f = File.new("/path/to/tex/output.tex")
f.puts template.result
f.close
system "pdflatex /path/to/tex/output.tex"
Run Code Online (Sandbox Code Playgroud)

或者更友好的方式:

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

system "pdflatex /path/to/tex/output.tex"
Run Code Online (Sandbox Code Playgroud)

File.open与块将打开该流,使得该流通过块可变(可访问f的块执行之后在这个例子中)和自动关闭该流.在'w'将打开或创建文件(如果该文件已经存在的内容将被擦除=>该文件将被截断)