不为别的,只为做一个连自己都羡慕的人

python实现jupyter代码的运行

此写法还有少许的缺陷,有机会再实现改正

import json
import re

import requests

token = "1"  # 用户用来登录的token或者是密码
XSRFToken = "123"
username = "root"  # 默认的用户名是root
base = 'http://127.0.0.1:8888'


def aa():
    import json
    import datetime
    import uuid
    from websocket import create_connection

    # 启动笔记本时,令牌会写入标准输出
    # The token is written on stdout when you start the notebook
    notebook_path = '/home/jupyter/tf2/循环神经网络.ipynb'

    headers = {
        'Authorization': 'Token ' + token,
        # "cookie": '_xsrf=123; username-192-168-0-121-3839="2|1:0|10:1653466150|27:username-192-168-0-121-3839|44'
        #           ':YzA1MDZiZTMyMDM2NDNhM2ExYTY1ZTYwNTEwMmI2OGE'
        #           '=|7b1a53cda7ce28931565a57948b8cb13608c830b1625a38c6fb83b8c353cba01" ',
        "cookie": "_xsrf=123",
        "X-XSRFToken": XSRFToken
    }

    url = base + '/api/kernels'
    print(url)
    # response = requests.post(url, headers=headers)
    # kernel = json.loads(response.text)
    # print(kernel)

    response = requests.post(url, headers=headers)
    print(response.text)
    kernel = json.loads(response.text)
    # 加载笔记本并获取每个单元格的代码
    # Load the notebook and get the code of each cell
    print(kernel)
    url = base + '/api/contents' + notebook_path
    print(url)
    response = requests.get(url, headers=headers)
    file = json.loads(response.text)
    code = [c['source'] for c in file['content']['cells'] if len(c['source']) > 0]
    # print(code)

    print(kernel["id"])
    # 执行请求/回复在 websockets 通道上完成
    # Execution request/reply is done on websockets channels
    ws = create_connection("ws://127.0.0.1:3839/api/kernels/" + kernel["id"] + "/channels", header=headers)
    print("*******************")
    print(ws)

    def send_execute_request(code):
        msg_type = 'execute_request'
        content = {'code': code, 'silent': False}
        # print("uuid:", uuid.uuid1().hex)
        hdr = {'msg_id': uuid.uuid1().hex,
               'username': 'test',
               'session': uuid.uuid1().hex,
               'data': datetime.datetime.now().isoformat(),
               'msg_type': msg_type,
               'version': '5.0'}
        msg = {'header': hdr, 'parent_header': hdr,
               'metadata': {},
               'content': content}
        return msg

    for c in code:
        # print(json.dumps(send_execute_request(c)))
        ws.send(json.dumps(send_execute_request(c)))

    # We ignore all the other messages, we just get the code execution output
    # 我们忽略所有其他消息,我们只得到代码执行输出
    # (this needs to be improved for production to take into account errors, large cell output, images, etc.)
    # (这需要在生产中进行改进,以考虑错误、大电池输出、图像等)
    print(len(code))
    fileCon = bb()
    for i in range(0, len(code)):
        status = ""
        while True:
            con = json.loads(ws.recv())
            print(con)
            # 代表程序开始运行
            if con["msg_type"] == "execute_input":
                print(con["content"].get("execution_count"))
                execution_count = con["content"].get("execution_count")
                if execution_count is not None:
                    fileCon["cells"][i]["execution_count"] = con["content"].get("execution_count")
            # 代表程序运行结束
            if con["msg_type"] == "execute_reply":
                print(con["content"].get("status"))
                if con["content"].get("status") == "ok":
                    print(con["content"].get("status"))
                    break
                elif con["content"].get("status") != "error":
                    # 如果不等于ok得时候,退出双层循环 status="aborted"
                    print("************")
                    status = con["content"].get("status")
                    break
                else:
                    data = {"ename": con["content"]["ename"], "evalue": con["content"]["evalue"],
                            "output_type": con["content"]["status"], "traceback": [con["content"]["traceback"]]}
                    fileCon["cells"][i]["outputs"].append(data)
                    break
            # 当内核重启时,结束运行
            if con["msg_type"] == "status":  # restarting
                if con["content"].get("execution_state") == "restarting":
                    status = con["content"].get("execution_state")
                    break
            # 返回程序得运行结果
            if con["msg_type"] == "stream":
                obj = {"name": con["content"]["name"], "output_type": con["msg_type"],
                       "text": [con["content"]["text"].strip().strip("\b").strip("\r").strip()]}
                fileCon["cells"][i]["outputs"].append(obj)
                # print(con["content"]["text"])
            # 返回程序得运行结果 图片之类的
            if con["msg_type"] == "display_data":
                data = {"metadata": con["metadata"], "data": {"text/plain": [con["content"]["data"]["text/plain"]],
                                                              "image/png": con["content"]["data"]["image/png"]},
                        "output_type": con["msg_type"]}
                fileCon["cells"][i]["outputs"].append(data)
        if status != "":
            break
        # msg_type = ''
        # while msg_type != "stream":
        #     rsp = json.loads(ws.recv())
        #     msg_type = rsp["msg_type"]
        # print(rsp["content"]["text"])
        # # rsp = json.loads(ws.recv())
        # # print(rsp)
    ws.close()
    dd(json.dumps(fileCon))


# 读取文件中得内容
def bb():
    # 以 utf-8 的编码格式打开指定文件
    f = open("入门神经网络.ipynb", 'r', encoding="utf-8")
    # 输出读取到的数据
    # print(f.read())
    cc = json.loads(f.read())
    print(cc["cells"])
    print(len(cc["cells"]))
    # 关闭文件
    f.close()
    return cc


# 向文件中写内容
def dd(con):
    with open("入门神经网络_运行.ipynb", "w", encoding="utf-8") as f:
        f.write(con)
        print("写入成功!")


if __name__ == '__main__':
    aa()

 

posted @ 2022-06-07 16:47  升级打怪  阅读(644)  评论(0编辑  收藏  举报