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,15 @@ 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'."""
50- cmd , * args = cmd_str .split ()
52+ cmd , remainder = cmd_str .split (" " , 1 )
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+ # For eval, preserve the remainder as a single string argument
57+ args = [remainder .strip ()] if cmd == "eval" else remainder .split (" " )
58+ return job_cls (cmd , args , client_id , globals = globals )
5559
5660
5761class SequentialJob (Job ):
@@ -282,6 +286,39 @@ async def reboot_callback(op):
282286 return BytesIO (msg .encode ("utf-8" ))
283287
284288
289+ class RunPyJob (Job ):
290+ """A job to evaluate Python script on the device."""
291+
292+ argc = 1
293+
294+ def output (self ):
295+ """Eval or exec given Python and return the result."""
296+ expr = self .args [0 ]
297+ try :
298+ result = self .do_eval (expr )
299+ except SyntaxError : # Not an expression, try exec
300+ result = self .do_exec (expr )
301+ return BytesIO (result .encode ("utf-8" ))
302+
303+ def do_eval (self , expr ):
304+ """Evaluate a Python expression and return the result."""
305+ op = compile (expr , "<string>" , "eval" )
306+ result = eval (op , self .globals , None )
307+ return repr (result )
308+
309+ def do_exec (self , expr ):
310+ """Execute a Python statement and return the output."""
311+ out_buf = BytesIO ()
312+ old_term = os .dupterm (out_buf )
313+ try :
314+ op = compile (expr , "<string>" , "exec" )
315+ exec (op , self .globals , None )
316+ result = out_buf .getvalue ()
317+ finally :
318+ os .dupterm (old_term )
319+ return result
320+
321+
285322# Map commands to associated job names
286323COMMANDS = {
287324 "whoami" : WhoAmIJob ,
@@ -291,4 +328,5 @@ async def reboot_callback(op):
291328 "cp" : PutFileJob ,
292329 "ota" : FirmwareUpdateJob ,
293330 "reboot" : RebootJob ,
331+ "eval" : RunPyJob ,
294332}
0 commit comments