You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
PolyglotNotebooksStudy/Docs/多语言笔记.9.2.使用python.ipynb

141 lines
3.3 KiB
Plaintext

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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