Skip to content

Commit c68190a

Browse files
committed
Update Exception handling and fstring fixes
1 parent 6891fab commit c68190a

File tree

5 files changed

+58
-26
lines changed

5 files changed

+58
-26
lines changed

PyBasic/interpreter.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,18 @@
2727
from lexer import Lexer
2828
from program import Program
2929
from sys import stderr,implementation
30+
try:
31+
from traceback import print_exception
32+
except:
33+
from sys import print_exception as sysprexcept
34+
print_exception = lambda err,value=None,tb=None: sysprexcept(err)
3035
from os import listdir,rename,remove
3136
import gc
3237
try:
3338
from pydos_ui import input
3439
except:
3540
pass
3641

37-
if implementation.name.upper() == 'MICROPYTHON':
38-
from sys import print_exception
39-
4042
gc.collect()
4143
if 'threshold' in dir(gc):
4244
gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
@@ -239,7 +241,5 @@ def main(passedIn=""):
239241

240242
# Trap all exceptions so that interpreter keeps running
241243
except Exception as e:
242-
if implementation.name.upper() == 'MICROPYTHON':
243-
print_exception(e)
244-
else:
245-
print(e)
244+
print_exception(e,e, \
245+
e.__traceback__ if hasattr(e,'__traceback__') else None)

PyDOS.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@
44
except:
55
sep = os.getcwd()[0]
66
from time import localtime
7-
from sys import stdin,implementation,path,print_exception
7+
from sys import stdin,implementation,path
8+
try:
9+
from traceback import print_exception,format_exception
10+
except:
11+
from sys import print_exception as sysprexcept
12+
print_exception = lambda err,value=None,tb=None: sysprexcept(err)
13+
format_exception = lambda err,value=None,tb=None: [err]
814
if not sep+'lib' in path:
915
path.insert(1,sep+'lib')
1016
path.append(sep+'PyBasic')
@@ -67,7 +73,7 @@ def PyDOS():
6773
global envVars
6874
if "envVars" not in globals().keys():
6975
envVars = {}
70-
_VER = "1.40"
76+
_VER = "1.41"
7177
prmpVals = ['>','(',')','&','|','\x1b','\b','<','=',' ',_VER,'\n','$','']
7278

7379
print("Starting Py-DOS...")
@@ -138,8 +144,10 @@ def exCmd(cFile,passedIn):
138144
else:
139145
exec(f"passedIn = '{passedIn}'\n{cf.read()}")
140146
except Exception as err:
141-
print_exception(err)
142-
envVars['lasterror'] = err
147+
print_exception(err,err, \
148+
err.__traceback__ if hasattr(err,'__traceback__') else None)
149+
envVars['lasterror'] = format_exception(err,err, \
150+
err.__traceback__ if hasattr(err,'__traceback__') else None)
143151
except KeyboardInterrupt:
144152
print("^C")
145153

