2010-07-15 218 views
42

我试图做的LaTeX以下:如何从LaTeX执行shell脚本?

\documentclass{article} 
\begin{document} 
\execute{/usr/local/bin/my-shell-script.sh} 
\end{document} 

的想法是在.tex文档处理的时刻来执行/usr/local/bin/my-shell-script.sh并注入其输出到LaTeX的流。它有可能吗?

+1

参见http://stackoverflow.com/questions/2671079/how-can-i-save- shell-output-to-a-variable-in-latex – 2010-07-15 08:03:09

+3

有趣的是,这是如何关闭的“脱离主题”。 – Orion 2016-07-17 13:17:18

回答

40

我会做类似下面的(部分动机b ÿ什么建议罗马):使你的LaTeX文件是

\documentclass{article} 
\begin{document} 
\input{scriptoutput.tex} 
\end{document} 

,并使用

/usr/local/bin/my-shell-script.sh > scriptoutput.tex 

你可以在makefile编码这个,如果你想拥有它需要的时候自动运行生成文件scriptoutput.tex。另外,您也可以使用TeX的\write18 command

\documentclass{article} 
\immediate\write18{/usr/local/bin/my-shell-script.sh > scriptoutput.tex} 
\begin{document} 
\input{scriptoutput.tex} 
\end{document} 

,我想这会自动每次编译文档时运行shell脚本。 \immediate对于确保脚本在LaTeX遇到命令时运行而不是等到写入输出页面时才是必需的。 (更多关于shipout例行见this question

+0

您的解决方案肯定比我的更清洁。尽管如此,如果你有很多换人的话,我很方便。 – 2010-07-15 06:46:56

+2

+1 for makefile idea – Gabe 2010-07-15 06:47:45

+0

David,非常感谢,这正是我一直在寻找的! – yegor256 2010-07-15 07:02:26

-1

我不认为这是可能的。我会为此使用一个简单的预处理器。即该文件更改为

\documentclass{article} 
\begin{document} 
%%OUTPUT%% 
\end{document} 

和预处理其与

#!/usr/bin/perl -lp 
BEGIN { $output = `/usr/local/bin/my-shell-script.sh`; } 
s/%%OUTPUT%%/$output/g; 

命令:

perl so.pl template.tex > preprocessed.tex 

或就地:

perl -i so.pl template.tex 
1

除非当务之急是 LaTeX的运行,我会建议只使用make运行乳胶和你的脚本运行脚本。

我已经使用这种方法为文章添加字数统计功能,并包括书目参考资料的统计功能。

让您的脚本生成一个.tex文件并将其包含在您的LaTeX源文件中。

下面是从我的Makefile中的一个片段:

TEX = /usr/texbin/pdflatex 
PREVIEW = /usr/bin/open 

REPORT = SimMon 
REPORT_MASTER = $(REPORT).tex 

TEX_OPTIONS = -halt-on-error 

SimMon: $(REPORT_MASTER) countRefferedPages 
    $(TEX) $(TEX_OPTIONS) $(REPORT_MASTER) 
    @$(PREVIEW) $(REPORT).pdf 

countRefferedPages: BibTeXPageCount 
    cat *.tex | support/BPC/build/Debug/BPC Castle.bib > litteraturTotal.tex 
6

可以在TeX的做到这一点。这个paper (PDF)向您展示了如何在TeX中编写和执行病毒。相同的原则适用于执行shell脚本。但是在我看来,编写一个Makefile文件更加可行,它会在LaTeX运行之前运行并插入结果。

28

正如David所指出的那样,您可以使用\write18来调用外部程序,然后\input产生的输出文件。但是,在调用\input之前,您可能需要使用\immediate\write18来确保脚本已被执行。

替代地,如果使用PDF的较新版本(Ia)的特(1.40后,我想),可以通过管道的输出直接到文档中,通过使用一个管道输入命令:

\documentclass{article} 
\begin{document} 
\input{|"/usr/local/bin/my-shell-script.sh"} 
\end{document} 

对于您将需要启用外部程序调用。对于TeXlive发行版,您需要使用-shell-escape选项来调用latex,或者对于MikTeX,我相信选项是-enable-write18

2

在Ubuntu 11.10的GNU/Linux

pdflatex --enable-pipes --shell-escape mytexfile 

... 
[This section currently is 
\input{|"wc kmb-box.tex| tr -s ' ' | cut -d' ' -f 4"} 
/2000 allowed characters] 

\input{kmb-box} 

... 

很好地工作。即,它使用wordcount(wc)报告文件kmb-box.tex中有多少个字符,它是(包含在)文档中的一部分。

(顺便说一句如果你想的话,而不是文字,只是改变“-f 4”的数量)

+0

当我将命令切换到“ls”时,出现错误。命令输出中的换行符有问题吗? – 2013-08-27 09:53:21