首页 > 解决方案 > 如何使用 Rmarkdown 中 Python 块中单独文件中定义的 Python 函数?

问题描述

所以,我有一个名为“function.py”的文件,其中包含简单的函数:

def square(x):
  return x*x

我有第二段这样的代码:

from test import square
print(square(2))

如果我将第二段代码存储在 python 文件中并在终端中运行它,它可以工作并给出预期的答案。

但是,如果我在 Rmarkdown 文档中添加一个 Python 块,如下所示:

```{python}
from test import square
print(square(2))
```

我得到错误:

“回溯(最近一次通话最后一次):文件“/var/folders/g7/462tmml173nfzj0j8437t9_m0000gn/T/RtmptMA22N/chunk-code-48764cec023f.txt”,第 1 行,来自测试导入方 ImportError:无法导入名称方”

Rmarkdown 文件和 python 文件在同一个目录下。有关特定错误消息的答案与依赖关系有关,但我看不出这与我的情况有何相关?

我已经在网上搜索并阅读了文档,但我认为我遗漏了一些重要的东西。感谢您的帮助!

编辑: 通过专门更改当前工作目录的路径来解决。

import sys, os
sys.path.append(os.getcwd())
import test
print(test.square(2))

标签: pythonr-markdown

解决方案


通过专门更改当前工作目录的路径来解决。

import sys, os
sys.path.append(os.getcwd())
import test
print(test.square(2))

答案基于Python: Best way to add to sys.path relative to the current running script


推荐阅读