导入使用 ipython 魔法的函数

Import functions that use ipython magic

在 ipython 个单元格中,您可以执行 shell 个命令,如下所示:

ipython:

print("asdf")
!echo asdf

但是,如果您尝试从文件中导入此代码,

asdf.py:

def asdf():
  print("asdf")
  !echo asdf

ipython:

from asdf import asdf

它会导致错误。

!echo asdf
^
SyntaxError: invalid syntax

用例是 google colab 中的重复大量脚本,利用 ffmpegwgetmount, e.t.c.
虽然您可以使用 os.systemsubprocess,但它们在提供实时标准输出方面不如交互式。

用例解决方案

如果您想重用其中包含 ipython 魔法函数的代码,只需使用 %run 而不是 import

ipython:

%run utils.ipynb

utils.ipynb:

def asdf():
  print("asdf")
  !echo asdf

上面的例子工作正常。
摘自 this answer


关于重用 ipython 代码

为什么原来的问题是某种 A-B 问题?原因是您 不应真正将 ipython 附加功能 拖到纯 python 执行中。

  • 如果您有一个 google colab notebook,其中包含有用的实用程序, 然后 !wget 它来自 public link 和 %run 它。
  • 如果要执行 python 脚本,请对 .py 个文件执行常规 import

当然,有一些方法可以将 .ipynb 文件导入 python 代码:Jupyter notebook 的 Notebook Loader, ipynb package, nbimporter package (但即使是 nbimporter 的作者也说 你不应该真的这样做那。只需使用 VSCode 或其他工具将您的笔记本转换为 .py

因此,如果您使用 ipython 研究环境和功能,坚持使用它。或者切换到具有适当模块、测试、e.t.c.

的纯 python 环境

此外,如果您正在努力 wget:

file_id = "1xE8Db1zvQ7v-z13CO2qc3F6wJmtr3YHu" # can be extracted from public link
file_out_name = "utils.ipynb"
!wget "https://docs.google.com/uc?export=download&id=""$file_id" -O "$file_out_name"

但是,关于调用cmd的问题,我看不到在python中用一行交互执行shell命令的方法。虽然 subprocess 可以做到这一点,但 it takes multiple lines to achieve