{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": "# 快捷键、魔法与进度:完整操作参考\n\n蓝色天空网 · mbsky.com\n\n保留命令/编辑键表、IPython魔法、动态图表和输出管理,标明版本与依赖。",
"id": "6e7f80079ac1"
},
{
"cell_type": "code",
"metadata": {},
"source": "print('蓝色天空网 · IPython魔法和输出实验')\nfrom IPython import get_ipython\nassert get_ipython() is not None",
"id": "644852c2e5d0",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%timeit -n 1 -r 1 sum(x*x for x in range(50))",
"id": "871adac4bea2",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%%time\nvalues=[x*x for x in range(100)]\nassert values[-1]==9801",
"id": "3905f72167d0",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nx=np.linspace(0,2*np.pi,30)\nfig,ax=plt.subplots()\nax.plot(x,np.sin(x))\nax.set_title('Blue Sky sine')\nfig.savefig('study.png')\nplt.show()\nplt.close(fig)",
"id": "687a7bab0089",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%who",
"id": "95e4eb4ab994",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%whos",
"id": "06e94c6dfaee",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%pwd",
"id": "bafffb6c35dc",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%ls",
"id": "5a48d002d6dc",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%%writefile hello.py\ndef greet(name):\n return '蓝色天空网:'+name\nmessage=greet('学习者')\nprint(message)",
"id": "42f98041bdac",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%run hello.py\nassert message=='蓝色天空网:学习者'",
"id": "c9795d54adc1",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%load hello.py",
"id": "63ba287ce284",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "import subprocess,sys\np=subprocess.run([sys.executable,'--version'],capture_output=True,text=True,timeout=10)\nassert p.returncode==0\nprint(p.stdout.strip())",
"id": "f41c69ebd270",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "shell_output = !{sys.executable} --version\nassert any('Python' in line for line in shell_output)\nprint(shell_output)",
"id": "18285e39791a",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%pip --version",
"id": "cc14e6c24c3a",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%history -n -l 5",
"id": "db3866a1134e",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%%html\n<h3>蓝色天空网 HTML输出</h3><p>这段来自本站自写代码。</p>",
"id": "ff777a65fdad",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "%%latex\n$$E=mc^2$$\n$$\\int_0^\\infty e^{-x^2}\\,dx=\\frac{\\sqrt{\\pi}}{2}$$",
"id": "ff8361a25612",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "from tqdm.notebook import tqdm\nfor i in tqdm(range(3),desc='学习进度'):\n pass\nfor i,item in enumerate(tqdm([2,4,6],desc='逐项')):\n assert item==(i+1)*2",
"id": "d98a740fd180",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "with tqdm(total=10,desc='手动进度') as bar:\n for chunk in range(2):\n bar.update(5)\n bar.set_postfix({'chunk':chunk})\n assert bar.n==10",
"id": "4fb16fb12e9e",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "import pandas as pd\ntqdm.pandas(disable=True)\ndf=pd.DataFrame({'value':[1,2,3]})\nsquared=df['value'].progress_apply(lambda value:value**2)\nassert squared.tolist()==[1,4,9]\ndisplay(squared)",
"id": "4add6a6bc554",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "from IPython.display import display,clear_output\nfor i in range(3):\n clear_output(wait=True)\n print('进度:',i+1,'/3')\nassert i==2",
"id": "8a63cf5a3cab",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "rng=np.random.default_rng(7)\nlosses=[]\nfor step in range(6):\n losses.append(1/(step+1)+float(rng.uniform(0,.01)))\n if (step+1)%3==0:\n clear_output(wait=True)\n fig,ax=plt.subplots()\n ax.plot(losses)\n ax.set_title('Blue Sky simulated loss')\n plt.show()\n plt.close(fig)\nassert len(losses)==6 and not plt.get_fignums()\nprint('模拟结束,不能当真实模型训练结果')",
"id": "0d420cf0b428",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "import numpy as np\nhelp(np.array)\nget_ipython().run_line_magic('pinfo','np.array')\nget_ipython().run_line_magic('pinfo2','np.array')",
"id": "bb2a89c67049",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "from IPython.display import display\nfirst=pd.DataFrame({'A':[1,2,3]})\nsecond=pd.DataFrame({'X':[7,8,9]})\ndisplay(first)\ndisplay(second)",
"id": "7dc9f8bbacbd",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "from IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity='all'\n2+2\n3+3\n'blue sky'",
"id": "6d7a956b8130",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "InteractiveShell.ast_node_interactivity='last_expr'\nplt.plot([1,2],[2,4]);\nplt.close('all')",
"id": "954652ca30c8",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "(result := np.array([1,2,3])*2)\nassert result.tolist()==[2,4,6]\nresult",
"id": "cd94ee1f682d",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "get_ipython().run_cell('2+3',store_history=True)\nassert get_ipython().user_ns['_']==5\nprint('上次表达式输出:',get_ipython().user_ns['_'])",
"id": "4ecba1348281",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "from IPython.display import Markdown,HTML,Image,SVG,Audio,Video\ndisplay(Markdown('## 蓝色天空网\\n\\n**逐步学习**'))\ndisplay(HTML('<span>mbsky.com 自有富文本</span>'))\ndisplay(Image(filename='study.png'))\ndisplay(SVG('<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"180\" height=\"40\"><text x=\"5\" y=\"25\">Blue Sky</text></svg>'))\n# Audio/Video类可承载适当资源;这里不拉取外部文件、不自动播放。",
"id": "bac9fa93ec46",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "import time\nfrom contextlib import contextmanager\n@contextmanager\ndef timer(label):\n start=time.perf_counter()\n try:\n yield\n finally:\n elapsed=time.perf_counter()-start\n assert elapsed>=0\n print(label,round(elapsed,6),'s')\nwith timer('自有数据处理'):\n total=sum(x*x for x in range(1000))\nassert total==332833500",
"id": "79c7d04e6b2f",
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": "## 保留的交互条件\n\n%debug需要交互式调试,Notebook7的widget后端需相应依赖。%matplotlib notebook、Classic扩展及快捷键不按当前kernel执行就自动判兼容。\n\n`%reset -f`会清空下文可用变量,下一格专门观察它。",
"id": "c0cdef9d4028"
},
{
"cell_type": "code",
"metadata": {},
"source": "%reset -f",
"id": "dfd583c35259",
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {},
"source": "assert 'result' not in globals() and 'values' not in globals()\nprint('清除变量后重新开始,磁盘文件仍存在')\nfrom pathlib import Path\nassert Path('hello.py').is_file()",
"id": "27a39d5d890f",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (Blue Sky learning)",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
本例需在 本项目Python3.12 / Notebook7.6.4 / ipykernel7.4.0 / nbclient0.11.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本项目Python3.12 / Notebook7.6.4 / ipykernel7.4.0 / nbclient0.11.0
入口文件:projects/notebook-lab/notebooks/keyboard-shortcuts.ipynb
预期结果与验证条件观察提示
- 32个Code单元格含全部魔法分支;Python/PNG/SVG/HTML/LaTeX/Markdown/widget MIME输出;写文件及run成功;复位后变量清空但hello.py保留
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联8章) · 含当前章节或实例 · mbskycom202611a518.zip