You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RStudio的RMarkdown中导入自定义Python模块?

Using Custom Python Modules in RMarkdown

Hey there! I’ve been in your shoes before—trying to get custom Python code running smoothly in RMarkdown can feel tricky at first, but it’s totally doable with the right setup. Let’s break this down step by step:

1. Install & Load the reticulate Package

This is the core package that lets R talk to Python. First, make sure it’s installed and loaded in your RMarkdown document:

install.packages("reticulate") # Only need to run this once
library(reticulate)

2. Point Reticulate to Your Python Environment

You need to make sure reticulate is using the same Python environment where your custom modules live (the one you use in PyCharm). If you’re using a virtual environment or conda environment, specify it like this:

  • For a virtual environment:
    use_virtualenv("path/to/your/virtualenv")
    
  • For a conda environment:
    use_condaenv("your-conda-env-name")
    

If you’re not sure which environment to use, run py_config() in an R code block to see which Python reticulate is currently using.

3. Add Your Module Directory to Python’s sys.path

This is the most common gotcha! Python won’t automatically find your custom modules unless their parent directory is in sys.path. You can add it either via R code or directly in a Python code block:

Option A: Add via R

# Replace "path/to/your/code/directory" with the actual path to your `code` folder's parent directory
py_run_string('import sys; sys.path.append("path/to/your/code/directory")')

Option B: Add directly in a Python code block

import sys
sys.path.append("/path/to/your/code/directory") # Use absolute path for reliability

4. Import Your Module Just Like in PyCharm

Once the path is set, you can use the exact import statement you’re used to in a Python code block:

from code.extract_feat.cluster_blast import fill_df_by_blast as fill_df

Quick Troubleshooting Tips

  • Double-check the path: Make sure the directory you added to sys.path is the parent folder of your code directory (not the code folder itself).
  • Verify the environment: Run py_config() to confirm reticulate is using the Python version/environment where your modules are installed.
  • Test in isolation: Try importing your module in a plain Python script first to make sure it works outside RMarkdown—this helps rule out issues with the module itself.

内容的提问来源于stack exchange,提问作者dabid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:47:38