如何从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
相关产品推荐
相关产品推荐

