Skip to content

Instantly share code, notes, and snippets.

@jieran233
Created May 17, 2024 23:21
Show Gist options
  • Save jieran233/168835cf53e00e00a336962df7ce6686 to your computer and use it in GitHub Desktop.
Save jieran233/168835cf53e00e00a336962df7ce6686 to your computer and use it in GitHub Desktop.
import os
import psutil
import subprocess
import logging
# Set up basic logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def find_weasel_server():
"""
Search for the WeaselServer executable within the Rime directory located
in either Program Files or Program Files (x86).
"""
# Define the environment variables to look for Program Files directories
program_files_environ = ['ProgramFiles', 'ProgramFiles(x86)']
rime_dir = 'Rime'
found_rimes = []
# Search for the Rime directory in the specified environment variables
for environ in program_files_environ:
if environ in os.environ:
rime_path = os.path.join(os.environ[environ], rime_dir)
if os.path.exists(rime_path):
found_rimes.append(rime_path)
if not found_rimes:
logging.error("Rime directory not found.")
return None
# Define the criteria for finding the WeaselServer executable
weasel_dir_startswith = 'weasel-'
weasel_server_exec = 'WeaselServer.exe'
found_weasel_server = None
# Search for the WeaselServer executable in the Rime directory
for item in os.listdir(found_rimes[0]):
item_path = os.path.join(found_rimes[0], item)
if os.path.isdir(item_path) and item.startswith(weasel_dir_startswith):
weasel_server_path = os.path.join(item_path, weasel_server_exec)
if os.path.exists(weasel_server_path):
found_weasel_server = weasel_server_path
break
if not found_weasel_server:
logging.error("WeaselServer.exe not found.")
return found_weasel_server
def on_process_terminate(proc):
"""
Callback function called when the monitored process terminates.
Logs the process termination and indicates a restart.
"""
logging.info(f"Process {proc.pid} terminated. Restarting...")
def main(weasel_server_path):
"""
Main function to start the WeaselServer and monitor its status.
If the server process terminates, it will be restarted.
"""
if not weasel_server_path:
logging.error("WeaselServer not found.")
return
while True:
try:
# Start the WeaselServer process
weasel_server_dir = os.path.split(weasel_server_path)[0]
proc = subprocess.Popen([weasel_server_path], cwd=weasel_server_dir)
# Monitor the process using psutil
ps_process = psutil.Process(proc.pid)
ps_process.wait()
# Handle process termination
on_process_terminate(ps_process)
except Exception as e:
logging.error(f"Error occurred: {e}")
if __name__ == "__main__":
# Find the WeaselServer path and start the main function
main(find_weasel_server())
@jieran233
Copy link
Author

Just create a basic task in Task Scheduler:

  • WeaselServer
  • Triggered when the current user logs in
  • Start program, pythonw.exe, Args "<path\to\weasel-daemon.py>"

pythonw is for running python scripts without command prompt window. Read more: https://stackoverflow.com/a/66055185

Then modify properties:

  • No elevation required
  • Set trigger delay if issues occur
  • Uncheck all conditions
  • Uncheck the stop the task if it runs for a long time option
  • Check the automatically restart the task upon failure option

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment