-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor_primes.py
More file actions
85 lines (73 loc) · 3.41 KB
/
monitor_primes.py
File metadata and controls
85 lines (73 loc) · 3.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import csv
import time
import os
from collections import deque
LOG_FILE_PATH = "prime_logfile.csv"
REFRESH_INTERVAL_SECONDS = 60
MAX_RECENT_PRIMES_DISPLAY = 10
def clear_console():
"""Clears the console screen."""
os.system('cls' if os.name == 'nt' else 'clear')
def read_prime_log():
"""Reads the prime log file and returns total count and recent primes."""
primes_found = []
try:
with open(LOG_FILE_PATH, 'r', newline='') as csvfile:
reader = csv.DictReader(csvfile)
# Ensure all expected columns are present, otherwise it's not a valid log or empty
expected_headers = ['timestamp', 'k', 'n', 'N_hex'] # Add more if needed for validation
if not reader.fieldnames or not all(header in reader.fieldnames for header in expected_headers):
# print(f"Waiting for valid log file with headers: {', '.join(expected_headers)}")
return 0, []
for row in reader:
try:
# Extract required fields. N_hex might be long, so display last part.
n_hex_full = row.get('N_hex', 'N/A')
n_hex_display = "..." + n_hex_full[-16:] if len(n_hex_full) > 16 else n_hex_full
primes_found.append({
'timestamp': row.get('timestamp', 'N/A'),
'k': row.get('k', 'N/A'),
'n': row.get('n', 'N/A'),
'N_hex': n_hex_display
})
except KeyError as e:
print(f"Warning: Missing expected column {e} in a row. Skipping row.")
except Exception as e:
print(f"Warning: Error processing a row: {e}. Skipping row.")
except FileNotFoundError:
# print(f"Log file '{LOG_FILE_PATH}' not found. Waiting...")
return 0, []
except Exception as e:
print(f"Error reading log file: {e}")
return 0, []
total_primes = len(primes_found)
# Get the last MAX_RECENT_PRIMES_DISPLAY primes using a deque for efficiency if list is huge
# For moderate sized lists, simple slicing is fine.
recent_primes = primes_found[-MAX_RECENT_PRIMES_DISPLAY:]
return total_primes, recent_primes
def display_stats(total_primes, recent_primes):
"""Displays the prime statistics to the console."""
clear_console()
print(f"--- Proth Prime Monitor --- ({time.strftime('%Y-%m-%d %H:%M:%S')}) ---")
print(f"Log File: {LOG_FILE_PATH}\n")
print(f"Total Proth Primes Found: {total_primes}\n")
if recent_primes:
print(f"Last {len(recent_primes)} Prime(s) Found:")
# Determine column widths for N_hex if needed, or just print
for prime in reversed(recent_primes): # Show most recent first
print(f" Timestamp: {prime['timestamp']}, k: {prime['k']}, n: {prime['n']}, N: {prime['N_hex']}")
else:
if total_primes == 0:
print("No primes found yet.")
print(f"\n--- (Refreshing in {REFRESH_INTERVAL_SECONDS} seconds) ---")
def main():
"""Main loop to monitor and display prime log stats."""
while True:
total_primes, recent_primes = read_prime_log()
display_stats(total_primes, recent_primes)
time.sleep(REFRESH_INTERVAL_SECONDS)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nMonitor stopped by user.")