-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsilent_launcher.py
More file actions
100 lines (83 loc) · 2.98 KB
/
silent_launcher.py
File metadata and controls
100 lines (83 loc) · 2.98 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
import subprocess
import sys
import os
import argparse
import signal
import psutil
import atexit
def cleanup_process(process):
"""
Cleanup a process and all its children
"""
try:
parent = psutil.Process(process.pid)
children = parent.children(recursive=True)
# Kill children processes
for child in children:
try:
child.kill()
except psutil.NoSuchProcess:
pass
# Kill parent process
try:
parent.kill()
except psutil.NoSuchProcess:
pass
except (psutil.NoSuchProcess, AttributeError):
pass
def resource_path(relative_path):
""" Get absolute path to resource (works for dev and PyInstaller .exe) """
try:
# When bundled by PyInstaller
base_path = sys._MEIPASS
except AttributeError:
# When running from source
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def run_silently(script_path):
"""
Run a Python script silently without showing the terminal window.
Args:
script_path (str): Path to the Python script to run
"""
# Convert to absolute path if relative
script_path = os.path.abspath(script_path)
if not os.path.exists(script_path):
error_msg = f"Error: Script not found: {script_path}"
with open("error_log.txt", "w") as f:
f.write(error_msg)
print(error_msg)
return False
try:
# Use pythonw for GUI scripts to avoid console window
process = subprocess.Popen(
['pythonw', script_path] + sys.argv[2:], # Forward any additional arguments
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW # Windows-specific: ensures no console window
)
# Register cleanup function to be called on exit
atexit.register(cleanup_process, process)
# Handle signals for clean shutdown
signal.signal(signal.SIGTERM, lambda signo, frame: cleanup_process(process))
signal.signal(signal.SIGINT, lambda signo, frame: cleanup_process(process))
# Wait for the process to complete
process.wait()
return True
except Exception as e:
error_msg = f"Error running script: {str(e)}"
with open("error_log.txt", "w") as f:
f.write(error_msg)
print(error_msg)
return False
def main():
parser = argparse.ArgumentParser(description='Run a Python script silently without showing the terminal window.')
parser.add_argument('script', help='Path to the Python script to run')
if len(sys.argv) < 2:
parser.print_help()
sys.exit(1)
args = parser.parse_args([sys.argv[1]]) # Only parse the script path
success = run_silently(args.script)
sys.exit(0 if success else 1)
if __name__ == '__main__':
main()