-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
181 lines (149 loc) · 6.12 KB
/
parser.py
File metadata and controls
181 lines (149 loc) · 6.12 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import subprocess
import json
import sys
import select
import os
def parse_output(line: str):
"""
Parse the output of the terminal into a JSON object
Args:
line (str): string to parse
Returns:
dict: parsed JSON data
"""
try:
parsed_data: dict = json.loads(line)
return parsed_data
except (json.JSONDecodeError, ValueError):
print(f"Failed to parse line: {line}")
return None
def upload_code():
"""
Run the PROS make-upload command to build and upload code
Returns:
int: Return code of the upload process
"""
print("\n=== UPLOADING CODE ===")
try:
# Run pros mu command and stream output in real-time
process = subprocess.Popen(
"pros mu",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
text=True,
bufsize=1,
universal_newlines=True
)
# Stream output in real-time
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
return_code = process.poll()
if return_code == 0:
print("=== UPLOAD SUCCESSFUL ===\n")
else:
print(f"=== UPLOAD FAILED (Exit Code: {return_code}) ===\n")
return return_code
except Exception as e:
print(f"Error during upload: {e}")
return -1
def run_terminal_and_parse(command="pros t"):
"""
Run the PROS terminal command and stream the output line by line as a generator
Supports interactive upload by typing 'u' and pressing enter
Args:
command (str, optional): command to run terminal. Defaults to "pros t".
Yields:
dict: parsed data
"""
print("PROS Terminal started. Type 'u' and press Enter to upload code.")
print("Press Ctrl+C to exit.\n")
process = None
try:
while True:
# Start or restart the pros t process
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.DEVNULL, # Prevents input echo to subprocess
shell=True,
text=True
)
# Read the output line by line
while True:
# Use select to efficiently check for both subprocess output and user input
if os.name != 'nt': # Unix/Linux/macOS
ready, _, _ = select.select([process.stdout, sys.stdin], [], [], 0.01)
if sys.stdin in ready:
user_input = sys.stdin.readline().strip().lower()
if user_input == 'u':
print("\n=== STOPPING TERMINAL ===")
process.terminate()
process.wait()
# Upload code
upload_code()
print("=== RESTARTING TERMINAL ===")
break # Break inner loop to restart pros t
if process.stdout in ready:
line = process.stdout.readline()
if line:
line = line.strip()
if line: # Skip empty lines
result = parse_output(line)
if result:
yield result
else: # Windows - use simpler polling approach
import msvcrt
# Check for user input (Windows)
if msvcrt.kbhit():
char = msvcrt.getch().decode('utf-8').lower()
if char == 'u':
# Wait for Enter key
while True:
if msvcrt.kbhit():
next_char = msvcrt.getch().decode('utf-8')
if next_char == '\r': # Enter key
print("\n=== STOPPING TERMINAL ===")
process.terminate()
process.wait()
# Upload code
upload_code()
print("=== RESTARTING TERMINAL ===")
break
break # Break inner loop to restart pros t
# Check if process is still running
if process.poll() is not None:
print("Terminal process ended unexpectedly. Restarting...")
break
# Try to read a line from subprocess
try:
line = process.stdout.readline()
if line:
line = line.strip()
if line: # Skip empty lines
result = parse_output(line)
if result:
yield result
except Exception:
continue
except KeyboardInterrupt:
print("\nTerminated by user.")
finally:
if process:
process.terminate()
process.wait()
# Test if data is being parsed correctly
if __name__ == "__main__":
command = "pros t"
print("Testing PROS terminal with upload functionality...")
print("Type 'u' and press Enter to trigger upload.")
print("Press Ctrl+C to exit.")
print()
for result in run_terminal_and_parse(command):
if result:
print(f"Parsed telemetry: {result}")