Skip to content

Instantly share code, notes, and snippets.

@argenisleon
Created October 14, 2019 15:35
Show Gist options
  • Select an option

  • Save argenisleon/d5a2528d6d144d56769157eb73164568 to your computer and use it in GitHub Desktop.

Select an option

Save argenisleon/d5a2528d6d144d56769157eb73164568 to your computer and use it in GitHub Desktop.
ip = "xxx.xxx.xxx.xxx"
port = "8888"
# headers = {'Authorization': 'Token 4a72cb6f71e0f05a6aa931a5e0ec70109099ed0c35f1d840'}
headers={}
# The token is written on stdout when you start the notebook
base = "http://"+ ip+ ":" + port
url = base + '/api'
response = requests.get(url,headers=headers)
kernel = json.loads(response.text)
print(kernel)
# headers = {'Authorization': 'Token 4a72cb6f71e0f05a6aa931a5e0ec70109099ed0c35f1d840'}
url = base + '/api/kernels'
response = requests.post(url,headers=headers)
kernel = json.loads(response.text)
print(kernel)
# Load the notebook and get the code of each cell
# url = base + '/api/contents' + notebook_path
# 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 ]
# Execution request/reply is done on websockets channels
ws = create_connection("ws://" +ip+ ":"+port+ "/api/kernels/"+kernel["id"]+"/channels",
header=headers)
def send_execute_request(code):
msg_type = 'execute_request';
content = { 'code' : code, 'silent':False }
hdr = { 'msg_id' : uuid.uuid1().hex,
'session': uuid.uuid1().hex,
'date': datetime.datetime.now().isoformat(),
'msg_type': msg_type,
'version' : '6.0.1'
}
msg = { 'header': hdr, 'parent_header': hdr,
'metadata': {},
'content': content }
return msg
code = ['["1+1"]']
# for c in code:
ws.send(json.dumps(send_execute_request("1+1")))
# 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.)
# while msg_type != "stream":
msg_type = ""
while msg_type != "execute_result":
# print(msg_type)
rsp = json.loads(ws.recv())
# print(rsp)
msg_type = rsp["msg_type"]
print(rsp["content"]["data"]["text/plain"])
ws.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment