一、 %run? ?执行文件
1. 执行同文件夹下的 .py文件
%run hello.py
2.执行不同文件夹、不同文件夹多个.py文件
# 方法1 import函数名
import Mymodule.FirstML
Mymodule.FirstML.predict(1)
# 方法2 from import函数名
from Mymodule import FirstML
FirstML.predict(2)
二、%load? 读取文件内容
1. .py文件的加载(加载单一模板)
# 运行%LOAD XXX.py后出现以下代码
# %load hello.py
def hello(name):
print("hello", name, "!")
hello("jupyter")
# %load magic/Hello.py
def Hello(name):
print("hello", name, "!")
Hello("jupyter")
三、%timeit? 多次测试代码执行时间,求平均值
1. %timeit 语法
%timeit L = [i**2 for i in range(1000)]
194 μs ± 7.4 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.可用于推测算法时间复杂度
%%timeit # 使用时间高于上述
L = []
for n in range(1000):
L.append(n ** 2)
207 μs ± 3.34 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
3.%time 语法
%time L = [i**2 for i in range(1000)]
# CPU times: user 193 μs, sys: 0 ns, total: 193 μs
# Wall time: 195 μs 单句运算时长
%%time
L = []
for n in range(1000):
L.append(n**2)
# CPU times: user 472 μs, sys: 6 μs, total: 478 μs
# Wall time: 482 μs 整体运算时长
import random
L = [random.random() for i in range(10000)]
%timeit L.sort()
# 33.4 μs ± 912 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# timeit 计算平均运行时长
L = [random.random() for i in range(10000)]
%timeit L.sort()
# 32.7 μs ± 464 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit L.sort()
# 33.9 μs ± 295 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
四、 %lsmagic 查看其他魔法命令api
1. 查看api
%lsmagic
"""Available line magics:
%alias %alias_magic %autoawait %autocall %automagic %autosave %bookmark %cat %cd %clear %colors %conda %config %connect_info %cp %debug %dhist %dirs %doctest_mode %ed %edit %env %gui %hist %history %killbgscripts %ldir %less %lf %lk %ll %load %load_ext %loadpy %logoff %logon %logstart %logstate %logstop %ls %lsmagic %lx %macro %magic %man %matplotlib %mkdir %more %mv %notebook %page %pastebin %pdb %pdef %pdoc %pfile %pinfo %pinfo2 %pip %popd %pprint %precision %prun %psearch %psource %pushd %pwd %pycat %pylab %qtconsole %quickref %recall %rehashx %reload_ext %rep %rerun %reset %reset_selective %rm %rmdir %run %save %sc %set_env %store %sx %system %tb %time %timeit %unalias %unload_ext %who %who_ls %whos %xdel %xmode
Available cell magics:
%%! %%HTML %%SVG %%bash %%capture %%debug %%file %%html %%javascript %%js %%latex %%markdown %%perl %%prun %%pypy %%python %%python2 %%python3 %%ruby %%script %%sh %%svg %%sx %%system %%time %%timeit %%writefile
Automagic is ON, % prefix IS NOT needed for line magics."""
|