[英]Import functions that use ipython magic
In ipython cells you can execute shell commands as follows:在 ipython 单元中,您可以执行 shell 命令,如下所示:
ipython:蟒蛇:
print("asdf")
!echo asdf
However, if you try to import this code from file,但是,如果您尝试从文件中导入此代码,
asdf.py: asdf.py:
def asdf():
print("asdf")
!echo asdf
ipython:蟒蛇:
from asdf import asdf
it results in an error.它会导致错误。
!echo asdf
^
SyntaxError: invalid syntax
The use case for that is repetative massive scripts in google colab utilizing ffmpeg, wget, mount, etc.用例是 google colab 中使用 ffmpeg、wget、mount、etc 的重复大量脚本。
While you can use os.system or subprocess, they are not as interactive in providing real-time stdout.虽然您可以使用 os.system 或 subprocess,但它们在提供实时标准输出方面没有那么交互。
If you want to reuse code that has ipython magic functions in it, simply use %run
instead of the import
.如果您想重用其中包含 ipython 魔术函数的代码,只需使用
%run
而不是import
。
ipython:蟒蛇:
%run utils.ipynb
utils.ipynb: utils.ipynb:
def asdf():
print("asdf")
!echo asdf
Example above works fine.上面的例子工作正常。
Taken from this answer .取自这个答案。
Why the original question was an A-B problem of some kind?为什么最初的问题是某种A-B 问题? The reason is that you should not really drag ipython additional functionality to the pure python execution.
原因是您不应该真正将 ipython 附加功能拖到纯 python 执行中。
!wget
it from the public link and %run
it.!wget
从公共链接中获取它并%run
它。import
on .py
files.import
.py
文件。 Sure, there are ways to import .ipynb
files to python code: Jupyter notebook's Notebook Loader , ipynb package , nbimporter package (but even the nbimporter's author says you should not really do that . Just convert your notebook to .py
using VSCode or another tool). Sure, there are ways to import
.ipynb
files to python code: Jupyter notebook's Notebook Loader , ipynb package , nbimporter package (but even the nbimporter's author says you should not really do that . Just convert your notebook to .py
using VSCode or another tool )。
So, if you use ipython research environment and features, just stick with it .所以,如果你使用 ipython 的研究环境和功能,那就坚持下去吧。 Or switch to pure python environment with proper modules, testing, etc.
或者切换到具有适当模块、测试、etc 的纯 python 环境。
Also, if you're struggling with doing wget
:另外,如果您正在努力做
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"
However, on the problem of calling cmd, I see no way of executing shell commands interactively in python with one line.但是,关于调用 cmd 的问题,我看不到在 python 中用一行交互式执行 shell 命令的方法。 While
subprocess
can do that, it takes multiple lines to achieve .虽然
subprocess
可以做到这一点, 但它需要多行才能实现.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.