-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1574 lines (1384 loc) · 45.6 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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ctypes
import itertools
import os
import platform
import shutil
import signal
import sys
import subprocess
import threading
from collections import deque
import re
from time import sleep as sleep_
from math import floor
compiledregex = re.compile(r"^[A-Z]:\\", flags=re.I)
from functools import cache
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
aptget = r"""#!/bin/bash
# apt-cyg: install tool for Cygwin similar to debian apt-get
#
# The MIT License (MIT)
#
# Copyright (c) 2013 Trans-code Design
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
if [ ${BASH_VERSINFO}${BASH_VERSINFO[1]} -lt 42 ]
then
echo 'Bash version 4.2+ required'
exit
fi
usage="\
NAME
apt-cyg - package manager utility
SYNOPSIS
apt-cyg [operation] [options] [targets]
DESCRIPTION
apt-cyg is a package management utility that tracks installed packages on a
Cygwin system. Invoking apt-cyg involves specifying an operation with any
potential options and targets to operate on. A target is usually a package
name, file name, URL, or a search string. Targets can be provided as command
line arguments.
OPERATIONS
install
Install package(s).
remove
Remove package(s) from the system.
update
Download a fresh copy of the master package list (setup.ini) from the
server defined in setup.rc.
download
Retrieve package(s) from the server, but do not install/upgrade anything.
show
Display information on given package(s).
depends
Produce a dependency tree for a package.
rdepends
Produce a tree of packages that depend on the named package.
list
Search each locally-installed package for names that match regexp. If no
package names are provided in the command line, all installed packages will
be queried.
listall
This will search each package in the master package list (setup.ini) for
names that match regexp.
category
Display all packages that are members of a named category.
listfiles
List all files owned by a given package. Multiple packages can be specified
on the command line.
search
Search for downloaded packages that own the specified file(s). The path can
be relative or absolute, and one or more files can be specified.
searchall
Search cygwin.com to retrieve file information about packages. The provided
target is considered to be a filename and searchall will return the
package(s) which contain this file.
mirror
Set the mirror; a full URL to a location where the database, packages, and
signatures for this repository can be found. If no URL is provided, display
current mirror.
cache
Set the package cache directory. If a file is not found in cache directory,
it will be downloaded. Unix and Windows forms are accepted, as well as
absolute or regular paths. If no directory is provided, display current
cache.
OPTIONS
--nodeps
Specify this option to skip all dependency checks.
--version
Display version and exit.
"
version="\
apt-cyg version 1
The MIT License (MIT)
Copyright (c) 2005-9 Stephen Jungels
"
function wget {
if command wget -h &>/dev/null
then
command wget "$@"
else
warn wget is not installed, using lynx as fallback
set "${*: -1}"
lynx -source "$1" > "${1##*/}"
fi
}
function find-workspace {
# default working directory and mirror
# work wherever setup worked last, if possible
cache=$(awk '
BEGIN {
RS = "\n\\<"
FS = "\n\t"
}
$1 == "last-cache" {
print $2
}
' /etc/setup/setup.rc)
mirror=$(awk '
/last-mirror/ {
getline
print $1
}
' /etc/setup/setup.rc)
mirrordir=$(sed '
s / %2f g
s : %3a g
' <<< "$mirror")
mkdir -p "$cache/$mirrordir/$arch"
cd "$cache/$mirrordir/$arch"
if [ -e setup.ini ]
then
return 0
else
get-setup
return 1
fi
}
function get-setup {
touch setup.ini
mv setup.ini setup.ini-save
wget -N $mirror/$arch/setup.bz2
if [ -e setup.bz2 ]
then
bunzip2 setup.bz2
mv setup setup.ini
echo Updated setup.ini
else
echo Error updating setup.ini, reverting
mv setup.ini-save setup.ini
fi
}
function check-packages {
if [[ $pks ]]
then
return 0
else
echo No packages found.
return 1
fi
}
function warn {
printf '\e[1;31m%s\e[m\n' "$*" >&2
}
function apt-update {
if find-workspace
then
get-setup
fi
}
function apt-category {
check-packages
find-workspace
for pkg in "${pks[@]}"
do
awk '
$1 == "@" {
pck = $2
}
$1 == "category:" && $0 ~ query {
print pck
}
' query="$pks" setup.ini
done
}
function apt-list {
local sbq
for pkg in "${pks[@]}"
do
let sbq++ && echo
awk 'NR>1 && $1~pkg && $0=$1' pkg="$pkg" /etc/setup/installed.db
done
let sbq && return
awk 'NR>1 && $0=$1' /etc/setup/installed.db
}
function apt-listall {
check-packages
find-workspace
local sbq
for pkg in "${pks[@]}"
do
let sbq++ && echo
awk '$1~pkg && $0=$1' RS='\n\n@ ' FS='\n' pkg="$pkg" setup.ini
done
}
function apt-listfiles {
check-packages
find-workspace
local pkg sbq
for pkg in "${pks[@]}"
do
(( sbq++ )) && echo
if [ ! -e /etc/setup/"$pkg".lst.gz ]
then
download "$pkg"
fi
gzip -cd /etc/setup/"$pkg".lst.gz
done
}
function apt-show {
find-workspace
check-packages
for pkg in "${pks[@]}"
do
(( notfirst++ )) && echo
awk '
$1 == query {
print
fd++
}
END {
if (! fd)
print "Unable to locate package " query
}
' RS='\n\n@ ' FS='\n' query="$pkg" setup.ini
done
}
function apt-depends {
find-workspace
check-packages
for pkg in "${pks[@]}"
do
awk '
@include "join"
$1 == "@" {
apg = $2
}
$1 == "requires:" {
for (z=2; z<=NF; z++)
reqs[apg][z-1] = $z
}
END {
prpg(ENVIRON["pkg"])
}
function smartmatch(small, large, values) {
for (each in large)
values[large[each]]
return small in values
}
function prpg(fpg) {
if (smartmatch(fpg, spath)) return
spath[length(spath)+1] = fpg
print join(spath, 1, length(spath), " > ")
if (isarray(reqs[fpg]))
for (each in reqs[fpg])
prpg(reqs[fpg][each])
delete spath[length(spath)]
}
' setup.ini
done
}
function apt-rdepends {
find-workspace
for pkg in "${pks[@]}"
do
awk '
@include "join"
$1 == "@" {
apg = $2
}
$1 == "requires:" {
for (z=2; z<=NF; z++)
reqs[$z][length(reqs[$z])+1] = apg
}
END {
prpg(ENVIRON["pkg"])
}
function smartmatch(small, large, values) {
for (each in large)
values[large[each]]
return small in values
}
function prpg(fpg) {
if (smartmatch(fpg, spath)) return
spath[length(spath)+1] = fpg
print join(spath, 1, length(spath), " < ")
if (isarray(reqs[fpg]))
for (each in reqs[fpg])
prpg(reqs[fpg][each])
delete spath[length(spath)]
}
' setup.ini
done
}
function apt-download {
check-packages
find-workspace
local pkg sbq
for pkg in "${pks[@]}"
do
(( sbq++ )) && echo
download "$pkg"
done
}
function download {
local pkg digest digactual
pkg=$1
# look for package and save desc file
awk '$1 == pc' RS='\n\n@ ' FS='\n' pc=$pkg setup.ini > desc
if [ ! -s desc ]
then
echo Unable to locate package $pkg
exit 1
fi
# download and unpack the bz2 or xz file
# pick the latest version, which comes first
set -- $(awk '$1 == "install:"' desc)
if (( ! $# ))
then
echo 'Could not find "install" in package description: obsolete package?'
exit 1
fi
dn=$(dirname $2)
bn=$(basename $2)
# check the md5
digest=$4
case ${#digest} in
32) hash=md5sum ;;
128) hash=sha512sum ;;
esac
mkdir -p "$cache/$mirrordir/$dn"
cd "$cache/$mirrordir/$dn"
if ! test -e $bn || ! $hash -c <<< "$digest $bn"
then
wget -O $bn $mirror/$dn/$bn
$hash -c <<< "$digest $bn" || exit
fi
tar tf $bn | gzip > /etc/setup/"$pkg".lst.gz
cd ~-
mv desc "$cache/$mirrordir/$dn"
echo $dn $bn > /tmp/dwn
}
function apt-search {
check-packages
echo Searching downloaded packages...
for pkg in "${pks[@]}"
do
key=$(type -P "$pkg" | sed s./..)
[[ $key ]] || key=$pkg
for manifest in /etc/setup/*.lst.gz
do
if gzip -cd $manifest | grep -q "$key"
then
package=$(sed '
s,/etc/setup/,,
s,.lst.gz,,
' <<< $manifest)
echo $package
fi
done
done
}
function apt-searchall {
cd /tmp
for pkg in "${pks[@]}"
do
printf -v qs 'text=1&arch=%s&grep=%s' $arch "$pkg"
wget -O matches cygwin.com/cgi-bin2/package-grep.cgi?"$qs"
awk '
NR == 1 {next}
mc[$1]++ {next}
/-debuginfo-/ {next}
/^cygwin32-/ {next}
{print $1}
' FS=-[[:digit:]] matches
done
}
function apt-install {
check-packages
find-workspace
local pkg dn bn requires wr package sbq script
for pkg in "${pks[@]}"
do
if grep -q "^$pkg " /etc/setup/installed.db
then
echo Package $pkg is already installed, skipping
continue
fi
(( sbq++ )) && echo
echo Installing $pkg
download $pkg
read dn bn </tmp/dwn
echo Unpacking...
cd "$cache/$mirrordir/$dn"
tar -x -C / -f $bn
# update the package database
awk '
ins != 1 && pkg < $1 {
print pkg, bz, 0
ins = 1
}
1
END {
if (ins != 1) print pkg, bz, 0
}
' pkg="$pkg" bz=$bn /etc/setup/installed.db > /tmp/awk.$$
mv /etc/setup/installed.db /etc/setup/installed.db-save
mv /tmp/awk.$$ /etc/setup/installed.db
[ -v nodeps ] && continue
# recursively install required packages
requires=$(awk '$1=="requires", $0=$2' FS=': ' desc)
cd ~-
wr=0
if [[ $requires ]]
then
echo Package $pkg requires the following packages, installing:
echo $requires
for package in $requires
do
if grep -q "^$package " /etc/setup/installed.db
then
echo Package $package is already installed, skipping
continue
fi
apt-cyg install --noscripts $package || (( wr++ ))
done
fi
if (( wr ))
then
echo some required packages did not install, continuing
fi
# run all postinstall scripts
[ -v noscripts ] && continue
find /etc/postinstall -name '*.sh' | while read script
do
echo Running $script
$script
mv $script $script.done
done
echo Package $pkg installed
done
}
function apt-remove {
check-packages
cd /etc
cygcheck awk bash bunzip2 grep gzip mv sed tar xz > setup/essential.lst
for pkg in "${pks[@]}"
do
if ! grep -q "^$pkg " setup/installed.db
then
echo Package $pkg is not installed, skipping
continue
fi
if [ ! -e setup/"$pkg".lst.gz ]
then
warn Package manifest missing, cannot remove $pkg. Exiting
exit 1
fi
gzip -dk setup/"$pkg".lst.gz
awk '
NR == FNR {
if ($NF) ess[$NF]
next
}
$NF in ess {
exit 1
}
' FS='[/\\\\]' setup/{essential,$pkg}.lst
esn=$?
if [ $esn = 0 ]
then
echo Removing $pkg
if [ -e preremove/"$pkg".sh ]
then
preremove/"$pkg".sh
rm preremove/"$pkg".sh
fi
mapfile dt < setup/"$pkg".lst
for each in ${dt[*]}
do
[ -f /$each ] && rm /$each
done
for each in ${dt[*]}
do
[ -d /$each ] && rmdir --i /$each
done
rm -f setup/"$pkg".lst.gz postinstall/"$pkg".sh.done
awk -i inplace '$1 != ENVIRON["pkg"]' setup/installed.db
echo Package $pkg removed
fi
rm setup/"$pkg".lst
if [ $esn = 1 ]
then
warn apt-cyg cannot remove package $pkg, exiting
exit 1
fi
done
}
function apt-mirror {
if [ "$pks" ]
then
awk -i inplace '
1
/last-mirror/ {
getline
print "\t" pks
}
' pks="$pks" /etc/setup/setup.rc
echo Mirror set to "$pks".
else
awk '
/last-mirror/ {
getline
print $1
}
' /etc/setup/setup.rc
fi
}
function apt-cache {
if [ "$pks" ]
then
vas=$(cygpath -aw "$pks")
awk -i inplace '
1
/last-cache/ {
getline
print "\t" vas
}
' vas="${vas//\\/\\\\}" /etc/setup/setup.rc
echo Cache set to "$vas".
else
awk '
/last-cache/ {
getline
print $1
}
' /etc/setup/setup.rc
fi
}
if [ -p /dev/stdin ]
then
mapfile -t pks
fi
# process options
until [ $# = 0 ]
do
case "$1" in
--nodeps)
nodeps=1
shift
;;
--noscripts)
noscripts=1
shift
;;
--version)
printf "$version"
exit
;;
update)
command=$1
shift
;;
list | cache | remove | depends | listall | download | listfiles |\
show | mirror | search | install | category | rdepends | searchall )
if [[ $command ]]
then
pks+=("$1")
else
command=$1
fi
shift
;;
*)
pks+=("$1")
shift
;;
esac
done
set -a
if type -t apt-$command | grep -q function
then
readonly arch=${HOSTTYPE/i6/x}
apt-$command
else
printf "$usage"
fi
"""
@cache
def get_comspec(gcmd=None, convert_to_83=True):
if not gcmd:
comspec = os.environ.get("ComSpec")
if not comspec:
system_root = os.environ.get("SystemRoot", "")
comspec = os.path.join(system_root, "System32", "cmd.exe")
if not os.path.isabs(comspec):
raise FileNotFoundError(
"shell not found: neither %ComSpec% nor %SystemRoot% is set"
)
cmd = comspec
return [cmd, "/k"]
else:
if os.path.exists(gcmd):
pa = os.path.normpath(gcmd)
else:
pa = shutil.which(gcmd)
if convert_to_83:
pa = get_short_path_name(pa)
return [pa]
iswindows = "win" in platform.platform().lower()
if iswindows:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
creationflags = subprocess.CREATE_NO_WINDOW
invisibledict = {
"startupinfo": startupinfo,
"creationflags": creationflags,
"start_new_session": True,
}
from ctypes import wintypes
windll = ctypes.LibraryLoader(ctypes.WinDLL)
user32 = windll.user32
kernel32 = windll.kernel32
GetExitCodeProcess = windll.kernel32.GetExitCodeProcess
CloseHandle = windll.kernel32.CloseHandle
GetExitCodeProcess.argtypes = [
ctypes.wintypes.HANDLE,
ctypes.POINTER(ctypes.c_ulong),
]
CloseHandle.argtypes = [ctypes.wintypes.HANDLE]
GetExitCodeProcess.restype = ctypes.c_int
CloseHandle.restype = ctypes.c_int
GetWindowRect = user32.GetWindowRect
GetClientRect = user32.GetClientRect
_GetShortPathNameW = kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD]
_GetShortPathNameW.restype = wintypes.DWORD
else:
invisibledict = {}
def is_process_alive(pid):
if re.search(
b"ProcessId=" + str(pid).encode() + rb"\s*$",
subprocess.run(
"wmic process list FULL", capture_output=True, **invisibledict
).stdout,
flags=re.MULTILINE,
):
return True
return False
@cache
def convert_path_to_short(string, returnstring=True):
if not iswindows:
return string
l2 = [q - 1 for q in index_all(s=string, n=":\\")]
addtostring = []
try:
result1 = list_split(l=string, indices_or_sections=l2)
except Exception:
return string
try:
for string in result1:
if not compiledregex.search(string):
addtostring.append(string)
continue
activepath = ""
lastfoundpath = ""
lastfoundpath_end = 0
for ini, letter in enumerate(string):
activepath += letter
if ini < 3:
continue
if letter.isspace():
continue
if os.path.exists(activepath):
lastfoundpath = activepath
lastfoundpath_end = ini
if lastfoundpath:
addtostring.append(get_short_path_name(lastfoundpath))
addtostring.append(string[lastfoundpath_end + 1 :])
else:
addtostring.append(string)
if not returnstring:
return addtostring
return "".join(addtostring)
except Exception:
return string
def list_split(l, indices_or_sections):
Ntotal = len(l)
try:
Nsections = len(indices_or_sections) + 1
div_points = [0] + list(indices_or_sections) + [Ntotal]
except TypeError:
Nsections = int(indices_or_sections)
if Nsections <= 0:
raise ValueError("number sections must be larger than 0.") from None
Neach_section, extras = divmod(Ntotal, Nsections)
section_sizes = (
[0] + extras * [Neach_section + 1] + (Nsections - extras) * [Neach_section]
)
div_points = []
new_sum = 0
for i in section_sizes:
new_sum += i
div_points.append(new_sum)
sub_arys = []
lenar = len(l)
for i in range(Nsections):
st = div_points[i]
end = div_points[i + 1]
if st >= lenar:
break
sub_arys.append((l[st:end]))
return sub_arys
@cache
def get_short_path_name(long_name):
try:
if not iswindows:
return long_name
output_buf_size = 4096
output_buf = ctypes.create_unicode_buffer(output_buf_size)
_ = _GetShortPathNameW(long_name, output_buf, output_buf_size)
return output_buf.value
except Exception as e:
sys.stderr.write(f"{e}\n")
return long_name
def sleep(secs):
if secs == 0:
return
maxrange = 50 * secs
if isinstance(maxrange, float):
sleeplittle = floor(maxrange)
sleep_((maxrange - sleeplittle) / 50)
maxrange = int(sleeplittle)
if maxrange > 0:
for _ in range(maxrange):
sleep_(0.016)
def killthread(threadobject):
# based on https://pypi.org/project/kthread/
if not threadobject.is_alive():
return True
tid = -1
for tid1, tobj in threading._active.items():
if tobj is threadobject:
tid = tid1
break
if tid == -1:
sys.stderr.write(f"{threadobject} not found")
return False
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
ctypes.c_long(tid), ctypes.py_object(SystemExit)
)
if res == 0:
return False
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
return False
return True
def index_all(s, n):
indototal = 0
allindex = []
while True:
try:
indno = s[indototal:].index(n)
indototal += indno + 1
allindex.append(indototal - 1)
except ValueError:
break
return allindex
def send_ctrl_commands(pid, command=0):
if iswindows:
commandstring = r"""import ctypes, sys; CTRL_C_EVENT, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT = 0, 1, 2, 3, 4; kernel32 = ctypes.WinDLL("kernel32", use_last_error=True); (lambda pid, cmdtosend=CTRL_C_EVENT: [kernel32.FreeConsole(), kernel32.AttachConsole(pid), kernel32.SetConsoleCtrlHandler(None, 1), kernel32.GenerateConsoleCtrlEvent(cmdtosend, 0), sys.exit(0) if isinstance(pid, int) else None])(int(sys.argv[1]), int(sys.argv[2]) if len(sys.argv) > 2 else None) if __name__ == '__main__' else None"""
subprocess.Popen(
[sys.executable, "-c", commandstring, str(pid), str(command)],
**invisibledict,
) # Send Ctrl-C
else:
os.kill(pid, signal.SIGINT)
class dequeslice(deque):
def __getitem__(self, index):
if isinstance(index, slice):
return self.__class__(
itertools.islice(self, index.start, index.stop, index.step)
)
return deque.__getitem__(self, index)
class CmdInteractive:
def __init__(
self,
print_stdout=True,
print_stderr=True,
limit_stdout=None,
limit_stderr=None,
limit_stdin=None,
convert_to_83=True,
exitcommand="▓▓▓▓▓▓▓▓▓▓▓",
getcomspec=None,
newline="\r\n",
wait_to_complete=0.1,
**kwargs,
):
r"""
A class for interacting with a command-line shell in a subprocess.
Args:
print_stdout (bool, optional): Whether to print stdout from the subprocess (default is True).
print_stderr (bool, optional): Whether to print stderr from the subprocess (default is True).
limit_stdout (int, optional): Maximum number of lines to keep in stdout history (default is None).
limit_stderr (int, optional): Maximum number of lines to keep in stderr history (default is None).
limit_stdin (int, optional): Maximum number of lines to keep in stdin history (default is None).
convert_to_83 (bool, optional): Whether to convert file paths to short (8.3) format (default is True).
exitcommand (str, optional): The command to signal the subprocess to exit (default is "▓▓▓▓▓▓▓▓▓▓▓").
getcomspec (str, optional): The command to get the shell executable (default is None).
newline (str, optional): The newline character to use (default is "\r\n").
wait_to_complete (float, optional): The interval to check for subprocess completion (default is 0.1 seconds).
**kwargs: Additional keyword arguments for subprocess.Popen.
Attributes:
(Attributes of the class and their descriptions.)
Methods:
(Methods of the class and their descriptions.)
"""
self.wait_to_complete = wait_to_complete
self.getcomspec = getcomspec
separate_stdout_stderr_with_list = True
invisible = True
self.newline = newline
self.convert_to_83 = convert_to_83
self.cmd = get_comspec(gcmd=self.getcomspec, convert_to_83=self.convert_to_83)
self.exitcommand = exitcommand
self.invisible = invisible
self.kwargs = kwargs.copy()
self.separate_stdout_with_list = separate_stdout_stderr_with_list
self.separate_stderr_with_list = separate_stdout_stderr_with_list
self.lockobject = threading.Lock()
self.limit_stdout = limit_stdout
self.limit_stderr = limit_stderr
self.limit_stdin = limit_stdin
self.separate_stdout_stderr_with_list = separate_stdout_stderr_with_list
if self.separate_stdout_with_list:
self.stdout = dequeslice([[]], maxlen=limit_stdout)
else:
self.stdout = dequeslice([], maxlen=limit_stdout)
if self.separate_stderr_with_list:
self.stderr = dequeslice([[]], maxlen=limit_stderr)
else:
self.stderr = dequeslice([], maxlen=limit_stderr)
self.stdin = dequeslice(self.cmd, maxlen=limit_stdin)
self.print_stdout = print_stdout
self.print_stderr = print_stderr
self.p = self._start_subproc(**kwargs)
self._t_stdout = threading.Thread(target=self._read_stdout)
self._t_stderr = threading.Thread(target=self._read_stderr)
self._t_stdout.start()
self._t_stderr.start()
def _start_subproc(self, **kwargs):
kwargs.update(
{