-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvariable_inspector.py
More file actions
365 lines (285 loc) · 11.3 KB
/
variable_inspector.py
File metadata and controls
365 lines (285 loc) · 11.3 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/env python3
"""
python/variable_inspector.py - Main backend entry point
Runs as a separate process to inspect Python variables
"""
import sys
import json
import io
from contextlib import redirect_stdout, redirect_stderr
from inspector import get_all_variables, get_variable_details
# Global namespace for executed code
exec_namespace = {}
def _inject_main_locals_capture(code):
"""
Injects code to expose main() local variables after it's called.
Uses AST transformation to add globals().update(locals()) at the end of main().
"""
import ast
import sys
try:
tree = ast.parse(code)
# Find and modify main() function
main_found = False
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) and node.name == 'main':
main_found = True
# Add code to expose locals at the end of main()
expose_stmt = ast.parse(
"globals().update({k: v for k, v in locals().items() if not k.startswith('_')})"
).body[0]
node.body.append(expose_stmt)
if not main_found:
return code
# Convert back to code using ast.unparse (Python 3.9+)
if sys.version_info >= (3, 9):
return ast.unparse(tree)
else:
# For older Python, just return original code
return code
except (SyntaxError, Exception):
# If AST modification fails, return original code
return code
def run_python_file(file_path, capture_main_locals=False):
"""Execute a Python file and capture variables
Args:
file_path: Path to the Python file to execute
capture_main_locals: If True, expose local variables from main() function
"""
global exec_namespace
try:
with open(file_path, 'r') as f:
code = f.read()
# Inject code to capture main() locals if enabled
if capture_main_locals:
code = _inject_main_locals_capture(code)
# Set __name__ to '__main__' so if __name__ == '__main__' blocks execute
exec_namespace['__name__'] = '__main__'
exec_namespace['__file__'] = file_path
# Capture stdout/stderr
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
exec(code, exec_namespace)
# Get variables after execution
variables = get_all_variables(exec_namespace)
response = {
'status': 'success',
'variables': variables,
'stdout': stdout_capture.getvalue(),
'stderr': stderr_capture.getvalue()
}
except Exception as e:
response = {
'status': 'error',
'error': str(e),
'variables': []
}
return response
def run_python_code(code, capture_main_locals=False):
"""Execute Python code string and capture variables
Args:
code: Python code string to execute
capture_main_locals: If True, expose local variables from main() function
"""
global exec_namespace
try:
# Inject code to capture main() locals if enabled
if capture_main_locals:
code = _inject_main_locals_capture(code)
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
exec(code, exec_namespace)
variables = get_all_variables(exec_namespace)
response = {
'status': 'success',
'variables': variables,
'stdout': stdout_capture.getvalue(),
'stderr': stderr_capture.getvalue()
}
except Exception as e:
response = {
'status': 'error',
'error': str(e),
'variables': get_all_variables(exec_namespace)
}
return response
def update_variable(var_name, var_type, new_value):
"""Update a variable value in the execution namespace"""
global exec_namespace
if var_name not in exec_namespace:
return {'status': 'error', 'error': f'Variable {var_name} not found'}
try:
# Convert the string value to the appropriate type
type_lower = var_type.lower()
if type_lower == 'bool':
# Handle boolean conversion
if new_value.lower() in ('true', '1', 'yes'):
converted_value = True
elif new_value.lower() in ('false', '0', 'no'):
converted_value = False
else:
return {'status': 'error', 'error': f'Invalid boolean value: {new_value}'}
elif type_lower in ('int', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64'):
converted_value = int(new_value)
elif type_lower in ('float', 'float16', 'float32', 'float64'):
converted_value = float(new_value)
elif type_lower == 'complex':
converted_value = complex(new_value)
elif type_lower == 'str':
converted_value = new_value
else:
return {'status': 'error', 'error': f'Type {var_type} is not editable'}
# Update the variable
exec_namespace[var_name] = converted_value
# Return updated variables list
from inspector import get_all_variables
variables = get_all_variables(exec_namespace)
return {'status': 'success', 'variables': variables}
except (ValueError, SyntaxError) as e:
return {'status': 'error', 'error': f'Invalid value for type {var_type}: {str(e)}'}
def clear_namespace():
"""Clear all variables from the execution namespace"""
global exec_namespace
# Keep built-in variables but clear user-defined ones
keys_to_delete = [key for key in exec_namespace.keys() if not key.startswith('_')]
for key in keys_to_delete:
del exec_namespace[key]
return {'status': 'success', 'message': 'Namespace cleared', 'variables': []}
def save_session(file_path):
"""Save the current session variables to a pickle file"""
global exec_namespace
import pickle
# Try to use dill if available (handles more types)
try:
import dill
serializer = dill
serializer_name = 'dill'
except ImportError:
serializer = pickle
serializer_name = 'pickle'
# Filter out non-picklable and internal variables
saved_vars = {}
skipped_vars = []
for name, value in exec_namespace.items():
# Skip internal variables
if name.startswith('_'):
continue
# Skip modules, functions, and classes (usually not what users want to save)
if isinstance(value, type) or callable(value):
# But allow lambda and simple functions if using dill
if serializer_name != 'dill' or isinstance(value, type):
skipped_vars.append({'name': name, 'reason': 'callable/type'})
continue
# Try to pickle the variable
try:
serializer.dumps(value)
saved_vars[name] = value
except Exception as e:
skipped_vars.append({'name': name, 'reason': str(e)[:50]})
if not saved_vars:
return {
'status': 'error',
'error': 'No variables could be saved. All variables are either internal or not serializable.'
}
try:
with open(file_path, 'wb') as f:
serializer.dump(saved_vars, f)
return {
'status': 'success',
'saved_count': len(saved_vars),
'saved_vars': list(saved_vars.keys()),
'skipped_vars': skipped_vars,
'serializer': serializer_name
}
except Exception as e:
return {
'status': 'error',
'error': f'Failed to save session: {str(e)}'
}
def load_session(file_path):
"""Load session variables from a pickle file"""
global exec_namespace
import pickle
# Try to use dill if available
try:
import dill
serializer = dill
serializer_name = 'dill'
except ImportError:
serializer = pickle
serializer_name = 'pickle'
try:
with open(file_path, 'rb') as f:
loaded_vars = serializer.load(f)
if not isinstance(loaded_vars, dict):
return {
'status': 'error',
'error': 'Invalid session file format. Expected a dictionary of variables.'
}
# Add loaded variables to namespace
loaded_count = 0
for name, value in loaded_vars.items():
exec_namespace[name] = value
loaded_count += 1
# Get updated variables list
variables = get_all_variables(exec_namespace)
return {
'status': 'success',
'loaded_count': loaded_count,
'loaded_vars': list(loaded_vars.keys()),
'variables': variables,
'serializer': serializer_name
}
except Exception as e:
return {
'status': 'error',
'error': f'Failed to load session: {str(e)}'
}
def main():
"""Main loop to process commands from VS Code"""
sys.stderr.write("Variable Inspector Backend Started\n")
sys.stderr.flush()
while True:
try:
line = sys.stdin.readline()
if not line:
break
command = json.loads(line.strip())
if command['command'] == 'run_file':
capture_main = command.get('capture_main_locals', False)
response = run_python_file(command['file'], capture_main)
print(json.dumps(response), flush=True)
elif command['command'] == 'run_code':
capture_main = command.get('capture_main_locals', False)
response = run_python_code(command['code'], capture_main)
print(json.dumps(response), flush=True)
elif command['command'] == 'get_variables':
variables = get_all_variables(exec_namespace)
response = {'variables': variables}
print(json.dumps(response), flush=True)
elif command['command'] == 'get_details':
path = command.get('path', None)
details = get_variable_details(command['name'], exec_namespace, path)
print(json.dumps(details), flush=True)
elif command['command'] == 'update_variable':
response = update_variable(command['name'], command['type'], command['value'])
print(json.dumps(response), flush=True)
elif command['command'] == 'clear_namespace':
response = clear_namespace()
print(json.dumps(response), flush=True)
elif command['command'] == 'save_session':
response = save_session(command['file'])
print(json.dumps(response), flush=True)
elif command['command'] == 'load_session':
response = load_session(command['file'])
print(json.dumps(response), flush=True)
except Exception as e:
error_response = {
'status': 'error',
'error': str(e)
}
print(json.dumps(error_response), flush=True)
if __name__ == '__main__':
main()