-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDraft_Basic_WebServer.py
127 lines (109 loc) · 4.3 KB
/
Draft_Basic_WebServer.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
import os
import sys
import time
import subprocess
import threading
import signal
import webbrowser
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
server = None
stop_event = threading.Event()
# Function to handle signals
def signal_handler(signal, frame):
logging.info("Web Server Shutting Down.")
if server:
server.shutdown()
stop_event.set()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Function to monitor script changes
def monitor_script(script_path):
last_modified = os.path.getmtime(script_path)
while not stop_event.is_set():
time.sleep(1)
current_modified = os.path.getmtime(script_path)
if current_modified != last_modified:
logging.info("Script modified! Restarting...")
os.execv(sys.executable, [sys.executable] + sys.argv)
break
last_modified = current_modified
# Function to start HTTP server
class RedirectHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
response = (
f"<html><head><title>https://pythonbasics.org</title></head>"
f"<body><p>TestRequest: {self.path}</p>"
f"<p>This is an example web server.</p></body></html>"
).encode("utf-8")
self.wfile.write(response)
logging.info(f"Handled request for {self.path}")
def start_server():
global server
address = ('127.0.0.1', 8000)
server = ThreadingHTTPServer(address, RedirectHandler)
logging.info("Web Server Started on: " + address[0] + ":" + str(address[1]))
server.serve_forever()
def listen_for_enter():
while True:
command = input().strip().lower() # Wait for Enter key press
if command == "stop":
logging.info("Stopping the server...")
if server:
server.shutdown()
logging.info("Server stopped.")
stop_event.set()
with open('stop_flag.txt', 'w') as f:
f.write('stop')
os._exit(0) # Force exit the program
elif command == "":
webbrowser.open('http://127.0.0.1:8000')
elif command == "open":
webbrowser.open('http://127.0.0.1:8000')
# Wrapper function to restart the script
def restart_script():
while True:
if os.path.exists('stop_flag.txt'):
logging.info("Stop flag detected. Exiting restart loop.")
os.remove('stop_flag.txt')
break
process = subprocess.Popen([sys.executable, __file__], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
# Real-time output handling
def output_reader(pipe, pipe_name):
with pipe:
for line in iter(pipe.readline, ''):
print(f"[{pipe_name}] {line}", end='')
stdout_thread = threading.Thread(target=output_reader, args=(process.stdout, 'STDOUT'))
stderr_thread = threading.Thread(target=output_reader, args=(process.stderr, 'STDERR'))
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
process.wait()
if process.returncode != 0:
logging.error("Script error. Press Enter to restart the script.")
input() # Wait for Enter key press to restart the script
if __name__ == "__main__":
if 'WRAPPER_RUN' not in os.environ:
os.environ['WRAPPER_RUN'] = '1'
restart_script()
else:
script_path = __file__
monitor_thread = threading.Thread(target=monitor_script, args=(script_path,))
monitor_thread.daemon = True
monitor_thread.start()
server_thread = threading.Thread(target=start_server)
server_thread.daemon = True
server_thread.start()
input_thread = threading.Thread(target=listen_for_enter)
input_thread.daemon = True
input_thread.start()
# Keep the main thread running, otherwise signals are ignored.
while not stop_event.is_set():
time.sleep(1)