Skip to content

Commit de1fcc3

Browse files
committed
Fix bare exceptions and replace print with logging
mkconcore.py: - Replace 13 bare except: with except (FileNotFoundError, IOError) as e: - Adds actual error message to logs for better debugging concore.py: - Add import logging with basic configuration - Replace 25+ print() statements with appropriate logging levels - logging.info() for status messages - logging.warning() for retries and non-critical issues - logging.error() for errors and failures This improves debugging experience and follows Python best practices.
1 parent 3b6756b commit de1fcc3

2 files changed

Lines changed: 61 additions & 56 deletions

File tree

concore.py

Lines changed: 37 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import time
2+
import logging
23
import os
34
from ast import literal_eval
45
import sys
56
import re
6-
import zmq # Added for ZeroMQ
7+
import zmq
8+
logging.basicConfig(
9+
level=logging.INFO,
10+
format='%(levelname)s - %(message)s'
11+
) # Added for ZeroMQ
712

813
# if windows, create script to kill this process
914
# because batch files don't provide easy way to know pid of last command
@@ -36,10 +41,10 @@ def __init__(self, port_type, address, zmq_socket_type):
3641
# Bind or connect
3742
if self.port_type == "bind":
3843
self.socket.bind(address)
39-
print(f"ZMQ Port bound to {address}")
44+
logging.info(f"ZMQ Port bound to {address}")
4045
else:
4146
self.socket.connect(address)
42-
print(f"ZMQ Port connected to {address}")
47+
logging.info(f"ZMQ Port connected to {address}")
4348

4449
def send_json_with_retry(self, message):
4550
"""Send JSON message with retries if timeout occurs."""
@@ -48,9 +53,9 @@ def send_json_with_retry(self, message):
4853
self.socket.send_json(message)
4954
return
5055
except zmq.Again:
51-
print(f"Send timeout (attempt {attempt + 1}/5)")
56+
logging.warning(f"Send timeout (attempt {attempt + 1}/5)")
5257
time.sleep(0.5)
53-
print("Failed to send after retries.")
58+
logging.error("Failed to send after retries.")
5459
return
5560

5661
def recv_json_with_retry(self):
@@ -59,9 +64,9 @@ def recv_json_with_retry(self):
5964
try:
6065
return self.socket.recv_json()
6166
except zmq.Again:
62-
print(f"Receive timeout (attempt {attempt + 1}/5)")
67+
logging.warning(f"Receive timeout (attempt {attempt + 1}/5)")
6368
time.sleep(0.5)
64-
print("Failed to receive after retries.")
69+
logging.error("Failed to receive after retries.")
6570
return None
6671

