{ "cells": [ { "cell_type": "markdown", "id": "a59722d6", "metadata": {}, "source": [ "Polyglot Netebooks 中,添加Jupyter内核,支持Python语言\n", "====================================================" ] }, { "cell_type": "markdown", "id": "23bcd178", "metadata": {}, "source": [ "使用魔术命令 \n", "\n", "无Conda环境:`#!connect jupyter --kernel-name pythonkernel --kernel-spec python3`\n", "有Conda环境:`#!connect jupyter --kernel-name pythonkernel --conda-env base --kernel-spec python3`\n", "\n", "实测有缺点:\n", "+ 不能重复执行:重复执行会报错\n", "+ 连接字符串必须是真实字符串:不能是变量,不灵活;明文\"不安全\",比如演示环境\n", "\n", "变通用法:在C#程序中,拼接好魔术命令`#!connect`,再发送给内核执行" ] }, { "cell_type": "code", "execution_count": null, "id": "b10341c4", "metadata": { "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "名为 Pythonkernel 的内核已存在。需要新内核时,请为--kernel-name参数使用不同的值, 本次执行不做任何更改!\r\n" ] } ], "source": [ "//魔术命令\n", "// #!connect jupyter --kernel-name pythonkernel --kernel-spec python3\n", "// #!connect jupyter --kernel-name pythonkernel --conda-env base --kernel-spec python3\n", "\n", "using Microsoft.DotNet.Interactive;\n", "using Microsoft.DotNet.Interactive.Commands;\n", "\n", "//优化方式\n", "{\n", " //内核名:\n", " string magicCommandKernelName = \"Pythonkernel\";\n", "\n", " //引入内核:可重复执行\n", " if(Microsoft.DotNet.Interactive.Kernel.Root.FindKernelByName(magicCommandKernelName) == null)\n", " {\n", " var connectKernelCode = $\"#!connect jupyter --kernel-name {magicCommandKernelName} --kernel-spec python3\";\n", " await Kernel.Root.SendAsync(new SubmitCode( connectKernelCode, \"csharp\"));\n", " }\n", " else\n", " {\n", " Console.WriteLine($\"名为 {magicCommandKernelName} 的内核已存在。需要新内核时,请为--kernel-name参数使用不同的值, 本次执行不做任何更改!\");\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "polyglot_notebook": { "kernelName": "pythonkernel" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello,python3!\n" ] } ], "source": [ "#!Pythonkernel\n", "# 写 python 代码\n", "print(\"hello,python3!\");" ] } ], "metadata": { "kernelspec": { "display_name": ".NET (C#)", "language": "C#", "name": ".net-csharp" }, "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelInfo": { "defaultKernelName": "csharp", "items": [ { "aliases": [], "languageName": "csharp", "name": "csharp" }, { "aliases": [], "languageName": "python", "name": "pythonkernel" }, { "aliases": [], "languageName": "python", "name": "Pythonkernel" } ] } } }, "nbformat": 4, "nbformat_minor": 5 }