-
Notifications
You must be signed in to change notification settings - Fork 4
/
client_test.py
135 lines (106 loc) · 2.83 KB
/
client_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import queue
from jupyter_client.manager import start_new_kernel
kernel_manager, client = start_new_kernel(kernel_name="bash")
def runCode(code):
### Execute the code
client.execute(code)
### Get the execution status
### When the execution state is "idle" it is complete
io_msg = client.get_iopub_msg(timeout=1)
io_msg_content = io_msg['content']
### We're going to catch this here before we start polling
if 'execution_state' in io_msg_content and io_msg_content['execution_state'] == 'idle':
return "no output"
### Continue polling for execution to complete
### which is indicated by having an execution state of "idle"
while True:
### Save the last message content. This will hold the solution.
### The next one has the idle execution state indicating the execution
###is complete, but not the stdout output
temp = io_msg_content
### Poll the message
try:
io_msg = client.get_iopub_msg(timeout=1)
io_msg_content = io_msg['content']
if (
'execution_state' in io_msg_content
and io_msg_content['execution_state'] == 'idle'
):
break
except queue.Empty:
print("timeout get_iopub_msg")
break
### Check the message for various possibilities
if 'data' in temp: # Indicates completed operation
out = temp['data']['text/plain']
elif 'name' in temp and temp['name'] == "stdout": # indicates output
out = temp['text']
elif 'traceback' in temp: # Indicates error
print("ERROR")
out = '\n'.join(temp['traceback']) # Put error into nice format
else:
out = ''
return out
python_commands = \
[
'!pwd',
'!echo "hello"',
'!ls',
'1+1',
'a=5',
'b=0',
'print()',
'b',
'print()',
'print("hello there")',
'print(a*10)',
'c=1/b'
]
R_commands = \
[
'a<-5',
'b<-0',
'rnorm(5)',
'b',
'describe(cars)',
'print("hello there")',
'print(a*10)',
'c=1/b'
]
bash_commands = \
[
'ls',
'pwd',
'echo "hello" | sed \'s/el/99/\'',
'a=10',
'echo $a'
]
for command in bash_commands:
print(">>>" + command)
out = runCode(command)
print(out)
"""
>>>!pwd
>>>!echo "hello"
"hello"
>>>!ls
>>>1+1
2
>>>a=5
>>>b=0
>>>print()
>>>b
0
>>>print()
>>>print("hello there")
hello there
>>>print(a*10)
50
>>>c=1/b
ERROR
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-12-47a519732db5> in <module>()
----> 1 c=1/b
ZeroDivisionError: division by zero
"""