【问题标题】:Ruby System Call Executing Before Script Finishes在脚本完成之前执行 Ruby 系统调用
【发布时间】:2011-06-08 15:44:31
【问题描述】:

我有一个使用 erb 模板生成 Latex 文档的 Ruby 脚本。生成 .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"

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

【问题讨论】:

    标签: ruby erb pdflatex


    【解决方案1】:

    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' 将打开或创建文件(如果文件已经存在,内容将被删除 => 文件将被截断)

    【讨论】:

    • 为了完整起见,另一种方法(不太合适)是在f.puts 之后添加f.flush。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多