@@ -222,7 +230,7 @@ def dirLoop(tmpDir,lastDir,isFile,swPause,swWide,swRecur,prSum, \
222230
lastDir = ""
223231

224232
if dirPat is None:
225-
(quit,nLines) = scrnPause(swPause,nLines,["",f"Directory of {dPath.replace('/',('\\' if envVars.get('DIRSEP','/') == '\\' else '/'))}"])
233+
(quit,nLines) = scrnPause(swPause,nLines,["","Directory of "+dPath.replace('/',('\\' if envVars.get('DIRSEP','/') == '\\' else '/'))])
226234
dirHeadPrntd = True
227235
nDirs += 2
228236
if swWide:
@@ -236,7 +244,7 @@ def dirLoop(tmpDir,lastDir,isFile,swPause,swWide,swRecur,prSum, \
236244
else:
237245
scrAdj1 = 52 - min(scrWdth,52)
238246
(quit,nLines) = scrnPause(swPause,nLines, \
239-
[f".{" "*(23-scrAdj1)}<DIR>",f"..{" "*(22-scrAdj1)}<DIR>"])
247+
[f'.{" "*(23-scrAdj1)}<DIR>',f'..{" "*(22-scrAdj1)}<DIR>'])
240248

241249
for _dir in sorted([srtFnc(x,pFmt(dPath)) for x in os.listdir(dPath)]):
242250
_dir = _dir.split('*')[1]
@@ -267,7 +275,7 @@ def dirLoop(tmpDir,lastDir,isFile,swPause,swWide,swRecur,prSum, \
267275
wideCount += 1
268276
if not ForD:
269277
(quit,nLines) = scrnPause(swPause,nLines, \
270-
[f"[{_dir[:13]}]{" "*(14-len(_dir[:13]))}"],"")
278+
[f'[{_dir[:13]}]{" "*(14-len(_dir[:13]))}'],"")
271279
else:
272280
(quit,nLines) = scrnPause(swPause,nLines, \
273281
[_dir[:15]+" "*(16-len(_dir[:15]))],"")
@@ -278,11 +286,11 @@ def dirLoop(tmpDir,lastDir,isFile,swPause,swWide,swRecur,prSum, \
278286
scrAdj1 = 52 - min(scrWdth,52)
279287
scrAdj2 = min(13,65-min(scrWdth,65))
280288
(quit,nLines) = scrnPause(swPause,nLines, \
281-
[f"{_dir[:max(8,scrWdth-26)]}{" "*(24-len(_dir)-scrAdj1)}<DIR>{" "*(18-scrAdj2)}{fTime[1]:02}-{fTime[2]:02}-{fTime[0]:04} {fTime[3]:02}:{fTime[4]:02}"])
289+
[f'{_dir[:max(8,scrWdth-26)]}{" "*(24-len(_dir)-scrAdj1)}<DIR>{" "*(18-scrAdj2)}{fTime[1]:02}-{fTime[2]:02}-{fTime[0]:04} {fTime[3]:02}:{fTime[4]:02}'])
282290
else:
283291
scrAdj1 = 65 - min(scrWdth,65)
284292
(quit,nLines) = scrnPause(swPause,nLines, \
285-
[f"{_dir[:max(8,scrWdth-20-len(fSize))]}{" "*(36-len(_dir)+10-len(fSize)-scrAdj1)}{fSize} {fTime[1]:02}-{fTime[2]:02}-{fTime[0]:04} {fTime[3]:02}:{fTime[4]:02}"])
293+
[f'{_dir[:max(8,scrWdth-20-len(fSize))]}{" "*(36-len(_dir)+10-len(fSize)-scrAdj1)}{fSize} {fTime[1]:02}-{fTime[2]:02}-{fTime[0]:04} {fTime[3]:02}:{fTime[4]:02}'])
286294

287295
if quit:
288296
break
@@ -316,8 +324,8 @@ def dirLoop(tmpDir,lastDir,isFile,swPause,swWide,swRecur,prSum, \
316324

317325
scrAdj1 = 65 - min(scrWdth,65)
318326
(quit,nLines) = scrnPause(swPause,nLines, \
319-
[(f"{" "*(4-len(str(nFiles)))} {nFiles} File(s){" "*(32-len(str(tFSize))-scrAdj1)} {tFSize} Bytes.")[:scrWdth], \
320-
(f"{" "*(4-len(str(nDirs)))} {nDirs} Dir(s){" "*(33-len(str(availDisk))-scrAdj1)} {availDisk} Bytes free.")[:scrWdth],""],"")
327+
[(f'{" "*(4-len(str(nFiles)))} {nFiles} File(s){" "*(32-len(str(tFSize))-scrAdj1)} {tFSize} Bytes.')[:scrWdth], \
328+
(f'{" "*(4-len(str(nDirs)))} {nDirs} Dir(s){" "*(33-len(str(availDisk))-scrAdj1)} {availDisk} Bytes free.')[:scrWdth],""],"")
321329

322330
return (nLines,nFiles,tFSize,nDirs,quit)
323331

@@ -637,7 +645,7 @@ def readBATFile(BATfile):
637645
print(f'The current date is: {"MonTueWedThuFriSatSun"[i:i+3]} {localtime()[1]:02}/{localtime()[2]:02}/{localtime()[0]:04}')
638646

