繁体   English   中英

如何从脚本运行 IPython CELL magic (%% magic)

[英]How to run an IPython CELL magic from a script (%% magic)

Jupyter magic 命令(以单个%开头,例如%timeit )可以使用How to run an IPython magic from a script (or timing a Python script)中的答案在脚本中运行

但是,我找不到关于如何运行单元魔术命令的答案,例如在 Jupyter 中我们可以这样做:

%%sh -s $task_name
#!/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...................

如何编写才能从 python 脚本执行?

可以使用没有很好记录的run_cell_magic来完成

run_cell_magic(magic_name, line, cell) 执行给定的单元格魔法。 参数:
magic_name: str 所需魔法函数的名称,不带“%”前缀。 line: str 第一输入行的其余部分作为单个字符串。 cell: str 单元格的主体(可能是多行)字符串。

因此,为 python 脚本转换的代码是:

from IPython import get_ipython
task_name = 'foobar'
get_ipython().run_cell_magic('sh', '-s $task_name', '''
#!/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...................
''')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM