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

如何从Python脚本运行IPython单元格魔法命令(%%魔法)

在Python脚本中执行Jupyter单元格魔法命令(如%%sh)

方法一:借助IPython API调用单元格魔法

单元格魔法是IPython内核提供的功能,若能确保脚本在IPython环境(比如用ipython命令执行脚本)运行,可直接调用IPython的run_cell_magic方法:

from IPython import get_ipython

task_name = "test_task"

# 获取当前IPython shell实例
ipython = get_ipython()

# 执行%%sh单元格魔法
ipython.run_cell_magic(
    "sh",
    "-s $task_name",  # %%sh后面的参数部分
    """#!/bin/bash
task_name=$1
echo This is a script running task [$task_name] that is executed from python
echo Many more bash commands here...................
"""
)
  • 第一个参数是魔法命令名称(如sh),第二个参数是魔法的选项与参数,第三个参数是单元格内的脚本内容。
  • 注意:普通python命令启动的环境无法使用该方法,必须在IPython/Jupyter的内核环境中运行。

方法二:用Python标准库替代(无需IPython依赖)

如果要在普通Python脚本中实现和%%sh相同的功能,直接用subprocess模块调用bash即可,无需依赖IPython:

import subprocess

task_name = "test_task"
bash_content = """#!/bin/bash
task_name=$1
echo This is a script running task [$task_name] that is executed from python
echo Many more bash commands here...................
"""

# 执行bash脚本
result = subprocess.run(
    ["bash", "-s", task_name],
    input=bash_content,
    capture_output=True,
    text=True
)

# 打印输出结果
print(result.stdout)
if result.stderr:
    print("错误信息:", result.stderr)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:50:42