639647
elif cmd == "TIME":
640-
print(f"The current time is: {localtime()[3]%12}:{localtime()[4]:02}:{localtime()[5]:02} {["AM","PM"][localtime()[3]//12]}")
648+
print(f'The current time is: {localtime()[3]%12}:{localtime()[4]:02}:{localtime()[5]:02} {["AM","PM"][localtime()[3]//12]}')
641649

642650
elif cmd == "MEM":
643651
gc.collect()

blink.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,16 @@
1212

1313
def blink(ledPin=None):
1414
cmnd = ""
15+
minus = False
1516

1617
if ledPin == None or ledPin == "":
1718
ledPin = Pydos_hw.led
1819
elif sys.implementation.name.upper() == 'CIRCUITPYTHON':
1920
ledPin = getattr(board,str(ledPin).upper().replace("'","").replace('"',''))
2021
else:
22+
if type(ledPin) == str:
23+
if ledPin[:1] == '-':
24+
minus = True
2125
try:
2226
ledPin = int(ledPin)
2327
except:
@@ -26,8 +30,8 @@ def blink(ledPin=None):
2630

2731

2832
# Micropython: pass a negative pin value if the led turns off with a value of 1
29-
if type(ledPin) == int and ledPin < 0:
30-
ledPin = -ledPin
33+
if (type(ledPin) == int and ledPin < 0) or minus:
34+
ledPin = abs(ledPin)
3135
ledOff = True
3236
else:
3337
ledOff = False
@@ -111,4 +115,3 @@ def blink(ledPin=None):
111115
blink(passedIn)
112116
else:
113117
print("Enter 'blink.blink(pinNo=Default)' in the REPL to run.")
114-
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# PyDOS Board Configuration for 'Adafruit Feather HUZZAH ESP32'
2+
3+
Pydos_pins = {
4+
'sndPin' : (16,"D16 GPIO16"),
5+
'led' : (-2,"D2 GPIO2"),
6+
'I2C_NUM' : (1,None),
7+
'SCL' : (5,"SCL GPIO5"),
8+
'SDA' : (4,"SDA GPIO4"),
9+
'SPI_NUM' : [(0,None)],
10+
'SCK' : [(14,"SCK GPIO14")],
11+
'MOSI' : [(13,"MO GPIO13")],
12+
'MISO' : [(12,"MI GPIO12")],
13+
'CS' : [(15,"D15 GPIO15")]
14+
}

sdmount.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
from sys import implementation
22
from pydos_hw import Pydos_hw
33
import os
4+
try:
5+
from traceback import print_exception
6+
except:
7+
from sys import print_exception as sysprexcept
8+
print_exception = lambda err,value=None,tb=None: sysprexcept(err)
49

510
if implementation.name.upper() == "MICROPYTHON":
6-
from sys import print_exception
711
from machine import Pin
812
try:
913
from machine import SDCard
@@ -128,7 +132,8 @@ def do_mount(drive,spiNo):
128132
Pydos_hw.SDdrive[spiNo] = drive
129133
sdMounted = True
130134
except Exception as e:
131-
print_exception(e)
135+
print_exception(e,e, \
136+
e.__traceback__ if hasattr(e,'__traceback__') else None)
132137

133138
elif implementation.name.upper() == "CIRCUITPYTHON":
134139

@@ -149,7 +154,8 @@ def do_mount(drive,spiNo):
149154
Pydos_hw.SDdrive[sdioNo] = drive
150155
sdMounted = True
151156
except Exception as e:
152-
print('SD-Card: Fail,', e)
157+
print_exception(e,e, \
158+
e.__traceback__ if hasattr(e,'__traceback__') else None)
153159
elif spiNo+1 > len(Pydos_hw.CS):
154160
print("CS Pin not allocated for Pydos_bcfg SPI interface #",spiNo)
155161
elif Pydos_hw.SDdrive[spiNo] != None:
@@ -165,7 +171,8 @@ def do_mount(drive,spiNo):
165171
Pydos_hw.SDdrive[spiNo] = drive
166172
sdMounted = True
167173
except Exception as e:
168-
print('SD-Card: Fail,', e)
174+
print_exception(e,e, \
175+
e.__traceback__ if hasattr(e,'__traceback__') else None)
169176

170177
if sdMounted:
171178
print(drive+" mounted")

0 commit comments

Comments
 (0)