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