6772
# Global ZeroMQ ports registry
@@ -76,28 +81,28 @@ def init_zmq_port(port_name, port_type, address, socket_type_str):
7681
socket_type_str (str): String representation of ZMQ socket type (e.g., "REQ", "REP", "PUB", "SUB").
7782
"""
7883
if port_name in zmq_ports:
79-
print(f"ZMQ Port {port_name} already initialized.")
84+
logging.info(f"ZMQ Port {port_name} already initialized.")
8085
return # Avoid reinitialization
8186

8287
try:
8388
# Map socket type string to actual ZMQ constant (e.g., zmq.REQ, zmq.REP)
8489
zmq_socket_type = getattr(zmq, socket_type_str.upper())
8590
zmq_ports[port_name] = ZeroMQPort(port_type, address, zmq_socket_type)
86-
print(f"Initialized ZMQ port: {port_name} ({socket_type_str}) on {address}")
91+
logging.info(f"Initialized ZMQ port: {port_name} ({socket_type_str}) on {address}")
8792
except AttributeError:
88-
print(f"Error: Invalid ZMQ socket type string '{socket_type_str}'.")
93+
logging.error(f"Error: Invalid ZMQ socket type string '{socket_type_str}'.")
8994
except zmq.error.ZMQError as e:
90-
print(f"Error initializing ZMQ port {port_name} on {address}: {e}")
95+
logging.error(f"Error initializing ZMQ port {port_name} on {address}: {e}")
9196
except Exception as e:
92-
print(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}")
97+
logging.error(f"An unexpected error occurred during ZMQ port initialization for {port_name}: {e}")
9398

9499
def terminate_zmq():
95100
for port in zmq_ports.values():
96101
try:
97102
port.socket.close()
98103
port.context.term()
99104
except Exception as e:
100-
print(f"Error while terminating ZMQ port {port.address}: {e}")
105+
logging.error(f"Error while terminating ZMQ port {port.address}: {e}")
101106
# --- ZeroMQ Integration End ---
102107

103108
# ===================================================================
@@ -142,13 +147,13 @@ def safe_literal_eval(filename, defaultValue):
142147

143148
# Convert key=value;key2=value2 to Python dict format
144149
if sparams != '{' and not (sparams.startswith('{') and sparams.endswith('}')): # Check if it needs conversion
145-
print("converting sparams: "+sparams)
150+
logging.debug("converting sparams: "+sparams)
146151
sparams = "{'"+re.sub(';',",'",re.sub('=',"':",re.sub(' ','',sparams)))+"}"
147-
print("converted sparams: " + sparams)
152+
logging.debug("converted sparams: " + sparams)
148153
try:
149154
params = literal_eval(sparams)
150155
except Exception as e:
151-
print(f"bad params content: {sparams}, error: {e}")
156+
logging.warning(f"bad params content: {sparams}, error: {e}")
152157
params = dict()
153158
else:
154159
params = dict()
@@ -206,17 +211,17 @@ def read(port_identifier, name, initstr_val):
206211
message = zmq_p.recv_json_with_retry()
207212
return message
208213
except zmq.error.ZMQError as e:
209-
print(f"ZMQ read error on port {port_identifier} (name: {name}): {e}. Returning default.")
214+
logging.error(f"ZMQ read error on port {port_identifier} (name: {name}): {e}. Returning default.")
210215
return default_return_val
211216
except Exception as e:
212-
print(f"Unexpected error during ZMQ read on port {port_identifier} (name: {name}): {e}. Returning default.")
217+
logging.error(f"Unexpected error during ZMQ read on port {port_identifier} (name: {name}): {e}. Returning default.")
213218
return default_return_val
214219

215220
# Case 2: File-based port
216221
try:
217222
file_port_num = int(port_identifier)
218223
except ValueError:
219-
print(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
224+
logging.error(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
220225
return default_return_val
221226

222227
time.sleep(delay)
@@ -229,7 +234,7 @@ def read(port_identifier, name, initstr_val):
229234
except FileNotFoundError:
230235
ins = str(initstr_val)
231236
except Exception as e:
232-
print(f"Error reading {file_path}: {e}. Using default value.")
237+
logging.error(f"Error reading {file_path}: {e}. Using default value.")
233238
return default_return_val
234239

235240
# Retry logic if file is empty
@@ -241,12 +246,12 @@ def read(port_identifier, name, initstr_val):
241246
with open(file_path, "r") as infile:
242247
ins = infile.read()
243248
except Exception as e:
244-
print(f"Retry {attempts + 1}: Error reading {file_path} - {e}")
249+
logging.warning(f"Retry {attempts + 1}: Error reading {file_path} - {e}")
245250
attempts += 1
246251
retrycount += 1
247252

248253
if len(ins) == 0:
249-
print(f"Max retries reached for {file_path}, using default value.")
254+
logging.error(f"Max retries reached for {file_path}, using default value.")
250255
return default_return_val
251256

252257
s += ins
@@ -260,10 +265,10 @@ def read(port_identifier, name, initstr_val):
260265
simtime = max(simtime, current_simtime_from_file)
261266
return inval[1:]
262267
else:
263-
print(f"Warning: Unexpected data format in {file_path}: {ins}. Returning raw content or default.")
268+
logging.warning(f"Warning: Unexpected data format in {file_path}: {ins}. Returning raw content or default.")
264269
return inval
265270
except Exception as e:
266-
print(f"Error parsing content from {file_path} ('{ins}'): {e}. Returning default.")
271+
logging.error(f"Error parsing content from {file_path} ('{ins}'): {e}. Returning default.")
267272
return default_return_val
268273

269274

@@ -280,9 +285,9 @@ def write(port_identifier, name, val, delta=0):
280285
try:
281286
zmq_p.send_json_with_retry(val)
282287
except zmq.error.ZMQError as e:
283-
print(f"ZMQ write error on port {port_identifier} (name: {name}): {e}")
288+
logging.error(f"ZMQ write error on port {port_identifier} (name: {name}): {e}")
284289
except Exception as e:
285-
print(f"Unexpected error during ZMQ write on port {port_identifier} (name: {name}): {e}")
290+
logging.error(f"Unexpected error during ZMQ write on port {port_identifier} (name: {name}): {e}")
286291

287292
# Case 2: File-based port
288293
try:
@@ -292,14 +297,14 @@ def write(port_identifier, name, val, delta=0):
292297
file_port_num = int(port_identifier)
293298
file_path = os.path.join(outpath+str(file_port_num), name)
294299
except ValueError:
295-
print(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
300+
logging.error(f"Error: Invalid port identifier '{port_identifier}' for file operation. Must be integer or ZMQ name.")
296301
return
297302

298303
# File writing rules
299304
if isinstance(val, str):
300305
time.sleep(2 * delay) # string writes wait longer
301306
elif not isinstance(val, list):
302-
print(f"File write to {file_path} must have list or str value, got {type(val)}")
307+
logging.error(f"File write to {file_path} must have list or str value, got {type(val)}")
303308
return
304309

305310
try:
@@ -311,7 +316,7 @@ def write(port_identifier, name, val, delta=0):
311316
else:
312317
outfile.write(val)
313318
except Exception as e:
314-
print(f"Error writing to {file_path}: {e}")
319+
logging.error(f"Error writing to {file_path}: {e}")
315320

316321
def initval(simtime_val_str):
317322
"""
@@ -327,12 +332,12 @@ def initval(simtime_val_str):
327332
simtime = first_element
328333
return val[1:]
329334
else:
330-
print(f"Error: First element in initval string '{simtime_val_str}' is not a number. Using data part as is or empty.")
335+
logging.error(f"Error: First element in initval string '{simtime_val_str}' is not a number. Using data part as is or empty.")
331336
return val[1:] if len(val) > 1 else []
332337
else:
333-
print(f"Error: initval string '{simtime_val_str}' is not a list or is empty. Returning empty list.")
338+
logging.error(f"Error: initval string '{simtime_val_str}' is not a list or is empty. Returning empty list.")
334339
return []
335340

