python - 如何使用 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))
解决方案
通过专门更改当前工作目录的路径来解决。
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。
推荐阅读
- regex - Ubuntu 16 sed 不能使用括号
- tensorflow - 无法在“float”和“list”的实例之间使用验证数据“<”训练连体
- react-native - 反应原生 admob 安装
- javascript - 多选与 Bootstrap 4.5 和 Bootstrap-Select 冲突
- tsql - 存储过程在调用时从不删除行
- apache-spark - 带火花的默认部署模式
- ios-simulator - iPhone模拟器不断崩溃
- splunk - 寻找一种解决方案,使用适用于 AWS 的 Splunk 插件将 Pega 云服务日志摄取到 Splunk
- python - 如何从 numpy 3d mgrid 到位置数组
- jquery - 如何对仅在数据表中具有数字的列进行排序?