-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
982 lines (859 loc) · 31.1 KB
/
__init__.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
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
from time import sleep
import os
import random
import shlex
import subprocess
import sys
from typing import Union, Optional, Tuple, List
from time import perf_counter, time
import kthread
import psutil
import keyboard as keyboard__
from kthread_sleep import sleep
from tolerant_isinstance import isinstance_tolerant
from touchtouch import touch
outputvars = sys.modules[__name__]
outputvars.results = []
def execute_subprocess(
cmd: str, exit_keys: str = "ctrl+e", end_of_printline: str = "", timeout=None
) -> list:
popen = None
t= None
def run_subprocess(cmd):
nonlocal t
nonlocal popen
def killer():
sleep(timeout)
kill_process()
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
# popen.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
if timeout is not None:
t = kthread.KThread(target=killer, name=str(random.randrange(1, 100000000000)))
t.start()
try:
popen = subprocess.Popen(
cmd, stdout=subprocess.PIPE, universal_newlines=True
)
counter = -1
for stdout_line in iter(popen.stdout.readline, ""):
counter += 1
if counter == 0:
try:
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
except Exception:
pass
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
print(proxyresult, end=end_of_printline)
except BaseException:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
try:
if t is not None:
if t.is_alive():
t.kill()
except Exception:
pass
return proxyresults
def execute_subprocess_multiple_commands(
cmd: str, subcommands: list, exit_keys: str = "ctrl+x", end_of_printline: str = ""
) -> list:
popen = None
def run_subprocess(cmd):
nonlocal popen
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
try:
read, write = os.pipe()
for subcommand in subcommands:
if not isinstance(subcommand, bytes):
subcommand = subcommand.rstrip("\n") + "\n"
subcommand = subcommand.encode()
else:
subcommand = subcommand.rstrip(b"\n") + b"\n"
os.write(write, subcommand)
os.close(write)
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
popen = subprocess.Popen(
cmd,
stdin=read,
stdout=subprocess.PIPE,
universal_newlines=True,
stderr=None,
shell=True,
)
for stdout_line in iter(popen.stdout.readline, ""):
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
print(proxyresult, end=end_of_printline)
except BaseException:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
return proxyresults
def execute_subprocess_multiple_commands_v2(
cmd: str, subcommands: list, exit_keys: str = "ctrl+x", end_of_printline: str = ""
) -> list:
popen = None
def run_subprocess(cmd):
nonlocal popen
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
try:
popen = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
stderr=None,
shell=False,
)
for subcommand in subcommands:
if isinstance(subcommand, bytes):
subcommand = subcommand.rstrip(b"\n") + b"\n"
subcommand = subcommand.decode("utf-8", "replace")
else:
subcommand = subcommand.rstrip("\n") + "\n"
popen.stdin.write(subcommand)
popen.stdin.close()
for stdout_line in iter(popen.stdout.readline, ""):
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
print(proxyresult, end=end_of_printline)
except BaseException:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
return proxyresults
def execute_subprocess_multiple_commands_with_timeout_str(
cmd: str, subcommands: list, exit_keys: str = "ctrl+x", end_of_printline: str = "", print_output=True, timeout=None
) -> list:
if isinstance(subcommands, str):
subcommands = [subcommands]
elif isinstance(subcommands, tuple):
subcommands = list(subcommands)
popen = None
t= None
def run_subprocess(cmd):
nonlocal t
nonlocal popen
def killer():
sleep(timeout)
kill_process()
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
DEVNULL = open(os.devnull, "wb")
try:
popen = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
stderr=DEVNULL,
shell=False,
)
for subcommand in subcommands:
if isinstance(subcommand, bytes):
subcommand = subcommand.rstrip(b"\n") + b"\n"
subcommand = subcommand.decode("utf-8", "replace")
else:
subcommand = subcommand.rstrip("\n") + "\n"
popen.stdin.write(subcommand)
popen.stdin.close()
if timeout is not None:
t = kthread.KThread(target=killer, name=str(random.randrange(1,100000000000)))
t.start()
for stdout_line in iter(popen.stdout.readline, ""):
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
if print_output:
print(proxyresult, end=end_of_printline)
except KeyboardInterrupt:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
try:
if t is not None:
if t.is_alive():
t.kill()
except Exception:
pass
return proxyresults
def execute_subprocess_multiple_commands_with_timeout_bin(
cmd: str, subcommands: list, exit_keys: str = "ctrl+x", end_of_printline: str = "", print_output=True, timeout=None
) -> list:
if isinstance(subcommands, str):
subcommands = [subcommands]
elif isinstance(subcommands, tuple):
subcommands = list(subcommands)
popen = None
t= None
def run_subprocess(cmd):
nonlocal t
nonlocal popen
def killer():
sleep(timeout)
kill_process()
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
DEVNULL = open(os.devnull, "wb")
try:
popen = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=False,
stderr=DEVNULL,
shell=False,
)
for subcommand in subcommands:
if isinstance(subcommand, str):
subcommand = subcommand.rstrip("\n") + "\n"
subcommand = subcommand.encode()
else:
subcommand = subcommand.rstrip(b"\n") + b"\n"
popen.stdin.write(subcommand)
popen.stdin.close()
if timeout is not None:
t = kthread.KThread(target=killer, name=str(random.randrange(1,100000000000)))
t.start()
for stdout_line in iter(popen.stdout.readline, b""):
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
if print_output:
try:
print(f'{proxyresult!r}', end=end_of_printline)
print('')
except Exception:
pass
except KeyboardInterrupt:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
try:
if t is not None:
if t.is_alive():
t.kill()
except Exception:
pass
return proxyresults
def execute_as_mainprocess(
cmd: Union[str, List[str]],
nameofexe: Optional[str] = None,
returnpid: bool = True,
timeout_get_pid: int = 5,
creationtimebreak: int = 1,
) -> Union[subprocess.Popen, psutil.Process]:
"""
Starts a new process using the `start` command on Windows.
Args:
cmd (Union[str, List[str]]): The command to execute. Can be a string or a list of strings.
nameofexe (Optional[str]): The name of the executable file to look for after the process has started. Defaults to None.
returnpid (bool): Whether to return the PID of the new process or not. Defaults to True.
timeout_get_pid (int): The maximum amount of time (in seconds) to wait for the new process to start. Defaults to 5.
creationtimebreak (int): The maximum amount of time (in seconds) to wait for the new process to start after its creation time - if found, returns immediately. If not, the function returns the process after timeout_get_pid Defaults to 1.
Returns:
Union[subprocess.Popen, psutil.Process]: If `returnpid` is True, returns the `psutil.Process` object corresponding to the new process. Otherwise, returns the `subprocess.Popen` object that was used to start the new process.
"""
_startupinfo = subprocess.STARTUPINFO()
_startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
if isinstance(cmd, str):
cmd = [cmd]
exefile = cmd[0]
exefile = exefile.strip().strip('"').strip()
exefile = os.path.normpath(exefile)
exefile = f'"{exefile}"'
try:
arguments = cmd[1:]
except Exception:
arguments = []
args_command = " ".join(arguments).strip()
wholecommand = f'start "" {exefile} {args_command}'
for pp in psutil.process_iter():
try:
pp
except Exception:
pass
p = subprocess.Popen(wholecommand, shell=True, startupinfo=_startupinfo)
timeoutfinal = time() + timeout_get_pid
alla = []
if returnpid:
while timeoutfinal > time():
for pp in psutil.process_iter():
try:
if pp.name().lower() == nameofexe.lower():
g = pp.create_time()
if time() - g < creationtimebreak:
print(time() - g)
return pp
alla.append((g, pp))
except Exception as fe:
continue
if alla:
p = list(sorted(alla, key=lambda x: x[0]))[0][-1]
return p
def _killpro(t, addhotkeys, exit_keys, popen):
DEVNULL = open(os.devnull, "wb")
_startupinfo = subprocess.STARTUPINFO()
_startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
try:
try:
subprocess.Popen(
f"taskkill /F /PID {popen.pid} /T",
stdin=DEVNULL,
stdout=DEVNULL,
universal_newlines=False,
stderr=DEVNULL,
shell=False,
creationflags=subprocess.CREATE_NO_WINDOW,
startupinfo=_startupinfo,
)
except Exception as fe:
pass
try:
if psutil.pid_exists(popen.pid):
p = psutil.Process(popen.pid)
p.kill()
except Exception as fe:
pass
try:
if t.is_alive():
t.kill()
except Exception as fe:
pass
finally:
_unhookkeys(addhotkeys, exit_keys)
try:
DEVNULL.close()
except Exception:
pass
def _unhookkeys(addhotkeys, exit_keys):
try:
if addhotkeys:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
if addhotkeys:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
def execute_subprocess_multiple_commands_with_timeout_bin2(
cmd: Union[list, str],
subcommands: Union[list, tuple, None, str] = None,
exit_keys: Union[str, None] = None,
end_of_printline: str = "",
print_output: bool = True,
timeout: Optional[float] = None,
cwd: str = os.getcwd(),
decodestdout=None,
decodestdouterrors: str = "ignore",
stderrfile: Optional[str] = None,
stdoutfile: Optional[str] = None,
create_no_window: bool = True,
use_shlex: bool = False,
pyinstaller_module_name: Optional[str] = None,
pyinstaller_entry: Optional[str] = None,
argsforpyinstaller: Tuple = (),
isthread=False,
**kwargs,
) -> list:
r"""
Executes a subprocess and runs one or more commands in it, with the option to add a timeout and exit keys.
:param cmd: The command to be executed in the subprocess.
:type cmd: str
:param subcommands: Additional commands to run in the subprocess, as a list or tuple of strings or a single string. Defaults to None.
:type subcommands: Union[list, tuple, None, str]
:param exit_keys: If set, the process can be terminated by pressing the specified key combination (e.g. "ctrl+alt+x"). Defaults to None.
:type exit_keys: Union[str, None]
:param end_of_printline: The string to be printed at the end of each line of output. Defaults to "".
:type end_of_printline: str
:param print_output: Whether to print the output of the subprocess to the console. Defaults to True.
:type print_output: bool
:param timeout: The maximum amount of time to allow the subprocess to run before terminating it. Defaults to None.
:type timeout: Optional[float]
:param cwd: The working directory for the subprocess. Defaults to the current working directory.
:type cwd: str
:param decodestdout: The character encoding to use for decoding the output of the subprocess. Defaults to None.
:type decodestdout: Optional[str]
:param decodestdouterrors: The error handling mode to use for decoding the output of the subprocess. Defaults to "ignore".
:type decodestdouterrors: str
:param stderrfile: The file path to write standard error output to. Defaults to None.
:type stderrfile: Optional[str]
:param stdoutfile: The file path to write standard output to. Defaults to None.
:type stdoutfile: Optional[str]
:param create_no_window: Whether to create a new console window for the subprocess. Defaults to True.
:type create_no_window: bool
:param use_shlex: Whether to use the shlex module to split the command string into arguments. Defaults to False.
:type use_shlex: bool
:param pyinstaller_module_name: The name of the PyInstaller module to run in the subprocess. Defaults to None.
:type pyinstaller_module_name: Optional[str]
:param pyinstaller_entry: The name of the PyInstaller entry point to run in the subprocess. Defaults to None.
:type pyinstaller_entry: Optional[str]
:param argsforpyinstaller: Additional arguments to pass to the PyInstaller subprocess. Defaults to ().
:type argsforpyinstaller: Tuple
:param kwargs: Additional keyword arguments to pass to the subprocess.Popen() constructor.
:type kwargs: Any
:return: A list of
"""
_startupinfofun = subprocess.STARTUPINFO()
creationflags = 0
if create_no_window:
creationflags = creationflags | subprocess.CREATE_NO_WINDOW
_startupinfofun.wShowWindow = subprocess.SW_HIDE
if isinstance_tolerant(subcommands, str):
subcommands = [subcommands]
elif isinstance_tolerant(subcommands, tuple):
subcommands = list(subcommands)
popen = None
t = None
addhotkeys = not isinstance_tolerant(exit_keys, None)
stoutputfile = None
def run_subprocess(cmd):
nonlocal t
nonlocal popen
nonlocal stderrfile
nonlocal stoutputfile
def killer():
sleep(timeout)
kill_process()
def kill_process():
nonlocal popen
_killpro(t, addhotkeys, exit_keys, popen)
if addhotkeys:
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
if isinstance_tolerant(stderrfile, None):
DEVNULL = open(os.devnull, "wb")
else:
stderrfile = os.path.normpath(stderrfile)
if not os.path.exists(stderrfile):
touch(stderrfile)
DEVNULL = open(stderrfile, "ab")
if not isinstance_tolerant(stdoutfile, None):
if not os.path.exists(stdoutfile):
touch(stdoutfile)
stoutputfile = open(stdoutfile, "ab")
try:
if use_shlex:
if isinstance_tolerant(cmd, str):
cmd = shlex.split(cmd)
if not isinstance_tolerant(
pyinstaller_module_name, None
) and not isinstance_tolerant(pyinstaller_entry, None):
if getattr(sys, "frozen", False):
popen = subprocess.Popen(
[
os.path.join(sys._MEIPASS, pyinstaller_entry),
*argsforpyinstaller,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=False,
stderr=DEVNULL,
shell=False,
cwd=cwd,
creationflags=creationflags,
startupinfo=_startupinfofun,
**kwargs,
)
else:
popen = subprocess.Popen(
[
sys.executable,
"-m",
f"{pyinstaller_module_name}.{pyinstaller_entry}",
*argsforpyinstaller,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=False,
stderr=DEVNULL,
shell=False,
cwd=cwd,
creationflags=creationflags,
startupinfo=_startupinfofun,
**kwargs,
)
else:
popen = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=False,
stderr=DEVNULL,
shell=False,
cwd=cwd,
creationflags=creationflags,
startupinfo=_startupinfofun,
**kwargs,
)
if not isinstance_tolerant(subcommands, None):
for subcommand in subcommands:
if isinstance(subcommand, str):
subcommand = subcommand.rstrip("\n") + "\n"
subcommand = subcommand.encode()
else:
subcommand = subcommand.rstrip(b"\n") + b"\n"
popen.stdin.write(subcommand)
popen.stdin.close()
if not isinstance_tolerant(timeout, None):
t = kthread.KThread(
target=killer,
name=str(perf_counter() + random.randrange(1, 100000000000)),
)
t.start()
woutput = not isinstance_tolerant(stoutputfile, None)
dodecode = not isinstance_tolerant(decodestdout, None)
for stdout_line in iter(popen.stdout.readline, b""):
try:
if woutput:
try:
stoutputfile.write(stdout_line)
except Exception as fe:
print(fe)
if dodecode:
stdout_line = stdout_line.decode(
decodestdout, decodestdouterrors
)
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
finally:
if not isinstance_tolerant(stderrfile, None):
try:
DEVNULL.close()
except Exception as fe:
pass
if not isinstance_tolerant(stdoutfile, None):
try:
stoutputfile.close()
except Exception as fe:
pass
proxyresults = []
keyex = False
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
if print_output:
try:
print(f"{proxyresult!r}", end=end_of_printline)
print("")
except Exception:
pass
except KeyboardInterrupt:
keyex = True
_killpro(t, addhotkeys, exit_keys, popen)
if not keyex:
_killpro(t, addhotkeys, exit_keys, popen)
if isthread:
outputvars.results.append(proxyresults)
return proxyresults
def execute_subprocess_multiple_commands_with_timeout_bin2_thread(
cmd: Union[list, str],
subcommands: Union[list, tuple, None, str] = None,
exit_keys: Union[str, None] = None,
end_of_printline: str = "",
print_output: bool = True,
timeout: Optional[float] = None,
cwd: str = os.getcwd(),
decodestdout=None,
decodestdouterrors: str = "ignore",
stderrfile: Optional[str] = None,
stdoutfile: Optional[str] = None,
CREATE_NO_WINDOW: bool = True,
use_shlex: bool = False,
pyinstaller_module_name: Optional[str] = None,
pyinstaller_entry: Optional[str] = None,
argsforpyinstaller: Tuple = (),
**kwargs,
) -> None:
t = kthread.KThread(
target=execute_subprocess_multiple_commands_with_timeout_bin2,
name=str(perf_counter() + random.randrange(1, 100000000000)),
# args=args,
kwargs={
"cmd": cmd,
"subcommands": subcommands,
"exit_keys": exit_keys,
"end_of_printline": end_of_printline,
"print_output": print_output,
"timeout": timeout,
"cwd": cwd,
"decodestdout": decodestdout,
"decodestdouterrors": decodestdouterrors,
"stderrfile": stderrfile,
"stdoutfile": stdoutfile,
"create_no_window": CREATE_NO_WINDOW,
"use_shlex": use_shlex,
"pyinstaller_module_name": pyinstaller_module_name,
"pyinstaller_entry": pyinstaller_entry,
"argsforpyinstaller": argsforpyinstaller,
"isthread": True,
}
| kwargs,
)
t.start()