我希望这并不像我感觉的那么简单。我已经设置了一个基本目录:
root --> Paper
--> Code
对于我正在写的一篇论文。我想从 Paper 目录中的knitr 文档调用 Code 目录中的 Python 脚本(类似于this https://github.com/yihui/knitr/issues/277,但使用 Python 而不是 R)。所以它会是这样的:
Python脚本testit.py
## @knitr testit
import os
print os.getcwd()
knitr 文件 test.Rnw 保存在 Code 目录下:
\documentclass{article}
\begin{document}
<<setup,echo=FALSE>>=
read_chunk("testit.py")
@
<<testit,engine='python'>>=
@
\end{document}
当我编译为PDF时,答案是正确的:
## /Users/blah/foo/bar/Code
但文件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}
outputs:
## /Users/blah/foo/bar/Paper
root.dir 在这里没有像 R 块那样的明显效果,而且我不知道还可以尝试更改 Python 块的目录。这是一个问题,因为我想让python脚本对Code目录中的文件进行操作,但它当然找不到它们。我可以在 python 脚本中硬编码目录更改,但这似乎很脆弱。我什至很乐意将根目录直接传递给 python 解释器作为脚本的参数,如果可能的话(但我不这么认为,因为 knit 使用 python -c ?)。关于如何处理这个问题有什么想法吗?我的谷歌-fu在这里让我失望了......