| import os |
| import subprocess |
| import sys |
| import threading |
|
|
| def modify_jupyter_config(): |
| """修改 Jupyter 配置文件以允许远程访问并禁用 token""" |
| config_dir = os.path.expanduser("~/.jupyter") |
| config_file = os.path.join(config_dir, "jupyter_notebook_config.py") |
|
|
| |
| if not os.path.exists(config_file): |
| print("生成 Jupyter 配置文件...") |
| try: |
| subprocess.check_call([sys.executable, "-m", "jupyter", "notebook", "--generate-config"]) |
| print(f"配置文件已生成: {config_file}") |
| except subprocess.CalledProcessError as e: |
| print(f"生成配置文件时出错: {e}") |
| return |
|
|
| |
| with open(config_file, "r") as f: |
| config_content = f.read() |
| if "c.ServerApp.allow_remote_access" in config_content: |
| print("Jupyter 配置文件已经包含必要的设置,无需修改。") |
| return |
|
|
| |
| try: |
| print("修改 Jupyter 配置文件...") |
| with open(config_file, "a") as f: |
| f.write("\n# Allow remote access\n") |
| f.write("c.ServerApp.allow_remote_access = True\n") |
| f.write("c.ServerApp.ip = '0.0.0.0'\n") |
| f.write("c.ServerApp.port = 18888\n") |
| f.write("c.ServerApp.token = ''\n") |
| f.write("c.ServerApp.allow_origin = '*'\n") |
| f.write("c.ServerApp.allow_root = True\n") |
| f.write("c.ServerApp.open_browser = False\n") |
| print("Jupyter 配置文件修改完成!") |
| except Exception as e: |
| print(f"修改配置文件时出错: {e}") |
|
|
| def start_jupyter_lab(): |
| """启动 JupyterLab 服务并确保禁用 token""" |
| try: |
| print("启动 JupyterLab 服务...") |
|
|
| |
| command = [ |
| sys.executable, "-m", "jupyter", "lab", |
| "--no-browser", |
| "--ip=0.0.0.0", |
| "--port=18888", |
| "--allow-root", |
| "--NotebookApp.token=''", |
| "--NotebookApp.password=''", |
| "--notebook-dir=/", |
| ] |
|
|
| process = subprocess.Popen( |
| command, |
| stdout=subprocess.PIPE, |
| stderr=subprocess.PIPE, |
| text=True, |
| bufsize=1 |
| ) |
|
|
| def stream_output(pipe, pipe_name): |
| """实时打印子进程的输出""" |
| with pipe: |
| for line in pipe: |
| print(f"[{pipe_name}] {line.strip()}") |
|
|
| |
| threading.Thread(target=stream_output, args=(process.stdout, "STDOUT"), daemon=True).start() |
| threading.Thread(target=stream_output, args=(process.stderr, "STDERR"), daemon=True).start() |
|
|
| |
| process.wait() |
| print("JupyterLab 服务已停止。") |
| except Exception as e: |
| print(f"启动 JupyterLab 时出错: {e}") |
|
|
| if __name__ == "__main__": |
| |
| modify_jupyter_config() |
| |
| |
| start_jupyter_lab() |
|
|