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

如何在Databricks中执行从GitHub拉取并保存为变量的Python脚本?

在Databricks中执行从GitHub拉取的Python脚本(变量形式)及优化方案

一、执行存储在变量中的Python脚本

方法1:使用exec()直接执行字符串代码

拿到脚本内容字符串后,直接通过exec()执行,即可调用脚本内的函数:

# 先通过shell克隆仓库(注意%sh魔法命令需单独成块)
%sh git clone https://github.com/some-repo.git

import subprocess as sp
# 获取脚本内容
some_file = sp.getoutput('cat ./some-repo/folder/file/some-script.py')

# 执行脚本内容
exec(some_file)
# 调用脚本中的函数
hell()

注意:确保拉取的脚本语法正确(比如示例中的def hell()需补全冒号def hell():),否则exec()会触发语法错误。

方法2:写入临时文件后导入为模块(更安全)

针对复杂脚本,推荐将内容写入临时文件后以模块形式导入,避免exec()的安全风险:

import tempfile
import os
import importlib.util
import subprocess as sp

%sh git clone https://github.com/some-repo.git
some_file = sp.getoutput('cat ./some-repo/folder/file/some-script.py')

# 创建临时Python文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
    f.write(some_file)
    temp_script_path = f.name

# 导入临时模块
spec = importlib.util.spec_from_file_location('temp_script', temp_script_path)
temp_script = importlib.util.module_from_spec(spec)
spec.loader.exec_module(temp_script)

# 调用函数
temp_script.hell()

# 清理临时文件
os.unlink(temp_script_path)

二、更优的实现方式

方案1:使用Databricks Repos(官方推荐)

Databricks Repos支持直接关联GitHub仓库,实现代码同步、版本控制,无需手动克隆:

  1. 在Databricks工作区创建Repos,关联你的GitHub仓库;
  2. 仓库内容会同步到/Repos/[用户名]/[仓库名]路径;
  3. 直接导入仓库中的脚本:
import sys
# 添加脚本所在目录到Python路径
sys.path.append('/Repos/your-username/some-repo/folder/file')
# 导入脚本函数
from some_script import hell

hell()

方案2:克隆后直接导入模块

如果坚持用shell克隆,可将克隆路径添加到Python路径,直接导入脚本:

%sh git clone https://github.com/some-repo.git /tmp/some-repo

import sys
sys.path.append('/tmp/some-repo/folder/file')
from some_script import hell

hell()

方案3:挂载GitHub到DBFS(适合批量访问)

对于公共或带Token的私有仓库,可挂载到DBFS实现持久化访问:

# 挂载私有仓库(公共仓库可省略extra_configs)
dbutils.fs.mount(
    source = "https://github.com/some-repo.git",
    mount_point = "/mnt/github/some-repo",
    extra_configs = {"github.com": "your-personal-access-token"}
)

# 读取并执行脚本
with open('/dbfs/mnt/github/some-repo/folder/file/some-script.py', 'r') as f:
    script_content = f.read()
exec(script_content)
hell()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:41:42