From bb531aa603c2414d06a7daf99a1df15c9fad39a6 Mon Sep 17 00:00:00 2001 From: bicijinlian Date: Sat, 19 Apr 2025 16:27:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B4=E5=90=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Docs/多语言笔记-练习.ipynb | 189 +++++++++ ...言笔记.1.2.PocketView渲染html.ipynb} | 0 Docs/多语言笔记.1.2.显示格式化.md | 336 --------------- ...笔记.2.1.操作数据库-SQL内核.ipynb | 350 +++++++++++++++- .../多语言笔记.2.1.连接数据库.ipynb | 394 ------------------ Docs/多语言笔记.9.2.使用python.ipynb | 140 ------- ...语言笔记.9.2.使用python内核.ipynb | 252 +++++++++++ Docs/练习-添加Jupyter内核.ipynb | 131 ------ 8 files changed, 770 insertions(+), 1022 deletions(-) create mode 100644 Docs/多语言笔记-练习.ipynb rename Docs/{练习-Html-PocketView.ipynb => 多语言笔记.1.2.PocketView渲染html.ipynb} (100%) delete mode 100644 Docs/多语言笔记.1.2.显示格式化.md delete mode 100644 Docs/多语言笔记.2.1.连接数据库.ipynb delete mode 100644 Docs/多语言笔记.9.2.使用python.ipynb create mode 100644 Docs/多语言笔记.9.2.使用python内核.ipynb delete mode 100644 Docs/练习-添加Jupyter内核.ipynb diff --git a/Docs/多语言笔记-练习.ipynb b/Docs/多语言笔记-练习.ipynb new file mode 100644 index 0000000..8ce917f --- /dev/null +++ b/Docs/多语言笔记-练习.ipynb @@ -0,0 +1,189 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
Installed Packages
  • Microsoft.Identity.Client, 4.66.2
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
Installed Packages
  • Microsoft.Extensions.Configuration, 9.0.4
  • Microsoft.Extensions.Configuration.Binder, 9.0.4
  • Microsoft.Extensions.Configuration.CommandLine, 9.0.4
  • Microsoft.Extensions.Configuration.EnvironmentVariables, 9.0.4
  • Microsoft.Extensions.Configuration.ini, 9.0.4
  • Microsoft.Extensions.Configuration.json, 9.0.4
  • Microsoft.Extensions.Configuration.KeyPerFile, 9.0.4
  • Microsoft.Extensions.Configuration.UserSecrets, 9.0.4
  • Microsoft.Extensions.Configuration.xml, 9.0.4
  • Microsoft.Extensions.DependencyInjection, 9.0.4
  • Microsoft.Extensions.Logging, 9.0.4
  • Microsoft.Extensions.Logging.Configuration, 9.0.4
  • Microsoft.Extensions.Logging.Console, 9.0.4
  • Microsoft.Extensions.Logging.Debug, 9.0.4
  • Microsoft.Extensions.Logging.EventSource, 9.0.4
  • Microsoft.Extensions.Options, 9.0.4
  • Microsoft.Extensions.Options.ConfigurationExtensions, 9.0.4
  • Microsoft.Extensions.Options.DataAnnotations, 9.0.4
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "//全局初始化\n", + "#!import \"./Base.ipynb\"\n", + "\n", + "#r \"nuget:Microsoft.Identity.Client,4.66.2\"\n", + "using Microsoft.DotNet.Interactive;\n", + "using Microsoft.DotNet.Interactive.Commands;" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a118a9b7", + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [ + { + "data": { + "text/html": [ + "
Installed Packages
  • Microsoft.DotNet.Interactive.SqlServer, 1.0.0-beta.25177.1
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "Loading extension script from `C:\\Users\\ruyu\\.nuget\\packages\\microsoft.dotnet.interactive.sqlserver\\1.0.0-beta.25177.1\\interactive-extensions\\dotnet\\extension.dib`" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
Query Microsoft SQL Server databases.\r\n", + "

This extension adds support for connecting to Microsoft SQL Server databases using the #!connect mssql magic command. For more information, run a cell using the #!sql magic command.