336341
except Exception as e:
337-
print(f"Error parsing simtime_val_str '{simtime_val_str}': {e}. Returning empty list.")
342+
logging.error(f"Error parsing simtime_val_str '{simtime_val_str}': {e}. Returning empty list.")
338343
return []

mkconcore.py

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,8 @@
413413
fsource = open(CONCOREPATH+"/concoredocker.py")
414414
else:
415415
fsource = open(CONCOREPATH+"/concore.py")
416-
except:
417-
logging.error(f"{CONCOREPATH} is not correct path to concore")
416+
except (FileNotFoundError, IOError) as e:
417+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
418418
quit()
419419
with open(outdir+"/src/concore.py","w") as fcopy:
420420
fcopy.write(fsource.read())
@@ -426,8 +426,8 @@
426426
fsource = open(CONCOREPATH+"/concoredocker.hpp")
427427
else:
428428
fsource = open(CONCOREPATH+"/concore.hpp")
429-
except:
430-
logging.error(f"{CONCOREPATH} is not correct path to concore")
429+
except (FileNotFoundError, IOError) as e:
430+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
431431
quit()
432432
with open(outdir+"/src/concore.hpp","w") as fcopy:
433433
fcopy.write(fsource.read())
@@ -439,8 +439,8 @@
439439
fsource = open(CONCOREPATH+"/concoredocker.v")
440440
else:
441441
fsource = open(CONCOREPATH+"/concore.v")
442-
except:
443-
logging.error(f"{CONCOREPATH} is not correct path to concore")
442+
except (FileNotFoundError, IOError) as e:
443+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
444444
quit()
445445
with open(outdir+"/src/concore.v","w") as fcopy:
446446
fcopy.write(fsource.read())
@@ -449,8 +449,8 @@
449449
#copy mkcompile into /src 5/27/21
450450
try:
451451
fsource = open(CONCOREPATH+"/mkcompile")
452-
except:
453-
logging.error(f"{CONCOREPATH} is not correct path to concore")
452+
except (FileNotFoundError, IOError) as e:
453+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
454454
quit()
455455
with open(outdir+"/src/mkcompile","w") as fcopy:
456456
fcopy.write(fsource.read())
@@ -460,56 +460,56 @@
460460
#copy concore*.m into /src 4/2/21
461461
try: #maxtime in matlab 11/22/21
462462
fsource = open(CONCOREPATH+"/concore_default_maxtime.m")
463-
except:
464-
logging.error(f"{CONCOREPATH} is not correct path to concore")
463+
except (FileNotFoundError, IOError) as e:
464+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
465465
quit()
466466
with open(outdir+"/src/concore_default_maxtime.m","w") as fcopy:
467467
fcopy.write(fsource.read())
468468
fsource.close()
469469
try:
470470
fsource = open(CONCOREPATH+"/concore_unchanged.m")
471-
except:
472-
logging.error(f"{CONCOREPATH} is not correct path to concore")
471+
except (FileNotFoundError, IOError) as e:
472+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
473473
quit()
474474
with open(outdir+"/src/concore_unchanged.m","w") as fcopy:
475475
fcopy.write(fsource.read())
476476
fsource.close()
477477
try:
478478
fsource = open(CONCOREPATH+"/concore_read.m")
479-
except:
480-
logging.error(f"{CONCOREPATH} is not correct path to concore")
479+
except (FileNotFoundError, IOError) as e:
480+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
481481
quit()
482482
with open(outdir+"/src/concore_read.m","w") as fcopy:
483483
fcopy.write(fsource.read())
484484
fsource.close()
485485
try:
486486
fsource = open(CONCOREPATH+"/concore_write.m")
487-
except:
488-
logging.error(f"{CONCOREPATH} is not correct path to concore")
487+
except (FileNotFoundError, IOError) as e:
488+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
489489
quit()
490490
with open(outdir+"/src/concore_write.m","w") as fcopy:
491491
fcopy.write(fsource.read())
492492
fsource.close()
493493
try: #4/9/21
494494
fsource = open(CONCOREPATH+"/concore_initval.m")
495-
except:
496-
logging.error(f"{CONCOREPATH} is not correct path to concore")
495+
except (FileNotFoundError, IOError) as e:
496+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
497497
quit()
498498
with open(outdir+"/src/concore_initval.m","w") as fcopy:
499499
fcopy.write(fsource.read())
500500
fsource.close()
501501
try: #11/19/21
502502
fsource = open(CONCOREPATH+"/concore_iport.m")
503-
except:
504-
logging.error(f"{CONCOREPATH} is not correct path to concore")
503+
except (FileNotFoundError, IOError) as e:
504+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
505505
quit()
506506
with open(outdir+"/src/concore_iport.m","w") as fcopy:
507507
fcopy.write(fsource.read())
508508
fsource.close()
509509
try: #11/19/21
510510
fsource = open(CONCOREPATH+"/concore_oport.m")
511-
except:
512-
logging.error(f"{CONCOREPATH} is not correct path to concore")
511+
except (FileNotFoundError, IOError) as e:
512+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
513513
quit()
514514
with open(outdir+"/src/concore_oport.m","w") as fcopy:
515515
fcopy.write(fsource.read())
@@ -519,8 +519,8 @@
519519
fsource = open(CONCOREPATH+"/import_concoredocker.m")
520520
else:
521521
fsource = open(CONCOREPATH+"/import_concore.m")
522-
except:
523-
logging.error(f"{CONCOREPATH} is not correct path to concore")
522+
except (FileNotFoundError, IOError) as e:
523+
logging.error(f"{CONCOREPATH} is not correct path to concore: {e}")
524524
quit()
525525
with open(outdir+"/src/import_concore.m","w") as fcopy:
526526
fcopy.write(fsource.read())

0 commit comments

Comments
 (0)