我希望这并不像感觉那么简单.我有一个基本目录设置:
root --> Paper
--> Code
Run Code Online (Sandbox Code Playgroud)
我正在写一篇论文.我想从Paper目录中的knitr文档中调用Code目录中的Python脚本(类似于此,但使用Python而不是R).所以它会是这样的:
Python脚本testit.py
## @knitr testit
import os
print os.getcwd()
Run Code Online (Sandbox Code Playgroud)
knitr document test.Rnw保存在Code目录中:
\documentclass{article}
\begin{document}
<<setup,echo=FALSE>>=
read_chunk("testit.py")
@
<<testit,engine='python'>>=
@
\end{document}
Run Code Online (Sandbox Code Playgroud)
当我编译成PDF时,答案是正确的:
## /Users/blah/foo/bar/Code
Run Code Online (Sandbox Code Playgroud)
但是文件test-2.Rnw保存在Paper目录中:
\documentclass{article}
\begin{document}
<<setup,echo=FALSE>>=
opts_knit$set(root.dir="../Code/")
read_chunk("../Code/testit.py")
@
<<testit,engine='python'>>=
@
\end{document}
Run Code Online (Sandbox Code Playgroud)
输出:
## /Users/blah/foo/bar/Paper
Run Code Online (Sandbox Code Playgroud)
root.dir在这里没有像R块那样明显的效果,我不知道还有什么可以尝试更改Python块的目录.这是一个问题,因为我希望python脚本对Code目录中的文件进行操作,但当然它找不到它们.我可以在python脚本中硬编码目录更改,但这似乎很脆弱.我甚至很高兴将根目录直接传递给python解释器作为脚本的参数,这是可能的(但我不这么认为,因为knitr使用python -c?).有关如何处理这个问题的任何想法?我的google-fu在这里失败了......