\r\n", + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/markdown": [ + "Scaffolding a `DbContext` and initializing an instance of it called `SqlServerKernelWithEF` in the C# kernel." + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
Installed Packages
  • Humanizer, 2.14.1
  • humanizer.core, 2.14.1
  • microsoft.data.sqlclient, 5.2.2
  • Microsoft.EntityFrameworkCore.Design, 9.0.0
  • microsoft.entityframeworkcore.sqlserver, 9.0.0
  • Microsoft.Identity.Client, 4.66.2
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "Kernel added: #!sql-SqlServerKernelWithEF" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "//引入 SqlServer 的 NuGet 包\n", + "#r \"nuget:Microsoft.DotNet.Interactive.SqlServer,*-*\"\n", + "//#r \"nuget:Microsoft.Identity.Client,4.66.2\"\n", + "\n", + "//优化用法\n", + "{\n", + " //内核名:魔法命令中的内核名,执行后会自动加 sql- 前缀,做为内核名被使用\n", + " string magicCommandKernelName = \"SqlServerKernelWithEF\";\n", + " string completeKernelName = \"sql-\" + magicCommandKernelName;\n", + "\n", + " //引入内核:可重复执行\n", + " if(Microsoft.DotNet.Interactive.Kernel.Root.FindKernelByName(completeKernelName) == null)\n", + " {\n", + " var connectKernelCode = $\"#!connect mssql --kernel-name {magicCommandKernelName} \\\"Server=.\\\\SQL2019;Database=study;User Id=sa;Password=gly-bicijinlian;TrustServerCertificate=true;\\\" --create-dbcontext\";\n", + " await Kernel.Root.SendAsync(new SubmitCode( connectKernelCode, \"csharp\"));\n", + " }\n", + " else\n", + " {\n", + " Console.WriteLine($\"名为 {completeKernelName} 的内核已存在。需要新内核时,请为--kernel-name参数使用不同的值, 本次执行不做任何更改!\");\n", + " }\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [ + { + "ename": "Error", + "evalue": "(6,1): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEFContext”(是否缺少 using 指令或程序集引用?)\r\n(7,19): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEF”(是否缺少 using 指令或程序集引用?)\r\n(6,38): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEFContext”(是否缺少 using 指令或程序集引用?)", + "output_type": "error", + "traceback": [ + "(6,1): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEFContext”(是否缺少 using 指令或程序集引用?)\r\n", + "(7,19): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEF”(是否缺少 using 指令或程序集引用?)\r\n", + "(6,38): error CS0246: 未能找到类型或命名空间名“SqlServerKernelWithEFContext”(是否缺少 using 指令或程序集引用?)" + ] + } + ], + "source": [ + "//连接建立后,执行环境中就有了相关的类:DBContext等\n", + "using Microsoft.EntityFrameworkCore;\n", + "using Microsoft.EntityFrameworkCore.SqlServer;\n", + "using Microsoft.EntityFrameworkCore.Scaffolding;\n", + "\n", + "SqlServerKernelWithEFContext a = new SqlServerKernelWithEFContext();\n", + "var context = new SqlServerKernelWithEF();\n", + "var t = context.Students.ToList();\n", + "display(t);\n", + "\n", + "FormattableString fs = $\"select * from Student;\";\n", + "var c = context.Database.ExecuteSql(fs);\n", + "display(c);" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".NET (C#)", + "language": "C#", + "name": ".net-csharp" + }, + "polyglot_notebook": { + "kernelInfo": { + "defaultKernelName": "csharp", + "items": [ + { + "aliases": [], + "languageName": "csharp", + "name": "csharp" + } + ] + } + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/Docs/练习-Html-PocketView.ipynb b/Docs/多语言笔记.1.2.PocketView渲染html.ipynb similarity index 100% rename from Docs/练习-Html-PocketView.ipynb rename to Docs/多语言笔记.1.2.PocketView渲染html.ipynb diff --git a/Docs/多语言笔记.1.2.显示格式化.md b/Docs/多语言笔记.1.2.显示格式化.md deleted file mode 100644 index d4335e9..0000000 --- a/Docs/多语言笔记.1.2.显示格式化.md +++ /dev/null @@ -1,336 +0,0 @@ -单元格输出的格式化 -================ -## 格式化输出 -基于 .NET Interactive 的工具(包括 Polyglot 笔记本、Jupyter 和其他工具)的输出是通过 .NET Interactive 格式化器生成的,这是一组位于 Microsoft.DotNet.Interactive.Formatting 命名空间下的 API。这些 API 可以作为一个 NuGet 包独立于笔记本使用。 -格式化器创建对象的字符串表示,这些字符串表示可以从纯文本到 HTML,再到像 JSON 和 CSV 这样的机器可读格式。 - -以下是一些你可以在笔记本中编写的代码示例,这些代码会导致对象被格式化以供显示: -- C# 单元格末尾的返回语句或尾随表达式 -- F# 单元格末尾的尾随表达式 -- 调用 Display 和 ToDisplayString 扩展方法,这些方法对 C# 和 F# 中的所有对象都可用 -- 在 PowerShell 单元格中调用 Out-Display - -格式化器还用于在多语言笔记本变量视图中格式化.NET对象的输出显示。其他语言的值格式化并不依赖于.NET。 -> `格式化` 指的是创建对象字符串表示的过程。此过程由.NET Interactive内核通过此处所述的API实现。当格式化后的字符串在 VS Code 或 JupyterLab 中的笔记本上显示时,这一过程被称为`渲染` -## MIME类型 与 Display显示 -对于任何一个给定的对象,可以有多种不同的字符串表示方式。这些不同的表示方式都有对应的MIME类型,这些类型由简短的字符串标识,例如`text/html`或`application/json`。MIME类型可以用来通过Display扩展方法请求特定格式的对象显示,这个方法可以用于任何对象。 - -例如,我们可以调用rect.Display()来显示分配给变量rect的Rectangle对象 -```csharp -//注意:System.Drawing不能跨平台,只在Windows系统中使用。 -//不知道为啥:官方要选个不跨平台的示例 -using System.Drawing; -var ract = new Rectangle -{ - Height = 50, - Width = 100, -}; - -//默认为 text/html,下面两种方式的效果是一样的 -ract.Display(); -ract.Display("text/html"); -``` -注意,Polyglot 笔记本中默认的 MIME 类型是 text/html。这可能会因 .NET 类型的不同而有所变化,但在上述示例中,矩形类型尚未应用任何自定义设置。(将在下面展示更多关于如何进行自定义设置的内容。) -> 注意:对于 C# 或 F# 中单元格的返回值,只能使用默认 MIME 类型的格式化程序。 -在使用Display时,可以指定不同于默认的MIME类型。只需将所需的MIME类型作为参数传递即可,例如:rect.Display("text/plain") -```csharp -ract.Display("text/plain"); -``` -另一种常见的MIME类型是application/json。在Polyglot笔记本中使用此MIME类型时,对象使用System.Text.Json进行格式化。 - -执行下面的单元格,会以Json格式输出。JSON输出中的代码颜色由 VS Code 笔记本渲染器针对`application/json`类型提供。 -```csharp -ract.Display("application/json"); -``` -## 自定义格式化 -.NET Interactive的格式化API是高度可配置的。 - -可以使用`Microsoft.DotNet.Interactive.Formatting`中的代码,调整格式化行为的方式。 -### 限制输出数量 -在格式化序列时,例如数组或实现IEnumerable的对象,.NET Interactive的格式化器会将它们展开,以便你可以看到其中的值。 - -如果执行结果集太多,默认情况下只会输出前面很少项,剩余的数据以 `...More` 代替。 -```csharp -var names = new string[] -{ - "吕宇宁", "韦子异", "姚宇宁", "傅子异", "朱子韬", "林杰宏", "胡璐", "周璐", "田秀英", "姜詩涵", "蔡秀英", "张睿", "金嘉伦", "萧致远", "赵致远", "蒋宇宁", "顾震南", "余安琪", "熊岚", "卢子韬", - "孔杰宏", "周子韬", "黄睿", "史璐", "赵震南", "杜安琪", "赵致远", "石詩涵", "龚杰宏", "丁安琪", "黄杰宏", "傅睿", "戴嘉伦", "郝杰宏", "傅晓明", "孟嘉伦", "段睿", "戴致远", "石安琪", "汪詩涵", - "贾云熙", "邱子韬", "吴杰宏", "贾岚", "曾震南", "许云熙", "吴宇宁", "唐岚", "常嘉伦", "曾岚", "袁嘉伦", "黄晓明", "韦致远", "莫安琪", "丁子韬", "雷云熙", "许秀英", "朱宇宁", "黎詩涵", "贾晓明", - "孔詩涵", "秦宇宁", "方子韬", "邵秀英", "冯宇宁", "何晓明", "方嘉伦", "熊秀英", "沈云熙", "顾秀英", "许致远", "胡宇宁", "陶子异", "叶安琪", "邱震南", "刘子异", "周宇宁", "黄云熙", "龚杰宏", "杜秀英", - "向子异", "马睿", "黄安琪", "于安琪", "金嘉伦", "龚璐", "杨致远", "戴嘉伦", "钟詩涵", "阎詩涵", "雷安琪", "宋杰宏", "田致远", "冯致远", "雷杰宏", "雷子异", "叶璐", "王子异", "冯子韬", "史宇宁" -}; - -var students = Enumerable.Range(1,50).Select(s => new {Id = s, Age = Random.Shared.Next(1,100), Name = names[s]}); -students.Display(); -``` -Formatter.ListExpansionLimit 更改为自定义值 -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.ListExpansionLimit = 5; -students.Display(); -``` -上面的示例中,通过设置Formatter.ListExpansionLimit = 5,然后显示相同的列表对象,.NET Interactive现在仅显示前五项,后面跟着 ...(more)。 - -也可以通过设置`Formatter.ListExpansionLimit`来限制特定类型的输出。需要注意的是,这里的类型T必须与列表中的项完全匹配。 - -以下是一个使用int类型的示例: -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.ListExpansionLimit = 3; -Enumerable.Range(1, 10).Display(); - -``` -注意:有些以 ...(more)结尾,有些以(数字 more)结尾。 - -这是因为:List、List、数组等,列举前就知道元素确切的数量,以 `(数字 more)`结尾;而像 IEnumerable(Enumerable.Range 返回类型是IEnumerable)之类的,因此在枚举整个序列之前,无法知道元素确切的数量;在这种情况下,.NET交互式格式化器在达到配置的ListExpansionLimit时会停止,并不会继续计数剩余的序列, 以 `...(more)` 结尾 -### 限制对象循环引用次数 -有些对象存在引用循环。虽然.NET Interactive格式化器会遍历对象图,但它为了避免输出过大和无限递归,只会递归到特定深度。 - -以下是一个C#代码示例,它定义了一个简单的Node类,创建了一个引用循环,并使用C#脚本的尾随表达式(相当于返回语句)对其进行格式化: -```csharp -public class Node -{ - public Node Next { get; set; } -} - -Node node1 = new(); -Node node2 = new(); - -node1.Next = node2; -node2.Next = node1; - -node1 -``` -这表明格式化器在格式化到深度6后停止了递归。这个深度可以通过Formatter.RecursionLimit方法进行更改: -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.RecursionLimit = 2; -node1 -``` -### 首选 MIME 类型 -前面提到,Polyglot 笔记本中用于格式化的默认 MIME 类型是 text/html。当使用 Display() 方法时,如果没有向 mimeType 参数传递值,或者在 C# 或 F# 中使用 return 语句或尾随表达式时,就会应用这个默认设置。这个默认设置可以全局更改,也可以针对特定类型更改。 - -以下示例将 Rectangle 的默认值更改为 text/plain。 -```csharp -public class Student -{ - public int Id {get;set;} - public string Name {get;set;} - public int Age {get;set;} -} - -Microsoft.DotNet.Interactive.Formatting.Formatter.SetPreferredMimeTypesFor(typeof(Student), "text/plain"); - -new Student -{ - Id = 1, - Name = "张三", - Age = 55 -} -``` -该方法可用于设置多个首选MIME类型。第二个参数是params参数,它允许您传递多个值。 -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.SetPreferredMimeTypesFor -( - typeof(Student), - "text/plain", - "application/json" -); - -new Student -{ - Id = 1, - Name = "张三", - Age = 55 -} -``` -注册多个MIME时,可以切换输出格式: -单击 执行结果单元格的最左侧`...`, 选择 `更改演示文稿`后,在VS Code最上访,会弹出选择窗口,选择注册项中的一个,就可以重新以选中项的格式重新显示结果。 -### 替换默认的格式化类型 -默认格式化器通常通过打印列表和属性来显示对象的值。输出主要是文本形式。如果你希望以不同的方式显示某种类型的内容,无论是不同的文本输出、图像还是图表,你可以通过为特定类型注册自定义格式化器来实现。这些类型可以是你自己定义的,也可以是其他.NET库中定义的。 - -一个常见的使用自定义格式化器的场景是渲染图表。一些NuGet包,如Plotly.NET,提供了.NET Interactive扩展,利用此功能以交互式的HTML和JavaScript为基础生成输出。 - -注册自定义格式化器最简单的方法是使用Formatter.Register方法,它有几个不同的重载版本。在笔记本中使用最友好、最方便的一个接受两个参数: -+ 委托:它接受你要注册的类型的对象,并返回一个字符串。在这里,你可以指定所需的字符串转换; -+ MIME类型:只有当使用此MIME类型时,才会调用你的自定义格式化器 - -下面的示例将 Rectangles 类的实例格式化为SVG矩形。 -```csharp -public class Rectangle -{ - public int Width {get;set;} - public int Height {get;set;} -} - -Microsoft.DotNet.Interactive.Formatting.Formatter.Register -( - formatter: //格式化方法:把类型对象,转化为输出字符串 - rect => $""" - - - - """, - mimeType: //输出媒体类型 - "text/html" -); -``` -```csharp -/* -运行此代码后,Rectangle对象将显示为图形矩形,而不是属性值列表。 -(以下示例使用C#脚本尾随表达式语法,该语法通常配置为在笔记本中使用text/html MIME类型。) -*/ -new Rectangle(){Width = 100, Height = 50} -``` -特别指出:当在列表中遇到自定义类型或作为对象属性时,仍将调用自定义格式化程序 -```csharp -new[] -{ - new Rectangle(){Width = 200, Height = 50}, - new Rectangle(){Width = 200, Height = 100} -} -``` -```csharp -//具有 Rectangle 类型属性的匿名对象 -new { - Name = "Example", - Rectangle = new Rectangle(){ Width=100, Height=50 } -} -``` -### 打开泛型类型 -可以通过使用开放泛型类型定义作为键来指定格式化程序。以下代码将为所有类型的 T 的 List 变体注册一个格式化程序,并打印每个元素及其哈希代码。(请注意,必须强制转换对象才能迭代其项。 -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.Register -( - type: typeof(List<>), - formatter: (list, writer) => - { - foreach (var obj in (IEnumerable)list) - { - writer.WriteLine($"{obj} ({obj.GetHashCode()})"); - } - }, "text/html" -); -``` -```csharp -//运行上述代码后,以下内容将不再仅打印列表中的值 ["one","two","three"] -//变为:one (254814599) two (656421459) three (-1117028319) -var list = new List { "one", "two", "three" }; -list -``` -### TypeFormatterSource 特性类 -Formatter.Register方式外,另一种注册自定义格式化程序的方式是:使用 TypeFormatterSourceAttribute 修饰类型。如果您想直接在笔记本中重新定义格式化程序设置,这不是最方便的方法。但是,如果您正在编写 .NET Interactive 扩展,或者编写包含某些类型的自定义格式的库或应用程序,则建议使用此方法。其中一个原因是基于属性的方法更简单。另一个原因是,调用 Formatter.ResetToDefault() 时不会清除基于属性的格式化程序自定义,而使用 Formatter.Register 配置的格式化程序会被清除。您可以将基于属性的注册方法视为为类型设置默认格式的一种方式。 - -基于属性的格式化程序注册有两种方法:一种用于项目引用时,另一种用于项目不引用 Microsoft.DotNet.Interactive.Formatting 时 - -如果您已经引用了 Microsoft.DotNet.Interactive.Formatting ,例如,因为您正在编写 .NET Interactive 扩展,那么您可以使用 中定义的 TypeFormatterSourceAttribute 来修饰需要自定义格式的类型 Microsoft.DotNet.Interactive.Formatting 。下面是一个示例: -```csharp -[Microsoft.DotNet.Interactive.Formatting.TypeFormatterSource(typeof(MyFormatterSource))] -public class MyTypeWithCustomFormatting -{ - -} - -//带Mime类型 -[Microsoft.DotNet.Interactive.Formatting.TypeFormatterSource -( - typeof(MyFormatterSource), PreferredMimeTypes = new[] { "text/html", "application/json" } -)] -public class MyTypeWithCustomFormatting2 -{ -} - -//TypeFormatterSourceAttribute 指定的格式化程序源必须实现 ITypeFormatterSource,并且必须具有空构造函数。它不需要是 public 类型 -public class MyFormatterSource : Microsoft.DotNet.Interactive.Formatting.ITypeFormatterSource -{ - public IEnumerable CreateTypeFormatters() - { - return new Microsoft.DotNet.Interactive.Formatting.ITypeFormatter[] - { - new Microsoft.DotNet.Interactive.Formatting.PlainTextFormatter(context => - $"Hello from {nameof(MyFormatterSource)} using MIME type text/plain"), - new Microsoft.DotNet.Interactive.Formatting.HtmlFormatter(context => - $"Hello from {nameof(MyFormatterSource)} using MIME type text/html") - }; - } -} -``` -一个完整例子: -```csharp -[AttributeUsage(AttributeTargets.Class)] -internal class TypeFormatterSourceAttribute : Attribute -{ - public TypeFormatterSourceAttribute(Type formatterSourceType) - { - FormatterSourceType = formatterSourceType; - } - - public Type FormatterSourceType { get; } - - public string[] PreferredMimeTypes { get; set; } -} - -internal class MyConventionBasedFormatterSource -{ - public IEnumerable CreateTypeFormatters() - { - yield return new MyConventionBasedFormatter { MimeType = "text/html" }; - } -} - -internal class MyConventionBasedFormatter -{ - public string MimeType { get; set; } - - public bool Format(object instance, System.IO.TextWriter writer) - { - if (instance is MyTypeWithCustomFormatting myObj) - { - writer.Write($"
Custom formattering for {myObj}
"); - return true; - } - else - { - return false; - } - } -} -``` -### 重置格式设置 -在尝试不同的格式设置配置时,您可能会发现需要将所有内容重置为首次启动内核时看到的默认值。您可以轻松执行此作: -```csharp -Microsoft.DotNet.Interactive.Formatting.Formatter.ResetToDefault(); -``` -### 如何选择格式化程序 -可以注册多个可能适用于同一类型的格式化程序。例如,可以为 object、IEnumerable 和 IList 注册格式化程序,其中任何一个都可能合理地应用于 List 的实例。由于这些原因,了解如何选择 formatter 可能很有用。 -为 A 类型的对象选择适用的格式化程序,如下所示: -+ 选择 MIME 类型: - + 选择与 A 相关的最具体的用户注册 MIME 类型首选项 - + 如果没有相关的用户注册的 MIME 类型,则使用配置的默认 MIME 类型 -+ 选择一个格式化程序: - + 选择与 A 相关的最具体的用户注册格式化程序 - + 如果没有相关的用户注册格式化程序,则选择默认格式化程序 - -> 在这里,“最具体”是指类和接口层次结构。如果顺序完全一致或存在其他冲突,则首选较新的注册。当泛型类型的类型定义相同时,泛型类型的类型实例化优先于泛型格式化程序。 -> MIME 类型的默认格式化程序集始终包括 object 的格式化程序 -```csharp -using System.IO; -using Microsoft.DotNet.Interactive.Formatting; - -ITypeFormatter formatter = Formatter.GetPreferredFormatterFor( typeof(Rectangle), Formatter.DefaultMimeType); - -var rect = new Rectangle { Width = 100, Height = 50 }; - -var writer = new StringWriter(); - -formatter.Format(rect, writer); - -Console.WriteLine(writer.ToString()); -``` -Examples 例子, 用于说明 Formatter 选择的工作原理 - -+ 如果您为类型 A 注册格式化程序,则该格式化程序将用于类型 A 的所有对象(直到稍后指定类型 A 的替代格式化程序) -+ 如果为 System.Object 注册格式化程序,则它优先于所有其他格式化程序,但其他更具体的用户定义的格式化程序除外 -+ 如果为任何 sealed 类型注册格式化程序,则它优先于所有其他格式化程序(除非为该类型指定了更多格式化程序) -+ 如果注册 List<> 和 List 格式化程序,则 List 格式化程序优先用于 List 类型的对象,而 List<> 格式化程序优先用于其他泛型实例化,例如 List diff --git a/Docs/多语言笔记.2.1.操作数据库-SQL内核.ipynb b/Docs/多语言笔记.2.1.操作数据库-SQL内核.ipynb index 07a173d..5d0c94f 100644 --- a/Docs/多语言笔记.2.1.操作数据库-SQL内核.ipynb +++ b/Docs/多语言笔记.2.1.操作数据库-SQL内核.ipynb @@ -26,7 +26,8 @@ "id": "ed3707e0", "metadata": {}, "source": [ - "## 初始化" + "## 初始化\n", + "运行各单元格之前,必须先执行一次。" ] }, { @@ -38,6 +39,15 @@ } }, "outputs": [ + { + "data": { + "text/html": [ + "
Installed Packages
  • Microsoft.Identity.Client, 4.66.2
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, { "data": { "text/html": [ @@ -52,6 +62,8 @@ "//全局初始化\n", "#!import \"./Base.ipynb\"\n", "\n", + "#r \"nuget:Microsoft.Identity.Client,4.66.2\"\n", + "\n", "//共享\n", "using Microsoft.DotNet.Interactive;\n", "using Microsoft.DotNet.Interactive.Commands;" @@ -204,6 +216,14 @@ "## 查询数据库(SQL Server 2019为例)" ] }, + { + "cell_type": "markdown", + "id": "3a4296f8", + "metadata": {}, + "source": [ + "使用SQL语法,进行数据库操作" + ] + }, { "cell_type": "code", "execution_count": 4, @@ -302,6 +322,289 @@ "使用SQL语法,进行数据库操作" ] }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "polyglot_notebook": { + "kernelName": "sql-SqlServerKernelDemo" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(10 行受到影响)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/csv": [ + "Id,Name,Age\r\n", + "1,吕宇宁,74\r\n", + "2,韦子异,3\r\n", + "3,姚宇宁,27\r\n", + "4,傅子异,18\r\n", + "5,朱子韬,5\r\n", + "6,林杰宏,73\r\n", + "7,胡璐,60\r\n", + "8,周璐,23\r\n", + "9,田秀英,6\r\n", + "10,姜詩涵,82\r\n" + ], + "text/html": [ + "
IdNameAge
1
吕宇宁
74
2
韦子异
3
3
姚宇宁
27
4
傅子异
18
5
朱子韬
5
6
林杰宏
73
7
胡璐
60
8
周璐
23
9
田秀英
6
10
姜詩涵
82
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "--右下方:选择的SQL内核\n", + "\n", + "--原始SQL查询语句\n", + "select top 10 * from student" + ] + }, + { + "cell_type": "markdown", + "id": "ec584f13", + "metadata": {}, + "source": [ + "## 连接数据库:使用 `--create-dbcontext` 参数,自动创建 EFCore 上下文 `DbContext`" + ] + }, + { + "cell_type": "markdown", + "id": "7b4f61fc", + "metadata": {}, + "source": [ + "说明:目前默认情况下,Microsoft.DotNet.Interactive.SqlServer里引用的Microsoft.Identity.Client包,与环境中不一样,故需要单独引用特定版本的Microsoft.Identity.Client包,不知道后续官方是否会改正。目前单独包引用放在初始化单元格。" + ] + }, + { + "cell_type": "markdown", + "id": "01d19fab", + "metadata": {}, + "source": [ + "### 带 `--create-dbcontext` 参数的连接" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [ + { + "data": { + "text/markdown": [ + "Scaffolding a `DbContext` and initializing an instance of it called `SqlServerKernelWithEF` in the C# kernel." + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/html": [ + "
Installed Packages
  • Humanizer, 2.14.1
  • humanizer.core, 2.14.1
  • microsoft.data.sqlclient, 5.2.2
  • Microsoft.EntityFrameworkCore.Design, 9.0.0
  • microsoft.entityframeworkcore.sqlserver, 9.0.0
  • Microsoft.Identity.Client, 4.66.2
" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "Kernel added: #!sql-SqlServerKernelWithEF" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "/* 连接魔术命令\n", + " 给 #!connect mssql 加 --create-dbcontext 参数:连接操作,会执行下面的任务:\n", + " 1、搭建EFCore基架,并初始化 DBContext 的实例: xxxx\n", + " 2、安装包相关Nuget包,详情见输出\n", + " 3、添加新的子内核 #!sql-xxx\n", + "**/\n", + "\n", + "//注意:由于引用的Microsoft.Identity.Client包,版本冲突,目前把 Microsoft.Identity.Client的引用,放在 Microsoft.DotNet.Interactive.SqlServer之前\n", + "// #r \"nuget:Microsoft.Identity.Client,4.66.2\" 放入初始化\n", + "\n", + "//优化用法\n", + "{\n", + " //内核名:魔法命令中的内核名,执行后会自动加 sql- 前缀,做为内核名被使用\n", + " string magicCommandKernelName = \"SqlServerKernelWithEF\";\n", + " string completeKernelName = \"sql-\" + magicCommandKernelName;\n", + "\n", + " //引入内核:可重复执行\n", + " if(Microsoft.DotNet.Interactive.Kernel.Root.FindKernelByName(completeKernelName) == null)\n", + " {\n", + " var connectKernelCode = $\"#!connect mssql --kernel-name {magicCommandKernelName} \\\"{SharedDbConnect.MsSqlConnectionString}\\\" --create-dbcontext\";\n", + " await Kernel.Root.SendAsync(new SubmitCode( connectKernelCode, \"csharp\"));\n", + " }\n", + " else\n", + " {\n", + " Console.WriteLine($\"名为 {completeKernelName} 的内核已存在。需要新内核时,请为--kernel-name参数使用不同的值, 本次执行不做任何更改!\");\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "id": "eae8ee05", + "metadata": {}, + "source": [ + "### SQL内核中使用(与一般连接一样使用)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "polyglot_notebook": { + "kernelName": "sql-SqlServerKernelWithEF" + } + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(5 行受到影响)" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/csv": [ + "Id,Name,Age\r\n", + "1,吕宇宁,74\r\n", + "2,韦子异,3\r\n", + "3,姚宇宁,27\r\n", + "4,傅子异,18\r\n", + "5,朱子韬,5\r\n" + ], + "text/html": [ + "
IdNameAge
1
吕宇宁
74
2
韦子异
3
3
姚宇宁
27
4
傅子异
18
5
朱子韬
5
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "--原始SQL查询语句\n", + "select top 5 * from student" + ] + }, + { + "cell_type": "markdown", + "id": "27ee738f", + "metadata": {}, + "source": [ + "### C#语句中,直接使用 DbContext 上下文" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [], + "source": [ + "//连接建立后,执行环境中就有了相关的类:DBContext等\n", + "/* 因为类型版本问题,不能实际执行;后续看\n", + "{\n", + " //直接查询\n", + " var t = SqlServerKernelWithEF.Students.Take(5).ToList();\n", + " display(t);\n", + "\n", + " //EF内执行SQL语句\n", + " FormattableString fs = $\"select top 3 * from Student;\";\n", + " var c = SqlServerKernelWithEF.Database.ExecuteSql(fs);\n", + " display(c);\n", + "}\n", + "*/" + ] + }, { "cell_type": "markdown", "id": "867b43cc", @@ -320,7 +623,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 9, "metadata": { "polyglot_notebook": { "kernelName": "csharp" @@ -351,7 +654,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 10, "metadata": { "polyglot_notebook": { "kernelName": "csharp" @@ -398,7 +701,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 11, "metadata": { "polyglot_notebook": { "kernelName": "sql-SqlServerKernelShared" @@ -533,7 +836,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 12, "metadata": { "polyglot_notebook": { "kernelName": "csharp" @@ -745,7 +1048,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 13, "metadata": { "polyglot_notebook": { "kernelName": "javascript" @@ -810,7 +1113,7 @@ }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 14, "id": "180499e7", "metadata": { "polyglot_notebook": { @@ -834,7 +1137,7 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 15, "id": "09172abb", "metadata": { "polyglot_notebook": { @@ -877,7 +1180,7 @@ }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 16, "id": "3dac305e", "metadata": { "polyglot_notebook": { @@ -960,7 +1263,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 17, "id": "cb3528e0", "metadata": { "polyglot_notebook": { @@ -1097,7 +1400,7 @@ }, { "cell_type": "code", - "execution_count": 14, + "execution_count": 18, "id": "e41307ed", "metadata": { "polyglot_notebook": { @@ -1308,7 +1611,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 19, "id": "eabc34b9", "metadata": { "polyglot_notebook": { @@ -1365,7 +1668,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 20, "id": "45adfb6a", "metadata": { "polyglot_notebook": { @@ -1409,7 +1712,7 @@ }, { "cell_type": "code", - "execution_count": 17, + "execution_count": 21, "id": "3d0496c9", "metadata": { "polyglot_notebook": { @@ -1455,7 +1758,7 @@ }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 22, "id": "df085375", "metadata": { "polyglot_notebook": { @@ -1569,7 +1872,7 @@ }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 23, "id": "b37177b2", "metadata": { "polyglot_notebook": { @@ -1613,7 +1916,7 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 24, "id": "57b043ec", "metadata": { "polyglot_notebook": { @@ -1686,7 +1989,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 25, "id": "76d8d37f", "metadata": { "polyglot_notebook": { @@ -1800,7 +2103,7 @@ }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 26, "id": "5ee11d91", "metadata": { "polyglot_notebook": { @@ -1844,7 +2147,7 @@ }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 27, "id": "52a0668c", "metadata": { "polyglot_notebook": { @@ -1945,7 +2248,7 @@ }, { "cell_type": "code", - "execution_count": 24, + "execution_count": 28, "id": "7afddc24", "metadata": { "polyglot_notebook": { @@ -2068,6 +2371,11 @@ "aliases": [], "languageName": "T-SQL", "name": "sql-SqlServerKernelStuidy" + }, + { + "aliases": [], + "languageName": "T-SQL", + "name": "sql-SqlServerKernelWithEF" } ] } diff --git a/Docs/多语言笔记.2.1.连接数据库.ipynb b/Docs/多语言笔记.2.1.连接数据库.ipynb deleted file mode 100644 index 1658cfc..0000000 --- a/Docs/多语言笔记.2.1.连接数据库.ipynb +++ /dev/null @@ -1,394 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "连接数据库\n", - "============================== " - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "连接到SQL Server,并操作数据。" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 引用操作类库" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#r \"nuget:Microsoft.Dotnet.Interactive.SqlServer,*-*\"\n", - "#r \"nuget:Microsoft.Identity.Client,4.66.2\"" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 连接到SQL Server" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 数据库连接命令" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 命令概述: 使用帮助参数" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "数据库连接命令为 `#!connect` 查看连接帮助 `#!connect -h`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!connect -h" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 连接到本机SQL Server" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1. 建立连接" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> 连接到本机SQL Server, 特别注意的是 --kernel-name 指定名称,后面的SQL操作均需要使用:sql-{{kernel-name}}的值\n", - "> 比如 --kernel-name Demo, 则该SQL连接的kernel名称为 sql-Demo, 使用 #!sql-Demo 进行引用" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!connect mssql \"server=.\\SQL2008;uid=sa;pwd=gly-bicijinlian;database=Study;Encrypt=True;TrustServerCertificate=True;\" --kernel-name Demo\n", - "//重复执行会抛出错误,目前没有找到解决方法" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "2. 使用连接: 方式一" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> 在右下角,切换 Kernel, 由 `csharp - C# Script` 换成 由--kernel-name指定值生成的 `sql-Demo - T-SQL`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "sql-Demo" - }, - "polyglot_notebook": { - "kernelName": "sql-Demo" - } - }, - "outputs": [], - "source": [ - "SELECT * from Student" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "2. 使用连接:方式二(推荐)" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> 使用 `#!sql-Demo` ,后面直接写SQL语句,不用切换 kernel " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!sql-Demo\n", - "SELECT * from Student" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 使用 EF Core" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 新连接: 添加 --create-dbcontext 参数" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!connect mssql \"server=.\\SQL2008;uid=sa;pwd=gly-bicijinlian;database=Study;Encrypt=True;TrustServerCertificate=True;\" --create-dbcontext --kernel-name DemoEF " - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "上面的连接操作,会执行下面的任务:\n", - "+ 搭建EFCore基架,并初始化 DBContext 的实例: DemoEF\n", - "+ 安装包相关Nuget包,详情见输出\n", - "+ 添加新的子内核 #!sql-DemoEF" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 使用EFCore连接: 操作数据" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### 类SQL脚本方式" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!sql-DemoEF\n", - "SELECT * from Student" - ] - }, - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### C#程序中使用EF Core" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "dotnet_interactive": { - "language": "csharp" - }, - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "//连接建立后,执行环境中就有了相关的类:DBContext等\n", - "DemoEFContext context = new DemoEFContext();\n", - "var t = context.Students.ToList();\n", - "display(t);\n", - "\n", - "FormattableString fs = $\"select * from Student;\";\n", - "var c = context.Database.ExecuteSql(fs);\n", - "display(c);" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": ".NET (C#)", - "language": "C#", - "name": ".net-csharp" - }, - "language_info": { - "name": "polyglot-notebook" - }, - "polyglot_notebook": { - "kernelInfo": { - "defaultKernelName": "csharp", - "items": [ - { - "aliases": [], - "name": ".NET" - }, - { - "aliases": [ - "C#", - "c#" - ], - "languageName": "C#", - "name": "csharp" - }, - { - "aliases": [ - "F#", - "f#" - ], - "languageName": "F#", - "name": "fsharp" - }, - { - "aliases": [], - "languageName": "HTML", - "name": "html" - }, - { - "aliases": [], - "languageName": "KQL", - "name": "kql" - }, - { - "aliases": [], - "languageName": "Mermaid", - "name": "mermaid" - }, - { - "aliases": [ - "powershell" - ], - "languageName": "PowerShell", - "name": "pwsh" - }, - { - "aliases": [], - "languageName": "SQL", - "name": "sql" - }, - { - "aliases": [], - "languageName": "T-SQL", - "name": "sql-Demo" - }, - { - "aliases": [], - "languageName": "T-SQL", - "name": "sql-DemoEF" - }, - { - "aliases": [], - "name": "value" - }, - { - "aliases": [ - "frontend" - ], - "name": "vscode" - } - ] - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/Docs/多语言笔记.9.2.使用python.ipynb b/Docs/多语言笔记.9.2.使用python.ipynb deleted file mode 100644 index 83c589a..0000000 --- a/Docs/多语言笔记.9.2.使用python.ipynb +++ /dev/null @@ -1,140 +0,0 @@ -{ - "cells": [ - { - "attachments": {}, - "cell_type": "markdown", - "metadata": {}, - "source": [ - "在 Ployglog Notebook 中, 使用Python语言内核\n", - "=========================================\n", - "使用多语言笔记,直接支持 Python语言\n", - "优势:在一个笔记文档中,可以同时混合多种语言:Python、C#、F#、PowerShell、JS、SQL、HTML等" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 方式一:导入Python语言内核\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "这种导入方式,使用简单;但只能执行一次,多次执行会报错" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "//命名空间\n", - "using Microsoft.DotNet.Interactive;\n", - "using Microsoft.DotNet.Interactive.Commands;\n", - "\n", - "//引入Python内核\n", - "#!connect jupyter --kernel-name pythonkernel --kernel-spec python3" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 方式二:导入Python语言内核\n", - "这种导入方式,是方式一的优化、变型版,原理一样;但可多次执行,不报错" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "using Microsoft.DotNet.Interactive;\n", - "using Microsoft.DotNet.Interactive.Commands;\n", - "\n", - "//引入Python内核:使用C# 执行引入语句\n", - "if(Kernel.Root.FindKernelByName(\"pythonkernel\") == null)\n", - "{\n", - " //Console.WriteLine(\"正在导入Python内核....\");\n", - " var importPythonkernel = \"#!connect jupyter --kernel-name pythonkernel --kernel-spec python3\";\n", - " await Kernel.Root.SendAsync(new SubmitCode( importPythonkernel, \"csharp\"));\n", - " //Console.WriteLine(\"Python内核导入完成\");\n", - "}\n", - "else \n", - "{\n", - " //Console.WriteLine(\"Python内核已经导入\");\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 使用Python语言内核\n", - "#!pythonkernel 命令,切换到Python语言内核" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "polyglot_notebook": { - "kernelName": "csharp" - } - }, - "outputs": [], - "source": [ - "#!pythonkernel\n", - "\n", - "# 必须先执行导入Python内核语句\n", - "\n", - "print(\"你好,我是 Ployglot Notebooks 使用 Python语言内核,打印的内容!\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": ".NET (C#)", - "language": "C#", - "name": ".net-csharp" - }, - "language_info": { - "name": "polyglot-notebook" - }, - "orig_nbformat": 4, - "polyglot_notebook": { - "kernelInfo": { - "defaultKernelName": "csharp", - "items": [ - { - "aliases": [], - "name": "csharp" - }, - { - "aliases": [], - "languageName": "python", - "name": "pythonkernel" - }, - { - "aliases": [], - "name": "razor" - } - ] - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/Docs/多语言笔记.9.2.使用python内核.ipynb b/Docs/多语言笔记.9.2.使用python内核.ipynb new file mode 100644 index 0000000..e208211 --- /dev/null +++ b/Docs/多语言笔记.9.2.使用python内核.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "在 Polyglot Netebooks 中,添加Jupyter内核,支持Python语言\n", + "=======================================================\n", + "\n", + "+ 前提:系统要安装Python环境,推荐使用Anaconda安装,直接安装Python也可以\n", + "\n", + "+ 作用:使多语言笔记,直接支持 Python语言;\n", + "\n", + "+ 优势:在一个笔记文档中,可以同时混合多种语言:Python、C#、F#、PowerShell、JS、SQL、HTML等" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 安装 Python\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "+ 直接安装:[Python官网](https://www.python.org/) 下载安装即可;\n", + "+ Anaconda:[Anaconda官网](https://www.anaconda.com/) 安装后要设置好默认环境;" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "``` cmd\n", + " # 保证:在命令行窗口,能直接执行下面命令\n", + " python --version\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 方式一:直接使用魔法命令`#!connect jupyter`\n" + ] + }, + { + "cell_type": "markdown", + "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" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [ + { + "data": { + "text/markdown": [ + "The `#!connect jupyter` feature is in preview. Please report any feedback or issues at https://github.com/dotnet/interactive/issues/new/choose." + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "Kernel added: #!pythonkernel" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "//命名空间\n", + "using Microsoft.DotNet.Interactive;\n", + "using Microsoft.DotNet.Interactive.Commands;\n", + "\n", + "//引入Python内核\n", + "#!connect jupyter --kernel-name pythonkernel --kernel-spec python3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 方式二:变通用法:在C#程序中,拼接好魔术命令`#!connect`,再发送给内核执行\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "此种方式是魔法命令的变型、优化版,本质原理一样,只是调用方式换成C#。\n", + "优点:\n", + "+ 多次执行,不报错;\n", + "+ 魔法命令:可自由拼接(可使用配置文件、系统变量、共享变量等),非常灵活;" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "polyglot_notebook": { + "kernelName": "csharp" + } + }, + "outputs": [], + "source": [ + "using Microsoft.DotNet.Interactive;\n", + "using Microsoft.DotNet.Interactive.Commands;\n", + "\n", + "//引入Python内核:使用C# 执行引入语句\n", + "if(Kernel.Root.FindKernelByName(\"pythonkernel\") == null)\n", + "{\n", + " //Console.WriteLine(\"正在导入Python内核....\");\n", + " var importPythonkernel = \"#!connect jupyter --kernel-name pythonkernel --kernel-spec python3\";\n", + " await Kernel.Root.SendAsync(new SubmitCode( importPythonkernel, \"csharp\"));\n", + " //Console.WriteLine(\"Python内核导入完成\");\n", + "}\n", + "else \n", + "{\n", + " //Console.WriteLine(\"Python内核已经导入\");\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 使用Python语言内核" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "+ 使用 #!pythonkernel 命令,切换到Python语言内核\n", + "+ 单元格右下角,选择 `pythonkernel`内核 " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "polyglot_notebook": { + "kernelName": "pythonkernel" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "你好,我是 Ployglot Notebooks 使用 Python语言内核,打印的内容!\n" + ] + } + ], + "source": [ + "# 明确指定内核:优先级高于 \"单元格选择的内核\"\n", + "#!pythonkernel\n", + "\n", + "print(\"你好,我是 Ployglot Notebooks 使用 Python语言内核,打印的内容!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "polyglot_notebook": { + "kernelName": "pythonkernel" + } + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "右下方选择Python内核\n" + ] + } + ], + "source": [ + "# 右下方选择 内核\n", + "print(\"右下方选择Python内核\");" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "polyglot_notebook": { + "kernelName": "pythonkernel" + } + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".NET (C#)", + "language": "C#", + "name": ".net-csharp" + }, + "language_info": { + "name": "polyglot-notebook" + }, + "orig_nbformat": 4, + "polyglot_notebook": { + "kernelInfo": { + "defaultKernelName": "csharp", + "items": [ + { + "aliases": [], + "name": "csharp" + }, + { + "aliases": [], + "languageName": "python", + "name": "pythonkernel" + }, + { + "aliases": [], + "name": "razor" + } + ] + } + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Docs/练习-添加Jupyter内核.ipynb b/Docs/练习-添加Jupyter内核.ipynb deleted file mode 100644 index 8b0129b..0000000 --- a/Docs/练习-添加Jupyter内核.ipynb +++ /dev/null @@ -1,131 +0,0 @@ -{ - "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 -}