11import asyncio
22import logging
3+ import os
34from binascii import hexlify
45from hashlib import sha256
56from io import BytesIO
@@ -22,6 +23,7 @@ def __init__(self, cmd, args=[], client_id="localhost", **kwargs):
2223 f"Wrong number of arguments for { cmd } ; expected { self .argc } "
2324 )
2425
26+ self .globals = kwargs .get ("globals" , {})
2527 self .cmd = cmd
2628 self .args = args
2729 self .client_id = client_id
@@ -45,13 +47,13 @@ def ready(self):
4547 return True
4648
4749 @classmethod
48- def from_cmd (cls , cmd_str , client_id = None ):
50+ def from_cmd (cls , cmd_str , client_id = None , globals = {} ):
4951 """Create a job from a command string, e.g. 'get_file file1.txt'."""
5052 cmd , * args = cmd_str .split ()
5153 if cmd not in COMMANDS :
5254 raise ValueError (f"Unknown command: '{ cmd } '" )
5355 job_cls = COMMANDS [cmd ]
54- return job_cls (cmd , args , client_id )
56+ return job_cls (cmd , args , client_id , globals = globals )
5557
5658
5759class SequentialJob (Job ):
@@ -282,6 +284,39 @@ async def reboot_callback(op):
282284 return BytesIO (msg .encode ("utf-8" ))
283285
284286
287+ class RunPyJob (Job ):
288+ """A job to evaluate Python script on the device."""
289+
290+ argc = 1
291+
292+ def output (self ):
293+ """Eval or exec given Python and return the result."""
294+ expr = self .args [0 ]
295+ try :
296+ result = self .do_eval (expr )
297+ except SyntaxError : # Not an expression, try exec
298+ result = self .do_exec (expr )
299+ return BytesIO (result .encode ("utf-8" ))
300+
301+ def do_eval (self , expr ):
302+ """Evaluate a Python expression and return the result."""
303+ op = compile (expr , "<string>" , "eval" )
304+ result = eval (op , self .globals , None )
305+ return repr (result )
306+
307+ def do_exec (self , expr ):
308+ """Execute a Python statement and return the output."""
309+ out_buf = BytesIO ()
310+ old_term = os .dupterm (out_buf )
311+ try :
312+ op = compile (expr , "<string>" , "exec" )
313+ exec (op , self .globals , None )
314+ result = out_buf .getvalue ()
315+ finally :
316+ os .dupterm (old_term )
317+ return result
318+
319+
285320# Map commands to associated job names
286321COMMANDS = {
287322 "whoami" : WhoAmIJob ,
@@ -291,4 +326,5 @@ async def reboot_callback(op):
291326 "cp" : PutFileJob ,
292327 "ota" : FirmwareUpdateJob ,
293328 "reboot" : RebootJob ,
329+ "eval" : RunPyJob ,
294330}
0 commit comments