Python脚本如何生成Jupyter配置

wen 实用脚本 28

本文目录导读:

Python脚本如何生成Jupyter配置

  1. 生成默认配置文件
  2. 自定义配置文件生成
  3. JSON格式配置(Jupyter Lab)
  4. 交互式配置文件生成器
  5. 程序化配置管理
  6. 使用方法
  7. 注意事项

生成默认配置文件

import subprocess
import os
# 生成Jupyter Notebook默认配置
subprocess.run(['jupyter', 'notebook', '--generate-config'])
# 生成Jupyter Lab默认配置
subprocess.run(['jupyter', 'lab', '--generate-config'])

自定义配置文件生成

import json
import os
def generate_jupyter_config(config_path=None):
    """生成自定义Jupyter配置"""
    # 默认配置路径
    if config_path is None:
        config_path = os.path.expanduser('~/.jupyter/jupyter_notebook_config.py')
    # 配置内容
    config_content = """
# Jupyter Notebook配置
# 允许远程访问
c.NotebookApp.allow_remote_access = True
# 设置IP地址
c.NotebookApp.ip = '0.0.0.0'
# 设置端口
c.NotebookApp.port = 8888
# 不自动打开浏览器
c.NotebookApp.open_browser = False
# 设置密码(需要先使用jupyter notebook password生成)
# c.NotebookApp.password = 'sha1:...'
# 设置工作目录
# c.NotebookApp.notebook_dir = '/path/to/notebooks'
# Token设置
# c.NotebookApp.token = 'your-token-here'
# 设置根目录
# c.ServerApp.root_dir = '/path/to/notebooks'
# 禁用token
# c.NotebookApp.token = ''
# 设置语言
# c.NotebookApp.default_url = '/tree'
"""
    # 确保目录存在
    os.makedirs(os.path.dirname(config_path), exist_ok=True)
    # 写入配置
    with open(config_path, 'w', encoding='utf-8') as f:
        f.write(config_content)
    print(f"配置文件已生成: {config_path}")
    return config_path
# 使用函数
config_file = generate_jupyter_config()

JSON格式配置(Jupyter Lab)

import json
import os
def generate_jupyter_lab_config():
    """生成Jupyter Lab的JSON配置"""
    config_dir = os.path.expanduser('~/.jupyter/lab/user-settings/@jupyterlab')
    os.makedirs(config_dir, exist_ok=True)
    # 编辑器配置
    editor_config = {
        "editorConfig": {
            "cursorBlinkRate": 530,
            "fontFamily": "Consolas, 'Courier New', monospace",
            "fontSize": 14,
            "lineHeight": 1.6,
            "lineNumbers": True,
            "lineWrap": "off",
            "matchBrackets": True,
            "tabSize": 4,
            "autoClosingBrackets": True,
            "codeFolding": True
        }
    }
    # 主题配置
    theme_config = {
        "theme": "JupyterLab Light"
    }
    # 保存配置
    config_files = {
        'notebook-extension-1/editor_config.json': editor_config,
        'theme-extension-1/theme_config.json': theme_config
    }
    for filename, config in config_files.items():
        filepath = os.path.join(config_dir, filename)
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
        print(f"配置已生成: {filepath}")
# 生成配置
generate_jupyter_lab_config()

交互式配置文件生成器

import os
import json
import getpass
def interactive_jupyter_config_generator():
    """交互式Jupyter配置生成器"""
    print("=" * 50)
    print("Jupyter Notebook配置生成器")
    print("=" * 50)
    # 收集配置信息
    config = {}
    # IP地址
    ip = input("请输入绑定的IP地址 (默认: localhost): ").strip()
    config['c.NotebookApp.ip'] = ip if ip else "'localhost'"
    # 端口
    port = input("请输入端口号 (默认: 8888): ").strip()
    config['c.NotebookApp.port'] = int(port) if port else 8888
    # 是否自动打开浏览器
    open_browser = input("是否自动打开浏览器? (y/n, 默认: y): ").strip().lower()
    config['c.NotebookApp.open_browser'] = open_browser != 'n'
    # 工作目录
    work_dir = input("请输入工作目录路径 (默认: 当前目录): ").strip()
    if work_dir:
        config['c.NotebookApp.notebook_dir'] = f"'{work_dir}'"
    # 是否设置密码
    set_password = input("是否设置密码? (y/n, 默认: n): ").strip().lower()
    if set_password == 'y':
        print("请使用 'jupyter notebook password' 命令设置密码")
        print("然后将生成的hash值配置到文件中")
    # 生成配置内容
    config_content = "# Jupyter Notebook Configuration\n"
    config_content += f"# Generated by script at {__import__('datetime').datetime.now()}\n\n"
    for key, value in config.items():
        if isinstance(value, str) and not value.startswith("'"):
            config_content += f"{key} = '{value}'\n"
        else:
            config_content += f"{key} = {value}\n"
    # 保存配置
    config_path = os.path.expanduser('~/.jupyter/jupyter_notebook_config.py')
    os.makedirs(os.path.dirname(config_path), exist_ok=True)
    with open(config_path, 'w', encoding='utf-8') as f:
        f.write(config_content)
    print(f"\n配置文件已保存到: {config_path}")
    print("配置内容:")
    print(config_content)
# 运行交互式配置生成器
interactive_jupyter_config_generator()

程序化配置管理

import os
import configparser
from pathlib import Path
class JupyterConfigManager:
    """Jupyter配置管理器"""
    def __init__(self):
        self.config_dir = Path.home() / '.jupyter'
        self.config_file = self.config_dir / 'jupyter_notebook_config.py'
    def get_config_path(self):
        """获取配置文件路径"""
        return str(self.config_file)
    def config_exists(self):
        """检查配置是否存在"""
        return self.config_file.exists()
    def read_config(self):
        """读取配置文件"""
        if not self.config_exists():
            return None
        with open(self.config_file, 'r', encoding='utf-8') as f:
            return f.read()
    def write_config(self, content):
        """写入配置"""
        self.config_dir.mkdir(parents=True, exist_ok=True)
        with open(self.config_file, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"配置已写入: {self.config_file}")
    def update_config(self, key, value):
        """更新单个配置项"""
        config_content = self.read_config() or ""
        # 检查配置项是否已存在
        if f"{key}" in config_content:
            # 更新现有配置
            lines = config_content.split('\n')
            for i, line in enumerate(lines):
                if line.strip().startswith(key):
                    lines[i] = f"{key} = {value}"
                    break
            config_content = '\n'.join(lines)
        else:
            # 添加新配置
            config_content += f"\n{key} = {value}\n"
        self.write_config(config_content)
    def reset_to_default(self):
        """重置为默认配置"""
        subprocess.run(['jupyter', 'notebook', '--generate-config', '--force'])
# 使用示例
manager = JupyterConfigManager()
print(f"配置文件路径: {manager.get_config_path()}")
# 更新配置
manager.update_config('c.NotebookApp.ip', "'0.0.0.0'")
manager.update_config('c.NotebookApp.port', '8888')

使用方法

  1. 基本使用:运行脚本生成默认配置
  2. 自定义配置:修改脚本中的配置参数
  3. 批量部署:将脚本用于多台机器的配置
  4. 版本控制:将配置脚本纳入版本管理

注意事项

  • 确保有适当的文件写入权限
  • 密码配置建议使用jupyter notebook password命令
  • 生产环境配置需要更严格的安全设置
  • 配置修改后需要重启Jupyter服务

这些脚本可以帮助你快速生成和管理Jupyter配置。

抱歉,评论功能暂时关闭!