{ "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 }