ipython / ipython

Official repository for IPython itself. Other repos in the IPython organization contain things like the website, documentation builds, etc.

Home Page:https://ipython.readthedocs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can i connect to Ipython kernel

NjustWrun opened this issue · comments

examples:
server: (Ipython docs examples)

   from ipykernel.kernelbase import Kernel
    class EchoKernel(Kernel):
        implementation = 'Echo'
        implementation_version = '1.0'
        language = 'no-op'
        language_version = '0.1'
        language_info = {'mimetype': 'text/plain'}
        banner = "Echo kernel - as useful as a parrot"
    
        def do_execute(self, code, silent, store_history=True, user_expressions=None,
                       allow_stdin=False):
            if not silent:
                stream_content = {'name': 'stdout', 'text': code}
                self.send_response(self.iopub_socket, 'stream', stream_content)
    
            return {'status': 'ok',
                    # The base class increments the execution count
                    'execution_count': self.execution_count,
                    'payload': [],
                    'user_expressions': {},
                   }
    
    if __name__ == '__main__':
        from ipykernel.kernelapp import IPKernelApp
        IPKernelApp.launch_instance(kernel_class=EchoKernel)

client:

import zmq
import json

context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://127.0.0.1:8888")  # 请根据实际情况修改连接地址和端口

while True:
    code = input("Enter code to execute (or 'exit' to quit): ")
    if code == "exit":
        break

    # 构造要发送的消息
    message = {
        'header': {
            'msg_id': '1234',  # 为了简单起见,使用固定的消息ID
            'username': 'username',  # 可以是任何字符串,用于标识客户端
            'session': '',
            'msg_type': 'execute_request',
            'version': '5.0',
        },
        'parent_header': {},
        'metadata': {},
        'content': {
            'code': code,
            'silent': False,
            'store_history': True,
            'user_expressions': {},
            'allow_stdin': False,
            'stop_on_error': True,
        },
    }

    # 发送消息给内核执行
    print(f"Sending message: {json.dumps(message, indent=2)}")
    socket.send_json(message)

    # 接收执行结果
    try:
        response = socket.recv_json()
        print("Execution result:")
        print(response)
    except zmq.ZMQError as e:
        print(f"Error receiving response: {e}")

Why can not i connect to ipython with client code above?
Can you give me some suggess? Thank you very much

$ python server.py

NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.

To exit, you will have to explicitly quit this process, by either sending
"quit" from a client, or using Ctrl-\ in UNIX-like environments.

To read more about this, see https://github.com/ipython/ipython/issues/2049


To connect another client to this kernel, use:
    --existing kernel-63911.json

Note the --existing kernel-63911.json this file can be found (for me) in /Library/Jupyter/runtime (MacOS).

$ cat kernel-63911.json
{
  "shell_port": 57492,
  "iopub_port": 57496,
  "stdin_port": 57493,
  "control_port": 57494,
  "hb_port": 57498,
  "ip": "127.0.0.1",
  "key": "a47f4cd5-f653fa28db142e98b34710a7",
  "transport": "tcp",
  "signature_scheme": "hmac-sha256",
  "kernel_name": ""
}

So my guess is socket.connect("tcp://127.0.0.1:8888") is the wrong port.

You want to read about https://jupyter-client.readthedocs.io/ which will give you the right abstractions to talk with a kernel.