modelscope / start_jupyterlab.py
HOPStudio's picture
Update start_jupyterlab.py
8f466b4 verified
Raw
History Blame Contribute Delete
3.47 kB
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") # 禁用 token
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", # 允许以 root 身份运行
"--NotebookApp.token=''", # 禁用 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__":
# 1. 修改 Jupyter 配置
modify_jupyter_config()
# 2. 启动 JupyterLab
start_jupyter_lab()