-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram_B.py
151 lines (118 loc) · 4.44 KB
/
program_B.py
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
import subprocess
import threading
import queue
import sys
import os
import argparse
STDOUT_TIMEOUT = 1
DEBUG = False
def read_stdout(proc, output_queue):
for line in iter(proc.stdout.readline, ''):
output_queue.put(line)
proc.stdout.close()
def start_process(program_name):
if not os.path.exists(str(program_name)):
print(f"Program {program_name} does not exist.")
return None, None
if program_name.endswith('.kt'):
print("Compiling Kotlin program...")
compile_proc = subprocess.run(['kotlinc', program_name, '-include-runtime', '-d', 'program_A.jar'])
if compile_proc.returncode != 0:
print(f"Failed to compile {program_name}")
return None, None
print("Kotlin program compiled successfully.")
proc = subprocess.Popen(['java', '-jar', 'program_A.jar'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
elif program_name.endswith('.py'):
proc = subprocess.Popen(['python', program_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
elif program_name.endswith('.jar'):
proc = subprocess.Popen(['java', '-jar', program_name], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
else:
print(f"Unsupported file type: {program_name}")
return None, None
output_queue = queue.Queue()
threading.Thread(target=read_stdout, args=(proc, output_queue), daemon=True).start()
return proc, output_queue
class Controller:
def __init__(self, program_name=None):
self.program_name = program_name
self.rng_proc, self.output_queue = start_process(program_name)
if self.rng_proc is None:
sys.exit(1)
def get_response(self):
try:
rng_response = self.output_queue.get(timeout=STDOUT_TIMEOUT).strip()
return rng_response
except queue.Empty:
# Timeout, RNG did not respond
return None
def send_command(self, command):
self.rng_proc.stdin.write(command + '\n')
self.rng_proc.stdin.flush()
return self.get_response()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('program_name', type=str, help='The program to run (e.g., program_a.py, program_a.kt, program_a.jar)')
args = parser.parse_args()
controller = Controller(args.program_name)
random_numbers = []
ping_response = controller.send_command("Hi")
if ping_response != "Hi":
print("Program A did not respond correctly.")
controller.send_command("Shutdown")
return
for _ in range(100):
number = controller.send_command("GetRandom")
random_numbers.append(int(number))
controller.send_command("Shutdown")
# Doing the work
random_numbers.sort()
print(f"Sorted random numbers: {random_numbers}")
if len(random_numbers) % 2 == 0:
median = (random_numbers[len(random_numbers) // 2 - 1] + random_numbers[len(random_numbers) // 2]) / 2
else:
median = random_numbers[len(random_numbers) // 2]
print(f"Median: {median}")
def debug():
PROGRAMS = {
"1": "program_a.py",
"2": "program_a.kt",
"3": "program_a.jar"
}
while True:
print("Debug mode:")
print("""Select a program to run:
1. program_a.py
2. program_a.kt
3. program_a.jar
4. Custom program name
5. Exit
""")
choice = input("Enter your choice: ")
if choice == '5':
print("Exiting.")
return
elif choice == '4':
program_name = input("Enter the program name: ")
controller = Controller(program_name)
break
elif choice in PROGRAMS:
program_name = PROGRAMS.get(choice)
controller = Controller(program_name)
break
else:
print("Invalid choice.")
continue
print("Running " + controller.program_name)
print("Available commands: Hi, GetRandom, Shutdown")
while True:
command = input("Enter a command: ")
response = controller.send_command(command)
print(f"Response:\n{response}")
if command == 'Shutdown':
print("Shutting down.")
break
if __name__ == "__main__":
if DEBUG:
debug()
else:
main()