2121 pyb.exec('pyb.LED(1).on()')
2222 pyb.exit_raw_repl()
2323
24+ Note: if using Python2 then pyb.exec must be written as pyb.exec_.
2425To run a script from the local machine on the board and print out the results:
2526
2627 import pyboard
3940import sys
4041import time
4142
43+ try :
44+ stdout = sys .stdout .buffer
45+ except AttributeError :
46+ # Python2 doesn't have buffer attr
47+ stdout = sys .stdout
48+
4249def stdout_write_bytes (b ):
43- sys . stdout . buffer .write (b )
44- sys . stdout . buffer .flush ()
50+ stdout .write (b )
51+ stdout .flush ()
4552
4653class PyboardError (BaseException ):
4754 pass
@@ -208,11 +215,11 @@ def exec_raw(self, command, timeout=10, data_consumer=None):
208215 return self .follow (timeout , data_consumer )
209216
210217 def eval (self , expression ):
211- ret = self .exec ('print({})' .format (expression ))
218+ ret = self .exec_ ('print({})' .format (expression ))
212219 ret = ret .strip ()
213220 return ret
214221
215- def exec (self , command ):
222+ def exec_ (self , command ):
216223 ret , ret_err = self .exec_raw (command )
217224 if ret_err :
218225 raise PyboardError ('exception' , ret , ret_err )
@@ -221,12 +228,16 @@ def exec(self, command):
221228 def execfile (self , filename ):
222229 with open (filename , 'rb' ) as f :
223230 pyfile = f .read ()
224- return self .exec (pyfile )
231+ return self .exec_ (pyfile )
225232
226233 def get_time (self ):
227234 t = str (self .eval ('pyb.RTC().datetime()' ), encoding = 'utf8' )[1 :- 1 ].split (', ' )
228235 return int (t [4 ]) * 3600 + int (t [5 ]) * 60 + int (t [6 ])
229236
237+ # in Python2 exec is a keyword so one must use "exec_"
238+ # but for Python3 we want to provide the nicer version "exec"
239+ setattr (Pyboard , "exec" , Pyboard .exec_ )
240+
230241def execfile (filename , device = '/dev/ttyACM0' , baudrate = 115200 , user = 'micro' , password = 'python' ):
231242 pyb = Pyboard (device , baudrate , user , password )
232243 pyb .enter_raw_repl ()
0 commit comments