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,31 @@ def ready(self):
4547 return True
4648
4749 @classmethod
48- def from_cmd (cls , cmd_str , client_id = None ):
49- """Create a job from a command string, e.g. 'get_file file1.txt'."""
50- cmd , * args = cmd_str .split ()
50+ def from_cmd (cls , cmd_str , client_id = None , globals = {}):
51+ """Create a job from a command string, e.g. 'cat file1.txt'."""
52+ # Split command string into command and following arguments
53+ try :
54+ cmd , remainder = cmd_str .split (" " , 1 )
55+ except ValueError :
56+ cmd , remainder = cmd_str , None
57+
58+ # Lookup command in command table
5159 if cmd not in COMMANDS :
5260 raise ValueError (f"Unknown command: '{ cmd } '" )
5361 job_cls = COMMANDS [cmd ]
54- return job_cls (cmd , args , client_id )
62+
63+ # For eval, preserve the remainder as a single string argument and de-quote it
64+ # Otherwise, split remainder into separate arguments
65+ if remainder :
66+ if cmd == "eval" :
67+ args = [remainder .strip ("\" \' " )]
68+ else :
69+ args = remainder .split (" " )
70+ else :
71+ args = []
72+
73+ # Create and return the job instance
74+ return job_cls (cmd , args , client_id , globals = globals )
5575
5676
5777class SequentialJob (Job ):
@@ -282,6 +302,39 @@ async def reboot_callback(op):
282302 return BytesIO (msg .encode ("utf-8" ))
283303
284304
305+ class RunPyJob (Job ):
306+ """A job to evaluate Python script on the device."""
307+
308+ argc = 1
309+
310+ def output (self ):
311+ """Eval or exec given Python and return the result."""
312+ expr = self .args [0 ]
313+ try :
314+ result = self .do_eval (expr )
315+ except SyntaxError : # Not an expression, try exec
316+ result = self .do_exec (expr )
317+ return BytesIO (result .encode ("utf-8" ))
318+
319+ def do_eval (self , expr ):
320+ """Evaluate a Python expression and return the result."""
321+ op = compile (expr , "<string>" , "eval" )
322+ result = eval (op , self .globals , None )
323+ return repr (result )
324+
325+ def do_exec (self , expr ):
326+ """Execute a Python statement and return the output."""
327+ out_buf = BytesIO ()
328+ old_term = os .dupterm (out_buf )
329+ try :
330+ op = compile (expr , "<string>" , "exec" )
331+ exec (op , self .globals , None )
332+ result = out_buf .getvalue ()
333+ finally :
334+ os .dupterm (old_term )
335+ return result
336+
337+
285338# Map commands to associated job names
286339COMMANDS = {
287340 "whoami" : WhoAmIJob ,
@@ -291,4 +344,5 @@ async def reboot_callback(op):
291344 "cp" : PutFileJob ,
292345 "ota" : FirmwareUpdateJob ,
293346 "reboot" : RebootJob ,
347+ "eval" : RunPyJob ,
294348}
0 commit comments