-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_runner_gui.py
More file actions
1790 lines (1526 loc) · 87.8 KB
/
script_runner_gui.py
File metadata and controls
1790 lines (1526 loc) · 87.8 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Script Runner - Manage & Automate Scripts
# Built by SmaRTy Saini
# LinkedIn: https://www.linkedin.com/in/smartysaini/
# GitHub: https://github.com/SmaRTy-Saini/
# Store: https://smartysaini.gumroad.com/
import sys
import subprocess
import threading
import os
import json
import csv
import platform
import signal
from datetime import datetime
import psutil # For process management (pause/resume)
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore # For persistent scheduling
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QPushButton, QFileDialog, QVBoxLayout,
QHBoxLayout, QWidget, QTableWidget, QTableWidgetItem, QTextEdit, QMessageBox,
QInputDialog, QLineEdit, QLabel, QComboBox, QTabWidget, QSplitter, QProgressBar,
QHeaderView, QDialog, QDateTimeEdit, QFormLayout, QSpinBox
)
from PyQt5.QtGui import QIcon, QTextCharFormat, QColor, QFont, QPixmap
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QThread, QMutex, QTimer, QDateTime
# Get a writable config directory inside AppData
APPDATA_DIR = os.path.join(os.getenv("APPDATA"), "ScriptRunner")
os.makedirs(APPDATA_DIR, exist_ok=True) # Ensure it exists
# Define all important paths inside the writable directory
CONFIG_FILE = os.path.join(APPDATA_DIR, "scripts_config.json")
LOG_FILE = os.path.join(APPDATA_DIR, "script_logs.txt")
SCHEDULE_DB = os.path.join(APPDATA_DIR, "schedule.sqlite")
INTERPRETER_SETTINGS_FILE = os.path.join(APPDATA_DIR, "interpreter_settings.json")
WINDOW = None
def run_scheduled_script(script):
global WINDOW
if WINDOW is None:
print("Window not initialized")
return
WINDOW.run_script_scheduled(script)
class OutputEmitter(QObject):
output_signal = pyqtSignal(str, str)
status_signal = pyqtSignal(str, str) # path, status
progress_signal = pyqtSignal(int)
class ScriptExecutionThread(QThread):
def __init__(self, script, parameters, emitter, main_window):
super().__init__()
self.script = script
self.parameters = parameters
self.emitter = emitter
self.main_window = main_window
self.process = None
self.is_paused = False
self.is_stopped = False
self.mutex = QMutex() # Mutex for this thread's internal state (is_paused, is_stopped)
def run(self):
script_path = self.script['path']
script_type = self.script['type']
self.emitter.status_signal.emit(script_path, "Running")
self.emitter.output_signal.emit(f"\n[START] {self.script.get('tag', '')} {os.path.basename(script_path)}\n", "blue")
interpreter_path = self.main_window.get_interpreter_path(script_type)
cmd = []
try:
if script_type == "Python":
cmd = [interpreter_path, script_path]
elif script_type == "PowerShell":
if platform.system() == "Windows":
cmd = [interpreter_path, "-ExecutionPolicy", "Bypass", "-File", script_path]
else: # PowerShell Core for Linux/Mac
cmd = [interpreter_path, "-File", script_path]
elif script_type == "Batch":
if platform.system() == "Windows":
cmd = [script_path]
else:
self.emitter.output_signal.emit("Batch files are native to Windows and not directly supported on this platform.\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, "Batch files not supported on non-Windows platforms")
return
elif script_type == "Shell":
if platform.system() != "Windows":
cmd = [interpreter_path, script_path]
else:
self.emitter.output_signal.emit("Shell scripts (.sh) are typically for Unix-like systems. On Windows, consider using Git Bash or WSL.\n", "orange")
cmd = [interpreter_path, script_path] # Fallback to attempting 'bash' directly
elif script_type == "Go":
# For Go, we usually run the source file directly or a compiled executable
if script_path.endswith(".go"):
cmd = [interpreter_path, "run", script_path]
else: # Assume it's a compiled executable
cmd = [script_path]
elif script_type == "Rust":
# For Rust, similar to Go, run source via cargo or a compiled executable
if os.path.basename(script_path) == "Cargo.toml" or os.path.isdir(script_path):
# If it's a Cargo.toml or a directory, assume it's a Rust project
cmd = [interpreter_path, "run", "--manifest-path", os.path.join(script_path, "Cargo.toml") if os.path.isdir(script_path) else script_path]
# Change CWD to the script's directory for cargo to find project
self.process_cwd = os.path.dirname(script_path) if not os.path.isdir(script_path) else script_path
else: # Assume it's a compiled executable
cmd = [script_path]
elif script_type == "Java":
if script_path.lower().endswith(".jar"):
cmd = [interpreter_path, "-jar", script_path]
elif script_path.lower().endswith(".java"):
# For .java, first compile then run. This might be tricky in one go.
# Best practice is to compile outside, or provide a .class path.
# For simplicity, this assumes a compiled .class in a standard location
# A more advanced approach would compile on the fly.
class_name = os.path.splitext(os.path.basename(script_path))[0]
class_dir = os.path.dirname(script_path)
cmd = [interpreter_path, "-cp", class_dir, class_name]
else:
self.emitter.output_signal.emit("Unsupported Java file type. Please provide a .jar or .java file (and ensure it's compiled or handle compilation manually).\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, "Unsupported Java file type.")
return
elif script_type == "Ruby":
cmd = [interpreter_path, script_path]
elif script_type == "C#":
# For C#, typically execute a compiled .exe on Windows
if platform.system() == "Windows":
if script_path.lower().endswith(".exe"):
cmd = [script_path]
elif os.path.basename(script_path).lower() == "csproj" or script_path.lower().endswith(".csproj"):
# If it's a .NET project file, use dotnet run
cmd = [interpreter_path, "run", "--project", script_path]
self.process_cwd = os.path.dirname(script_path) # CWD to project directory
else:
self.emitter.output_signal.emit("Unsupported C# file type. Please provide a compiled .exe or a .csproj file.\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, "Unsupported C# file type.")
return
else: # For Linux/Mac, try with 'mono' or 'dotnet'
# User needs to ensure mono or dotnet is installed and configured
if script_path.lower().endswith(".exe"): # Mono executable
cmd = [interpreter_path, script_path]
elif os.path.basename(script_path).lower() == "csproj" or script_path.lower().endswith(".csproj"):
cmd = [interpreter_path, "run", "--project", script_path]
self.process_cwd = os.path.dirname(script_path)
else:
self.emitter.output_signal.emit("Unsupported C# file type for non-Windows. Provide a compiled .exe (for Mono) or a .csproj file (for dotnet).\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, "Unsupported C# file type.")
return
else:
self.emitter.output_signal.emit(f"Unsupported script type: {script_type}.\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, f"Unsupported script type: {script_type}")
return
if self.parameters:
cmd.extend(self.parameters.split())
# Define CWD for subprocess, especially important for Go/Rust/C# projects
cwd_for_process = getattr(self, 'process_cwd', None) # Get if set, else None
# Create process
# Add shell=True for batch files on Windows if cmd is just the script path
shell_needed = script_type == "Batch" and platform.system() == "Windows" and len(cmd) == 1
self.process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, # Merge stdout and stderr for simpler reading
text=True,
bufsize=1, # Line-buffered
universal_newlines=True,
shell=shell_needed, # Only for batch files and cases where shell is truly needed
cwd=cwd_for_process # Set working directory if defined
)
# Verify process was created successfully
if self.process is None:
self.emitter.output_signal.emit("[ERROR] Failed to create process\n", "red")
self.emitter.status_signal.emit(script_path, "Error")
self.write_log(script_path, -1, "Failed to create process")
return
# Handle output reading differently based on platform
try:
if platform.system() == "Windows":
self._read_output_windows()
else:
self._read_output_unix()
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Output reading failed: {str(e)}. Falling back to simpler read.\n", "red")
self._read_output_fallback()
if not self.is_stopped and self.process:
try:
self.process.wait()
exit_code = self.process.returncode
if exit_code == 0:
self.emitter.output_signal.emit(f"[SUCCESS] Finished with code {exit_code}\n", "green")
else:
self.emitter.output_signal.emit(f"[ERROR] Finished with code {exit_code}\n", "red")
self.write_log(script_path, exit_code)
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Process wait failed: {str(e)}\n", "red")
self.write_log(script_path, -1, str(e))
else:
self.emitter.output_signal.emit("[STOPPED] Script execution stopped by user\n", "orange")
self.write_log(script_path, -1, "Stopped by user")
except FileNotFoundError:
error_msg = f"Command not found: '{cmd[0]}'. Please ensure the required interpreter is installed and its path is configured in Settings (⚙️)."
self.emitter.output_signal.emit(f"[ERROR] {error_msg}\n", "red")
self.write_log(script_path, -1, error_msg)
except PermissionError:
error_msg = f"Permission denied to execute '{script_path}'. Check file permissions or run Script Runner as administrator."
self.emitter.output_signal.emit(f"[ERROR] {error_msg}\n", "red")
self.write_log(script_path, -1, error_msg)
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] {str(e)}\n", "red")
self.write_log(script_path, -1, str(e))
finally:
self.emitter.status_signal.emit(script_path, "Idle")
# Ensure process is truly dead after completion/error
if self.process and self.process.poll() is None:
try:
self.process.kill()
except:
pass
def _read_output_windows(self):
"""Windows-specific output reading with proper pause/resume support"""
if not self.process or not self.process.stdout:
self.emitter.output_signal.emit("[ERROR] No process or stdout available for Windows output reading\n", "red")
return
import queue
import threading
output_queue = queue.Queue()
def reader_thread_func():
try:
for line in iter(self.process.stdout.readline, ''):
if line:
output_queue.put(line.rstrip())
else:
break
output_queue.put(None) # Signal end of stream
except Exception as e:
output_queue.put(f"[ERROR] Reader thread error: {e}")
reader = threading.Thread(target=reader_thread_func, daemon=True)
reader.start()
psutil_imported = False
try:
import psutil
psutil_imported = True
except ImportError:
self.emitter.output_signal.emit("[WARNING] 'psutil' not found. Process pause/resume will be flag-based only.\n", "orange")
while True:
self.mutex.lock() # Lock for is_stopped, is_paused
stopped = self.is_stopped
paused = self.is_paused
self.mutex.unlock()
if stopped:
try:
if self.process and self.process.poll() is None:
self.process.terminate()
self.process.wait(timeout=1) # Give a moment to terminate
if self.process.poll() is None:
self.process.kill()
except Exception as e:
self.emitter.output_signal.emit(f"[STOP ERROR] {str(e)}\n", "red")
break
# Handle pause state (suspend/resume actual process)
if paused:
if psutil_imported and self.process and self.process.poll() is None:
try:
proc = psutil.Process(self.process.pid)
proc.suspend()
except psutil.NoSuchProcess:
break # Process already ended
except Exception as e:
self.emitter.output_signal.emit(f"[PAUSE WARNING] psutil suspend failed: {str(e)}\n", "orange")
self.msleep(100) # Sleep while paused
continue # Skip output reading while paused
else: # Not paused, try to resume if it was suspended
if psutil_imported and self.process and self.process.poll() is None:
try:
proc = psutil.Process(self.process.pid)
proc.resume()
except psutil.NoSuchProcess:
pass # Process already ended
except Exception as e:
self.emitter.output_signal.emit(f"[RESUME WARNING] psutil resume failed: {str(e)}\n", "orange")
try:
line = output_queue.get(timeout=0.05) # Small timeout to allow checks
if line is None: # End signal from reader thread
break
color = self.get_output_color(line)
self.emitter.output_signal.emit(line, color)
except queue.Empty:
if not reader.is_alive() and (self.process is None or self.process.poll() is None):
# Reader thread finished and process completed, no more output expected
break
continue
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Output processing failed: {str(e)}\n", "red")
break
# After loop, ensure reader thread is joined
if reader.is_alive():
reader.join(timeout=1) # Give it a moment to finish
def _read_output_unix(self):
"""Unix-specific output reading with select for non-blocking I/O"""
if not self.process or not self.process.stdout:
self.emitter.output_signal.emit("[ERROR] No process or stdout available for Unix output reading\n", "red")
return
try:
import select
import fcntl
import os
fd = self.process.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
buffer = ""
while True:
self.mutex.lock()
stopped = self.is_stopped
paused = self.is_paused
self.mutex.unlock()
if stopped:
try:
if self.process and self.process.poll() is None:
self.process.terminate()
self.process.wait(timeout=1)
if self.process.poll() is None:
self.process.kill()
except Exception as e:
self.emitter.output_signal.emit(f"[STOP ERROR] {str(e)}\n", "red")
break
if paused:
if self.process and self.process.poll() is None:
try:
os.kill(self.process.pid, signal.SIGSTOP)
except Exception as e:
self.emitter.output_signal.emit(f"[PAUSE WARNING] Failed to SIGSTOP process: {str(e)}\n", "orange")
self.msleep(100)
continue
else:
if self.process and self.process.poll() is None:
try:
os.kill(self.process.pid, signal.SIGCONT)
except Exception as e:
self.emitter.output_signal.emit(f"[RESUME WARNING] Failed to SIGCONT process: {str(e)}\n", "orange")
try:
ready, _, _ = select.select([self.process.stdout], [], [], 0.05)
if ready:
try:
chunk = self.process.stdout.read(4096)
if chunk:
buffer += chunk
while '\n' in buffer:
line, buffer = buffer.split('\n', 1)
if line.strip():
color = self.get_output_color(line.strip())
self.emitter.output_signal.emit(line.strip(), color)
else:
break
except BlockingIOError:
pass
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Reading stdout chunk failed: {str(e)}\n", "red")
break
if self.process.poll() is None:
if buffer.strip():
color = self.get_output_color(buffer.strip())
self.emitter.output_signal.emit(buffer.strip(), color)
break
except select.error as e:
if e.errno != 4:
self.emitter.output_signal.emit(f"[ERROR] Select error: {str(e)}\n", "red")
break
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Unix output reading failed: {str(e)}. Falling back.\n", "red")
self._read_output_fallback()
except Exception as e: # This handles exceptions during the setup of Unix reading (e.g., import errors)
self.emitter.output_signal.emit(f"[ERROR] Initialization of Unix reading failed: {str(e)}\n", "red")
self._read_output_fallback() # Fallback also for init errors
def _read_output_fallback(self):
"""Fallback method for basic output reading (blocking)"""
try:
if not self.process or not self.process.stdout:
self.emitter.output_signal.emit("[ERROR] No process or stdout available for fallback output reading\n", "red")
return
for line in iter(self.process.stdout.readline, ''):
self.mutex.lock()
stopped = self.is_stopped
paused = self.is_paused
self.mutex.unlock()
if stopped:
try:
self.process.terminate()
self.process.wait(timeout=1)
if self.process.poll() is None:
self.process.kill()
except:
pass
break
while paused:
self.msleep(100)
self.mutex.lock()
paused = self.is_paused
stopped = self.is_stopped # Re-check stopped state while paused
self.mutex.unlock()
if stopped: break # If stopped while paused, break outer loop
if stopped: break # Break outer loop if stopped after pause check
line = line.strip()
if line:
color = self.get_output_color(line)
self.emitter.output_signal.emit(line, color)
except Exception as e:
self.emitter.output_signal.emit(f"[ERROR] Error reading output (fallback): {e}\n", "red")
def get_output_color(self, line):
"""Determine output color based on keywords"""
line_lower = line.lower()
if any(keyword in line_lower for keyword in ['error', 'exception', 'failed', 'fail', 'critical', 'denied']):
return "red"
elif any(keyword in line_lower for keyword in ['warning', 'warn', 'caution', 'pause', 'resume', 'stopping', 'skipped']):
return "orange"
elif any(keyword in line_lower for keyword in ['success', 'completed', 'done', 'finished', 'ok']):
return "green"
elif any(keyword in line_lower for keyword in ['info', 'debug', 'log', 'start', 'end', 'scheduled run']):
return "cyan"
else:
return None
def pause(self):
self.mutex.lock()
if not self.is_stopped:
self.is_paused = True
if self.process and self.process.poll() is None:
try:
import psutil
proc = psutil.Process(self.process.pid)
if platform.system() == "Windows":
proc.suspend()
self.emitter.output_signal.emit(f"[PAUSED] Process {self.process.pid} suspended\n", "orange")
else: # Unix
if proc.status() != psutil.STATUS_STOPPED:
os.kill(self.process.pid, signal.SIGSTOP)
self.emitter.output_signal.emit(f"[PAUSED] Process {self.process.pid} stopped\n", "orange")
except ImportError:
self.emitter.output_signal.emit("[PAUSED] Process paused (flag-based, psutil not found)\n", "orange")
except psutil.NoSuchProcess:
self.emitter.output_signal.emit("[PAUSED] Process already finished, cannot suspend.\n", "orange")
except Exception as e:
self.emitter.output_signal.emit(f"[PAUSE WARNING] Failed to suspend/stop process: {str(e)}\n", "orange")
else:
self.emitter.output_signal.emit("[PAUSED] No active process to pause\n", "orange")
self.mutex.unlock()
def resume(self):
self.mutex.lock()
if not self.is_stopped:
self.is_paused = False
if self.process and self.process.poll() is None:
try:
import psutil
proc = psutil.Process(self.process.pid)
if platform.system() == "Windows":
proc.resume()
self.emitter.output_signal.emit(f"[RESUMED] Process {self.process.pid} resumed\n", "green")
else: # Unix
if proc.status() == psutil.STATUS_STOPPED:
os.kill(self.process.pid, signal.SIGCONT)
self.emitter.output_signal.emit(f"[RESUMED] Process {self.process.pid} continued\n", "green")
except ImportError:
self.emitter.output_signal.emit("[RESUMED] Process resumed (flag-based, psutil not found)\n", "green")
except psutil.NoSuchProcess:
self.emitter.output_signal.emit("[RESUMED] Process already finished, cannot resume.\n", "green")
except Exception as e:
self.emitter.output_signal.emit(f"[RESUME WARNING] Failed to resume/continue process: {str(e)}\n", "orange")
else:
self.emitter.output_signal.emit("[RESUMED] No active process to resume\n", "green")
self.mutex.unlock()
def stop(self):
self.mutex.lock()
if not self.is_stopped: # Prevent multiple stop calls
self.is_stopped = True
if self.process:
self.emitter.output_signal.emit(f"[STOPPING] Terminating process {self.process.pid}...\n", "orange")
try:
# First try graceful termination
self.process.terminate()
# Wait a bit for graceful shutdown
try:
self.process.wait(timeout=2)
except subprocess.TimeoutExpired:
# Force kill if terminate doesn't work
try:
self.process.kill()
self.emitter.output_signal.emit(f"[FORCE STOP] Force killed process {self.process.pid}\n", "red")
except Exception as kill_e:
self.emitter.output_signal.emit(f"[FORCE STOP ERROR] {str(kill_e)}\n", "red")
except Exception as e:
self.emitter.output_signal.emit(f"[STOP ERROR] {str(e)}\n", "red")
else:
self.emitter.output_signal.emit("[STOPPED] No active process to stop\n", "orange")
self.mutex.unlock()
def write_log(self, script_path, code, error=None):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = {
"timestamp": timestamp,
"script": script_path,
"exit_code": code,
"error": error if error else "None"
}
try:
# Read existing logs, append new, write back to handle potential partial writes
if os.path.exists(LOG_FILE) and os.path.getsize(LOG_FILE) > 0: # Check if file exists and is not empty
with open(LOG_FILE, 'r', encoding='utf-8') as f:
try:
existing_logs = [json.loads(line) for line in f if line.strip()]
except json.JSONDecodeError:
self.emitter.output_signal.emit(f"[LOG ERROR] Corrupted log file '{LOG_FILE}'. Starting fresh.\n", "red")
existing_logs = []
else:
existing_logs = []
existing_logs.append(log_entry)
with open(LOG_FILE, 'w', encoding='utf-8') as log_file:
for entry in existing_logs:
log_file.write(json.dumps(entry) + '\n')
except Exception as e:
self.emitter.output_signal.emit(f"Failed to write log: {str(e)}\n", "red")
class ManageSchedulesDialog(QDialog):
def __init__(self, parent=None, scheduler=None):
super().__init__(parent)
self.setWindowTitle("⏰ Manage Scheduled Scripts")
self.setGeometry(200, 200, 800, 500)
self.scheduler = scheduler
self.init_ui()
def init_ui(self):
main_layout = QVBoxLayout(self)
self.schedule_table = QTableWidget()
self.schedule_table.setColumnCount(4)
self.schedule_table.setHorizontalHeaderLabels(["ID", "Script Path", "Trigger", "Next Run"])
self.schedule_table.setSelectionBehavior(self.schedule_table.SelectRows)
self.schedule_table.setEditTriggers(QTableWidget.NoEditTriggers)
self.schedule_table.horizontalHeader().setStretchLastSection(True) # Make last column stretch
main_layout.addWidget(self.schedule_table)
button_layout = QHBoxLayout()
refresh_btn = QPushButton("🔄 Refresh")
refresh_btn.clicked.connect(self.load_schedules)
remove_btn = QPushButton("🗑 Remove Selected")
remove_btn.clicked.connect(self.remove_selected_schedule)
button_layout.addStretch()
button_layout.addWidget(refresh_btn)
button_layout.addWidget(remove_btn)
button_layout.addStretch()
main_layout.addLayout(button_layout)
self.load_schedules()
def load_schedules(self):
self.schedule_table.setRowCount(0)
if not self.scheduler or not self.scheduler.running:
QMessageBox.warning(self, "Scheduler Error", "Scheduler is not running.")
return
jobs = self.scheduler.get_jobs()
for job in jobs:
row_idx = self.schedule_table.rowCount()
self.schedule_table.insertRow(row_idx)
script_path = "N/A"
if job.args and len(job.args) > 0 and isinstance(job.args[0], dict) and 'path' in job.args[0]:
script_path = job.args[0]['path']
trigger_info = str(job.trigger)
next_run = job.next_run_time.strftime('%Y-%m-%d %H:%M:%S') if job.next_run_time else "No next run"
self.schedule_table.setItem(row_idx, 0, QTableWidgetItem(job.id))
self.schedule_table.setItem(row_idx, 1, QTableWidgetItem(script_path))
self.schedule_table.setItem(row_idx, 2, QTableWidgetItem(trigger_info))
self.schedule_table.setItem(row_idx, 3, QTableWidgetItem(next_run))
self.schedule_table.resizeColumnsToContents()
def remove_selected_schedule(self):
selected_rows = sorted(set(index.row() for index in self.schedule_table.selectedIndexes()), reverse=True)
if not selected_rows:
QMessageBox.warning(self, "No Selection", "Please select a scheduled script to remove.")
return
confirm = QMessageBox.question(
self, "Confirm Removal",
f"Are you sure you want to remove {len(selected_rows)} scheduled job(s)?",
QMessageBox.Yes | QMessageBox.No
)
if confirm == QMessageBox.Yes:
removed_count = 0
for row in selected_rows:
job_id = self.schedule_table.item(row, 0).text()
try:
self.scheduler.remove_job(job_id)
removed_count += 1
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to remove job '{job_id}': {str(e)}")
if removed_count > 0:
QMessageBox.information(self, "Removed", f"Removed {removed_count} scheduled job(s).")
self.load_schedules() # Refresh the list
class InterpreterSettingsDialog(QDialog):
def __init__(self, parent=None, settings=None):
super().__init__(parent)
self.setWindowTitle("⚙️ Interpreter Settings")
self.settings = settings if settings is not None else {}
self.init_ui()
def init_ui(self):
layout = QFormLayout(self)
self.interpreter_fields = {}
# Define interpreters and their default values. Provide common executables.
interpreters = {
'Python': sys.executable,
'PowerShell': 'powershell.exe' if platform.system() == "Windows" else 'pwsh',
'Batch': 'cmd.exe' if platform.system() == "Windows" else '', # Batch files are cmd directly, no interpreter needed usually
'Shell': 'bash' if platform.system() != "Windows" else 'bash.exe', # For Git Bash, WSL bash
'Go': 'go', # go run, go build
'Rust': 'cargo', # cargo run
'Java': 'java', # java -jar, java -cp
'Ruby': 'ruby',
'C#': 'dotnet' if platform.system() != "Windows" else 'dotnet.exe' # for dotnet run (cross-platform), or 'mono.exe'/'mono'
}
for name, default_path in interpreters.items():
line_edit = QLineEdit(self.settings.get(name, default_path))
browse_btn = QPushButton("Browse...")
browse_btn.clicked.connect(lambda checked, le=line_edit, n=name: self.browse_interpreter(le, f"{n} Interpreter"))
h_layout = QHBoxLayout()
h_layout.addWidget(line_edit)
h_layout.addWidget(browse_btn)
layout.addRow(f"{name} Interpreter:", h_layout)
self.interpreter_fields[name] = line_edit
buttons_layout = QHBoxLayout()
save_btn = QPushButton("Save")
save_btn.clicked.connect(self.accept)
cancel_btn = QPushButton("Cancel")
cancel_btn.clicked.connect(self.reject) # Corrected: Was `dialog.reject`, should be `self.reject`
buttons_layout.addStretch()
buttons_layout.addWidget(save_btn)
buttons_layout.addWidget(cancel_btn)
layout.addRow(buttons_layout)
def browse_interpreter(self, line_edit, title):
# On Windows, filter for .exe, .cmd, .bat; otherwise, filter all files.
filter_str = "Executables (*.exe);;All Files (*)"
if platform.system() != "Windows":
filter_str = "All Files (*)" # On Unix, executables don't typically have extensions
executable_path, _ = QFileDialog.getOpenFileName(self, title, "", filter_str)
if executable_path:
line_edit.setText(executable_path)
def get_settings(self):
updated_settings = {}
for name, line_edit in self.interpreter_fields.items():
updated_settings[name] = line_edit.text().strip()
return updated_settings
class ScriptRunner(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowIcon(QIcon("Logo.ico"))
self.setWindowTitle("🛠️ Script Runner - Manage & Automate Scripts")
self.setGeometry(100, 100, 1400, 900)
self.script_list = self.load_scripts()
self.interpreter_settings = self.load_interpreter_settings()
# Configure APScheduler with SQLAlchemyJobStore for persistence
jobstores = {
'default': SQLAlchemyJobStore(url=f'sqlite:///{SCHEDULE_DB}')
}
self.scheduler = BackgroundScheduler(jobstores=jobstores)
try:
self.scheduler.start()
except Exception as e:
QMessageBox.critical(self, "Scheduler Error", f"Failed to start scheduler. Scheduled jobs might not run or save correctly: {str(e)}")
# Fallback for scheduling if persistence fails, but warn user
self.scheduler = BackgroundScheduler()
self.scheduler.start()
# Track running threads
self.running_threads = {}
self.execution_mutex = QMutex() # Protects access to self.running_threads
self.emitter = OutputEmitter()
self.emitter.output_signal.connect(self.print_output)
self.emitter.status_signal.connect(self.set_status)
self.init_ui()
# --- Pre-installation and welcome information on app load ---
self.show_pre_installation_info()
# --- End pre-installation info ---
self.append_disclaimer()
# Auto-save timer
self.auto_save_timer = QTimer()
self.auto_save_timer.timeout.connect(self.save_scripts)
self.auto_save_timer.start(30000) # Auto-save every 30 seconds
def show_pre_installation_info(self):
info_message = (
"Welcome to Script Runner!\n\n"
"To ensure this tool works correctly with all script types, "
"please make sure you have the following installed on your system:\n\n"
"• Python (required for the app itself)\n"
"• PowerShell (for .ps1 scripts)\n"
"• Git Bash / WSL (for .sh scripts on Windows, 'bash' command)\n"
"• Go (for .go programs)\n"
"• Rust (for .rs programs, requires 'cargo')\n"
"• Java JDK/JRE (for .java, .jar files)\n"
"• Ruby (for .rb scripts)\n"
"• .NET SDK or Mono (for .csproj, .exe C# programs)\n\n"
"You can configure specific interpreter paths in '⚙️ Settings' if they are not in your system's PATH.\n\n"
"For full pause/resume functionality on Windows, it's recommended to install 'psutil':\n"
"pip install psutil\n\n"
"Click 'OK' to continue to the application."
)
QMessageBox.information(self, "Essential Pre-requisites", info_message)
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
# Create tabs
self.tabs = QTabWidget()
self.init_main_tab()
self.init_how_to_tab()
main_layout.addWidget(self.tabs)
# Footer at the bottom
self.init_footer()
main_layout.addWidget(self.footer)
def init_main_tab(self):
self.main_tab = QWidget()
layout = QVBoxLayout(self.main_tab)
# Control buttons
self.init_control_buttons(layout)
# Create splitter for table and output
splitter = QSplitter(Qt.Vertical)
# Table widget
self.table = QTableWidget()
self.table.setColumnCount(6)
self.table.setHorizontalHeaderLabels(["Type", "Path", "Description", "Parameters", "Tag/Icon", "Status"])
self.table.setSelectionBehavior(self.table.SelectRows)
self.table.setAlternatingRowColors(True)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive) # Allow manual resize
self.table.horizontalHeader().setStretchLastSection(True) # Last column stretches
self.table.setEditTriggers(QTableWidget.NoEditTriggers) # Disable direct editing in table initially
self.load_table()
# Output console - Create self.output first
output_widget = QWidget()
output_layout = QVBoxLayout(output_widget)
# Create the output widget first
self.output = QTextEdit()
self.output.setReadOnly(True)
self.output.setFont(QFont("Consolas", 10))
self.output.setStyleSheet("""
QTextEdit {
background-color: #1e1e1e;
color: #ffffff;
border: 1px solid #555;
}
""")
# Console controls - Now we can reference self.output
console_controls = QHBoxLayout()
self.pause_btn = QPushButton("⏸ Pause")
self.pause_btn.clicked.connect(self.pause_execution)
self.pause_btn.setEnabled(False)
self.resume_btn = QPushButton("▶ Resume")
self.resume_btn.clicked.connect(self.resume_execution)
self.resume_btn.setEnabled(False)
self.stop_btn = QPushButton("⏹ Stop All") # Changed to Stop All for clarity
self.stop_btn.clicked.connect(self.stop_execution)
self.stop_btn.setEnabled(False)
clear_btn = QPushButton("🧹 Clear Console")
clear_btn.clicked.connect(self.output.clear)
console_controls.addWidget(QLabel("🔧 Script Output Console:"))
console_controls.addStretch()
console_controls.addWidget(self.pause_btn)
console_controls.addWidget(self.resume_btn)
console_controls.addWidget(self.stop_btn)
console_controls.addWidget(clear_btn)
output_layout.addLayout(console_controls)
output_layout.addWidget(self.output)
# Add to splitter
splitter.addWidget(self.table)
splitter.addWidget(output_widget)
splitter.setSizes([300, 200]) # Initial sizes
layout.addWidget(splitter)
self.tabs.addTab(self.main_tab, "Script Manager")
def init_control_buttons(self, layout):
# Primary actions
primary_layout = QHBoxLayout()
add_btn = QPushButton("➕ Add Script")
add_btn.clicked.connect(self.add_script)
add_btn.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }")
run_btn = QPushButton("▶ Run Selected")
run_btn.clicked.connect(self.run_selected)
run_btn.setStyleSheet("QPushButton { background-color: #2196F3; color: white; font-weight: bold; }")
edit_btn = QPushButton("✏️ Edit Selected")
edit_btn.clicked.connect(self.edit_selected_script)
edit_btn.setStyleSheet("QPushButton { background-color: #FFC107; color: black; font-weight: bold; }") # Yellowish
delete_btn = QPushButton("🗑 Delete Selected")
delete_btn.clicked.connect(self.delete_selected)
delete_btn.setStyleSheet("QPushButton { background-color: #f44336; color: white; font-weight: bold; }")
for btn in [add_btn, run_btn, edit_btn, delete_btn]: # Added edit_btn
primary_layout.addWidget(btn)
primary_layout.addStretch()
# Secondary actions
secondary_layout = QHBoxLayout()
schedule_btn = QPushButton("⏰ Schedule Script")
schedule_btn.clicked.connect(self.schedule_script)
manage_schedules_btn = QPushButton("🗓️ Manage Schedules")
manage_schedules_btn.clicked.connect(self.manage_schedules)
log_btn = QPushButton("📜 View Logs")
log_btn.clicked.connect(self.view_logs)
export_btn = QPushButton("📤 Export Scripts")
export_btn.clicked.connect(self.export_scripts)
import_btn = QPushButton("📥 Import Scripts")
import_btn.clicked.connect(self.import_scripts)
export_logs_btn = QPushButton("📁 Export Logs (CSV)")
export_logs_btn.clicked.connect(self.export_logs_csv)
settings_btn = QPushButton("⚙️ Settings")
settings_btn.clicked.connect(self.open_settings)
for btn in [schedule_btn, manage_schedules_btn, log_btn, export_btn, import_btn, export_logs_btn, settings_btn]: # Added manage_schedules_btn, settings_btn
secondary_layout.addWidget(btn)
layout.addLayout(primary_layout)
layout.addLayout(secondary_layout)
def init_how_to_tab(self):
tab = QWidget()
layout = QVBoxLayout()
instructions = QTextEdit()
instructions.setReadOnly(True)
instructions.setFont(QFont("Segoe UI", 10))
instructions.setStyleSheet("QTextEdit { background-color: #f9f9f9; color: #333; border: none; }")
instructions.setHtml("""
<h2>🚀 Getting Started with Script Runner</h2>
<h3>🔧 Installation & Setup:</h3>
<ol>
<li>
<b>Download & Extract:</b> Get the latest release from GitHub or Gumroad and extract the ZIP file.
</li>
<li>
<b>Install Dependencies:</b> Open a terminal/command prompt in the extracted folder and run:
<pre><code>pip install -r requirements.txt</code></pre>
<p>This ensures you have everything needed. Key libraries include:</p>
<ul>
<li><code>PyQt5</code>: For the graphical interface.</li>
<li><code>APScheduler</code>: For powerful script scheduling.</li>
<li><code>SQLAlchemy</code>: For persistent scheduling across app restarts.</li>
<li><code>psutil</code>: <span style="color: #17A2B8; font-weight: bold;">(Recommended for Windows)</span> Enhances process control (pause/resume). Install with <code>pip install psutil</code>.</li>
</ul>
</li>
<li>
<b>Run the Application:</b> Execute the main script:
<pre><code>python script_runner_gui.py</code></pre>
</li>
</ol>
<h3>🖥️ Basic Usage:</h3>
<ol>
<li>
<b>Add Your Scripts:</b> Click the <span style="background-color: #4CAF50; color: white; padding: 2px 5px; border-radius: 3px;">➕ Add Script</span> button. Select your script file (supports <code>.py</code>, <code>.ps1</code>, <code>.bat</code>, <code>.cmd</code>, <code>.sh</code>, <code>.go</code>, <code>.rs</code>, <code>.java</code>, <code>.jar</code>, <code>.csproj</code>, <code>.exe</code>, <code>.rb</code>). You can add a description, default parameters, and a unique tag (like an emoji!).
</li>
<li>
<b>Run Instantly:</b> Select one or more scripts from the table and click <span style="background-color: #2196F3; color: white; padding: 2px 5px; border-radius: 3px;">▶ Run Selected</span>. A dialog will appear for any additional parameters.
</li>
<li>
<b>Control Execution:</b> While a script is running, use the <span style="background-color: #ff9800; color: white; padding: 2px 5px; border-radius: 3px;">⏸ Pause</span>, <span style="background-color: #4CAF50; color: white; padding: 2px 5px; border-radius: 3px;">▶ Resume</span>, and <span style="background-color: #f44336; color: white; padding: 2px 5px; border-radius: 3px;">⏹ Stop All</span> buttons.
</li>
<li>
<b>Automate with Scheduling:</b> Select a script and click <span style="background-color: #607D8B; color: white; padding: 2px 5px; border-radius: 3px;">⏰ Schedule Script</span> to set it to run at a specific interval or date/time.
</li>
<li>
<b>Monitor Output:</b> The 'Script Output Console' provides real-time feedback with color-coded messages for easy understanding.
</li>
<li>
<b>Manage Scripts:</b>
<ul>
<li><span style="background-color: #FFC107; color: black; padding: 2px 5px; border-radius: 3px;">✏️ Edit Selected:</span> Modify the description, parameters, or tag of an existing script.</li>
<li><span style="background-color: #f44336; color: white; padding: 2px 5px; border-radius: 3px;">🗑 Delete Selected:</span> Remove scripts from your list.</li>
<li><span style="background-color: #607D8B; color: white; padding: 2px 5px; border-radius: 3px;">🗓️ Manage Schedules:</span> View, pause, resume, or remove scheduled jobs.</li>
<li><span style="background-color: #607D8B; color: white; padding: 2px 5px; border-radius: 3px;">📤 Export Scripts / 📥 Import Scripts:</span> Backup or transfer your script configurations.</li>
<li><span style="background-color: #607D8B; color: white; padding: 2px 5px; border-radius: 3px;">📁 Export Logs (CSV):</span> Save your execution logs in a spreadsheet-friendly format.</li>
</ul>
</li>
</ol>
<h3>✨ Advanced Features:</h3>
<ul>
<li><b>Flexible Parameters:</b> Define default parameters for scripts or override them dynamically before execution.</li>
<li><b>Comprehensive Logging:</b> Every script execution is recorded with timestamp, exit code, and error details in <code>script_logs.txt</code>.</li>