一种JupterLab代码格式化插件的配置方法
如果你使用的是 Anaconda 环境,并且希望在 JupyterLab 中创建一个自定义的代码格式化命令来运行 black
或 autopep8
,你可以按照以下步骤进行操作。我们将使用 Anaconda 环境来管理依赖项,并创建一个自定义的 JupyterLab 扩展。
1. 安装 black
和 autopep8
首先,确保你已经安装了 black
和 autopep8
:
conda install black autopep8
2. 创建自定义命令
你可以通过编写一个 JupyterLab 扩展来创建自定义命令。以下是一个简单的示例,展示如何在 JupyterLab 中创建一个自定义命令来运行 black
或 autopep8
。
2.1 创建扩展目录
首先,创建一个新的目录来存放你的扩展代码:
mkdir jupyterlab-custom-formatter
cd jupyterlab-custom-formatter
JupyterLab 扩展需要一个 setup.py
文件来安装。我们可以通过以下步骤来创建并配置这个文件。
2.2 创建 setup.py
文件
在扩展的根目录中创建一个 setup.py
文件,内容如下:
from setuptools import setup, find_packages
setup(
name="jupyterlab-custom-formatter",
version="0.1.0",
packages=find_packages(),
install_requires=[
"jupyterlab>=4.0.0",
"black",
"autopep8"
],
include_package_data=True,
zip_safe=False,
)
2.3创建 MANIFEST.in
文件
在扩展的根目录中创建一个 MANIFEST.in
文件,内容如下:
include package.json
recursive-include src *
2.4创建 package.json
在扩展目录中创建一个 package.json
文件,定义你的扩展:
{
"name": "jupyterlab-custom-formatter",
"version": "0.1.0",
"description": "A custom formatter for JupyterLab using black and autopep8",
"jupyterlab": {
"extension": true
},
"dependencies": {
"@jupyterlab/application": "^4.0.0",
"@jupyterlab/apputils": "^4.0.0",
"@jupyterlab/codemirror": "^4.0.0",
"@jupyterlab/notebook": "^4.0.0"
},
"devDependencies": {
"typescript": "^4.0.0"
},
"scripts": {
"build": "tsc",
"watch": "tsc -w",
"prepare": "npm run build"
}
}
2.5 创建 src
目录
在扩展目录中创建一个 src
目录(指的是/jupyterlab-custom-formatter/src):
mkdir src
2.6 创建 src/index.ts
在 src
目录中创建一个 index.ts
文件,编写你的扩展代码:
import {
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import {
ICommandPalette
} from '@jupyterlab/apputils';
import {
CodeMirrorEditor
} from '@jupyterlab/codemirror';
import {
NotebookPanel,
INotebookTracker
} from '@jupyterlab/notebook';
import {
DocumentRegistry
} from '@jupyterlab/docregistry';
import {
IDisposable,
DisposableDelegate
} from '@lumino/disposable';
import {
CommandRegistry
} from '@lumino/commands';
import {
Message
} from '@lumino/messaging';
import {
Widget
} from '@lumino/widgets';
import {
execSync
} from 'child_process';
/**
* The plugin registration information.
*/
const plugin: JupyterFrontEndPlugin<void> = {
id: 'jupyterlab-custom-formatter:plugin',
autoStart: true,
requires: [ICommandPalette, INotebookTracker],
activate: (
app: JupyterFrontEnd,
palette: ICommandPalette,
notebooks: INotebookTracker
) => {
console.log('JupyterLab extension jupyterlab-custom-formatter is activated!');
// Add a command to the command registry
const command = 'custom-formatter:format';
app.commands.addCommand(command, {
label: 'Format Code with black or autopep8',
execute: () => {
const notebook = notebooks.currentWidget;
if (!notebook) {
return;
}
const cell = notebook.content.activeCell;
if (cell && cell.model.type === 'code') {
const code = cell.model.value.text;
try {
// Format code with black
const formattedCode = execSync(`echo "${code}" | black -q -`, { encoding: 'utf8' });
cell.model.value.text = formattedCode;
} catch (error) {
console.error('Error formatting code with black:', error);
}
}
}
});
// Add the command to the palette
palette.addItem({ command, category: 'Custom' });
}
};
export default plugin;
2.7 编译扩展
使用 TypeScript 编译你的扩展:
npm install
npm run build
2.8 安装扩展
将你的扩展安装到 JupyterLab:
jupyter labextension develop --overwrite .
3. 使用自定义命令
启动 JupyterLab 后,你应该能够在命令面板中看到新的命令 Format Code with black or autopep8
。选择该命令后,当前活动单元格中的代码将被 black
格式化。
4. 关于报错
Installing collected packages: jupyterlab-custom-formatter
Running setup.py develop for jupyterlab-custom-formatter
Successfully installed jupyterlab-custom-formatter-0.1.0
F:\annaconda\Lib\site-packages\jupyterlab\debuglog.py:54: UserWarning: An error occurred.
warnings.warn("An error occurred.")
F:\annaconda\Lib\site-packages\jupyterlab\debuglog.py:55: UserWarning: ModuleNotFoundError: There is no labextension at .. Errors encountered: [TypeError("the 'package' argument is required to perform a relative import for '.'"), ModuleNotFoundError("No module named 'jupyterlab_custom_formatter'")]
warnings.warn(msg[-1].strip())
F:\annaconda\Lib\site-packages\jupyterlab\debuglog.py:56: UserWarning: See the log file for details: C:\Users\w\AppData\Local\Temp\jupyterlab-debug-t331ya8l.log
warnings.warn(f"See the log file for details: {log_path!s}")
如有以上报错,请尝试重启jupterlab,并检查插件是否可以正常使用,如可以正常使用,请忽略(本人经多次GPT询问改错均无法解决,重启后可正常使用),如果不能正常使用请移步ChatGPT寻求帮助。
成功之后有如下按钮图样
总结
通过创建一个自定义的 JupyterLab 扩展,你可以轻松地在 JupyterLab 中添加自定义命令来运行 black
或 autopep8
。这个示例展示了如何使用 black
格式化代码,你可以根据需要修改代码以使用 autopep8
或其他格式化工具。