-
Notifications
You must be signed in to change notification settings - Fork 3
/
U.py
executable file
·8955 lines (7813 loc) · 263 KB
/
U.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
# coding=utf-8
gsImport='''
from qgb import U,T
'''
try:
import py
if not py.istr:raise Exception('not qgb.py')
except Exception as eipy:
try:from . import py
except Exception as ei:
print(ei)
import pdb;pdb.set_trace()
'''TODO:应该设计一个配置类,__getattr__ on a module 属性拦截,这样可以同步多个变量名, 在python2中没有很好的方法, 在Python 3.7+中,你只需要做一个明显的方法。
# my_module.py
def __getattr__(name: str) -> Any:
return attr
目前使用单变量名
'''
gbPrintErr=True
gbLogErr=True
import sys
gbDebug=DEBUG=sys.flags.debug or False#gbDebug只在这里出现一次
def debug(a=False):
# global gbDebug,DEBUG
if 'debug' in os.environ:#优先环境变量开关
e=os.getenv('debug').strip()#not .trim()
if e and e!='0':a=True
else:a=False
globals()['DEBUG']=a
globals()['gbDebug']=a
return DEBUG
# if(calltimes()<1):DEBUG=True #ct not defined
########
gError=[]
def setErr(ae,msg='#Error '):
global gError
if gbLogErr:# U.
if type(gError) is list:gError.append(ae)
elif gError:gError=[gError,ae]
else:gError=[ae]
else:
gError=ae
if gbPrintErr:print (msg,ae)# U.
if 'qgb.U' in sys.modules:sys.modules['_U']=sys.modules['qgb.U']
elif 'U' in sys.modules:sys.modules['_U']=sys.modules['U']
################ import python lib #######################
stdin=sys.stdin;stdout=sys.stdout;stderr=sys.stderr
gsdecode=decoding='utf-8';gsencode=gsencoding=encoding=py.getattr(stdout,'encoding','utf-8')#AttributeError: 'IDAPythonStdOut' object has no attribute 'encoding'
modules=sys.modules
try:
import os;path=os.path
from threading import Thread
thread=Thread
from threading import Lock as threading_lock
mutex=threadingLock=threading_lock
from multiprocessing import Process;process=Process
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor# ._max_workers 在没有第一次运行时可以调整,运行后调整无效
threadPool=ThreadPool=ThreadPoolExecutor
from copy import deepcopy
except Exception as ei:
setErr(ei,msg='#Error py lib import')
try:
_U=modules['_U']
gError=_U.gError
gbPrintErr=_U.gbPrintErr
except Exception as _e:pass
# pass# 已经存在于globals 中,是否有必要重新赋值给 gError?
# else:
try:
if __name__.endswith('qgb.U'):from . import F,T
else:import F,T
write,read,ls,ll,md,rm=F.write,F.read,F.ls,F.ll,F.md,F.rm
IntSize=F.IntSize
# F.fileName=F.filename=T.filename_legalized
from pprint import pformat
if __name__.endswith('qgb.U'):from . import Clipboard
else: import Clipboard
clipboard=cb=Clipboard#
cbs=CBS=Clipboard.set
cbg=CBG=Clipboard.get
except Exception as ei:
setErr(ei,msg='#Error import '+str(ei))
aError=ArgsErr=argserr=argErr=argerr=argumentError=ArgumentException=py.ArgumentError
ArgumentUnsupported=py.ArgumentUnsupported
############
true=True;false=False
int_max=INT_MAX=gimax=IMAX=imax=2147483647
int_min=INT_MIN=gimin=IMIN=imin=-2147483648
nan=float_nan=py.float('nan')
inf=float_inf=py.float('inf')
int_float_max=179769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791
int_float_min=0-int_float_max
int_float_max==2**1024-2**970-1
float_max=int_float_max*1.0
float_min_resolution=1e-323 # 1e-324==0.0
float_min_resolution=5e-324 # 3e-324 4e-324 都自动变成 5e-324
'''float(U.float_max+1) or float(U.float_min-1) #OverflowError: int too large to convert to float
float(1.79769313486231580793728971405303415079934132710037826936173778980444968292764750946649017977587207096330286416692887910946555547851940402630657488671505820681908902000708383676273854845817711531764475730270069855571366959622842914819860834936475292719074168444365510704342711559699508093042880177904174497791e+308) == float(1.7976931348623158079372897140530341507993413271003782693617377898044496829276475094664901797758720709633028641669288791094655554785194040263065748867150582068190890200070838367627385484581771153176447573027006985557136695962284291481986083493647529271907416844436551070434271155969950809304288017790417449779199999999999999999999e+308) == 1.7976931348623157e+308
'''
#2**1024-U.float_max=9979201547673599058281863565184192830337256302177287707512736212186059459344820328924789827463178505446712234220962476219862189941967968303695858991424157101600028364755428382587688607221814935913266783722719619966654052275604351944444276342240220787535604534378780208211792476151720049639425
float_float_max=float_int_add_max=9979201547673598504324897285072871471186213993555970510405882466533898272496291900571175780142852257200163724564939022373763785492381006715959384438336167193578868484000098586299213046281059798601446904646187766350716006315149259876521361241978618923324738012834739836717385472725200706469887
float_float_max=2**970-2**916-1
float_max_min=0.749999999999999944488848768742172978818416595458984374
float_max_min_min=0.24999999999999998612221219218554324470460414886474609374#==0.24999999999999997
'''
float(U.float_max+float(U.float_float_max))==1.7976931348623157e+308,
float(U.float_max+float(U.float_float_max+1))==U.inf
>>> t,fs=(['0.24999999999999998612221219218554324470460414886474609374'], '
float(2**1024-2**970-1+ float(2**970-2**916-1+ float(2**916-2**862-1+ float(2**862-2**808-1+ float(2**808-2**754-1+ float(2**754-2**700-1+ float(2**700-2**646-1+ float(2**646-2**592-1+ float(2**592-2**538-1+ float(2**538-2**484-1+ float(2**484-2**430-1+ float(2**430-2**376-1+ float(2**376-2**322-1+ float(2**322-2**268-1+ float(2**268-2**214-1+ float(2**214-2**160-1+ float(2**160-2**106-1+ float(2**106-2**52-1+ float(2**52-1+0.749999999999999944488848768742172978818416595458984374+ 0.24999999999999998612221219218554324470460414886474609374+%s ) ))))))))))))))))))
')
>>> eval(fs%'+'.join(t*31368))
1.7976931348623157e+308
>>> eval(fs%'+'.join(t*31369))
1.7976931348623157e+308
>>> eval(fs%'+'.join(t*31370))
1.7976931348623157e+308
>>> eval(fs%'+'.join(t*31371))
# pocess exit!
>>> eval('+'.join(t*31420))
7854.999999999999
>>> eval('+'.join(t*31421))
# pocess exit!
'''
float_0_9999999999999999=f_9_16=float_0_9_16=0.999999999999999944488848768742172978818416595458984374
# float_0_9999999999999999==0.9999999999999999 #True 16个9
# float(0.99999999999999999)==1.0 #True 17个9
NoneType=py.type(None)
module=py.module
Class=py.Class
instance=py.instance
Class=classtype=classType=py.classType
iterable=py.iterable
def iterable_but_str(a):
if py.istr(a):return False
return py.iterable(a)
iterable_not_str=iterable_but_str
#######################################
gd_sync_level={
'process':1,
'python':1,
'py':1,
'system':2 ,
'sys':2 , #not sys module
'lan':3 ,# lan sync #TODO default rpc to find out qpsu computer
'wan':4 ,# internet sync
'all':5 ,
}
SET_NO_VALUE=py.No('U.set value=None',no_raise=True)
GET_NO_VALUE=py.No('U.get ',no_raise=True)
def set(name,value=SET_NO_VALUE,return_old_value=False,level=gd_sync_level['process'],**ka):
if ka:
raise py.NotImplementedError()
if level>=gd_sync_level['process']:
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})# 统一用这句
if value is SET_NO_VALUE: # py.No 比较不能用== ,no==0 ==None ==0.0 ...
value=name
name='_'
if return_old_value:
if name in d:old=d[name]
else:old=GET_NO_VALUE
d[name]=value
# sys._qgb_dict=d
if level>=gd_sync_level['system']:
import sqlite3
if return_old_value:return old,value
return value
def set_no_return(name,value,**ka):
set(name,value,**ka)
def set_delete(*names,level=gd_sync_level['process'],**ka):
if level>=gd_sync_level['process']:
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
r=[]
for name in names:
if name in d:
r.append(d.pop(name))
else:
r.append(py.No('{} not found to unset'.format(py.repr(name)),) ,)#如果用%s,name tuple时
#出错:TypeError: not all arguments converted during string formatting
if py.len(r)==1:
return r[0]
else:
return r
set_del=delset=del_set=unset=delete_set=set_delete
def set_delete_by_surfix(s,confirm=True,level=gd_sync_level['process']):
U,T,N,F=py.importUTNF()
ks=[]
if level>=gd_sync_level['process']:
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
for k in d:
if py.istr(k) and k.endswith(s):
ks.append(k)
if confirm:
U.input('delete:%s \n### press Enter to del,ctrl+c to cancel'%ks)
return U.object_custom_repr(U.dict_multi_pop(d,*ks),repr='{%s}#dict custom repr'%','.join('%r: ... '%k for k in ks),)
delset_surfix=del_set_by_surfix=set_delete_by_surfix
def set_delete_by_prefix(s,confirm=True,level=gd_sync_level['process']):
U,T,N,F=py.importUTNF()
ks=[]
if level>=gd_sync_level['process']:
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
for k in d:
if py.istr(k) and k.startswith(s):
ks.append(k)
if confirm:
U.input('delete:%s \n### press Enter to del,ctrl+c to cancel'%ks)
return U.object_custom_repr(U.dict_multi_pop(d,*ks),repr='{%s}#dict custom repr'%','.join('%r: ... '%k for k in ks),)
delset_prefix=del_set_by_prefix=set_delete_by_prefix
def set_multi_prefix(prefix,**ka):
import sys
sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
d={prefix+k:v for k,v in ka.items()}
sys._qgb_dict.update(d)
return d
def set_multi(**ka):
prefix=get_duplicated_kargs(ka,'__prefix','_prefix',default='')
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
sys._qgb_dict.update({prefix+k:v for k,v in ka.items()})
# for name,value in ka.items():
# d[name]=value
return ka
set_named=set_multi
def get(name='_',default=GET_NO_VALUE,level=gd_sync_level['process']):
if level>=gd_sync_level['process']:
import sys
d=sys._qgb_dict=py.getattr(sys,'_qgb_dict',{})
#TODO 对于不存在的 name ,可以记录最后访问时间为 py.No,方便排查
# if default==None:
# default=py.No('can not get name '+py.repr(name),no_raise=True)
return d.get(name,default)
#TODO
def get_startswith_keys(name):
import sys
r=[]
for k,v in sys._qgb_dict.items():
if py.istr(k) and k.startswith(name):
r.append(k)
return r
get_prefix_keys=get_startswith=get_startswith_keys
def get_multi_return_dict():
raise py.NotImplementedError()
return
def get_prefix_multi_return_list(prefix,*names,**defaults):
if not prefix:return prefix
r=[]
for name in names:
if not name.startswith(prefix):
name=prefix+name
r.append( get(name) )
for name,default in defaults.items():
if not name.startswith(prefix):
name=prefix+name
r.append( get(name,default=default) )
return r
def get_multi_return_list(*names,**defaults):
r=[]
for name in names:
r.append( get(name) )
for name,default in defaults.items():
r.append( get(name,default=default) )
return r
getm=multi_get=get_multi=get_multi_return_list
def get_multi_return_exist_one(*names,default=GET_NO_VALUE,no_raise=True):
for name in names:
v=get(name,default=default)
if not (v is default):return v
if not no_raise:
raise Exception('can not U.get names:',names)
return default
def input_and_set(name,default=py.No('auto get last',no_raise=1),default_function=lambda a:a,**ka):
r=get(name)
if not py.isno(r) and py.isno(default):
default=r
if py.callable(default_function):default=default_function(r)
return set(name, input('%s :'%name,default=default,**ka))
inset=set_and_input=set_input=input_set=input_or_set=input_and_set
def get_or_set_input(name,default='',type=None):
r=get(name)
if r:return r
return set(name,input('%s :'%name,default=default,type=type) )
get_input=getInput=getOrInput=get_or_input=get_or_input_set=get_or_set_input
def get_or_set(name,default=None,lazy_default=None):
# if not default: # ipy module set {}
if (py.isno(default) or (default==None)) and not py.callable(lazy_default) :
raise py.ArgumentError('default cannot be {},lazy_default must callable'.format( repr(default) ))
r=get(name)
if not py.isno(r):
return r
else:
# if default:
if py.callable(lazy_default) and not default:
default=lazy_default()
return set(name,default)
getset=getSet=get_set=get_or_set
# def get_or_dill_load_noset(name):
# o=get(name)
# if not o:
# o=F.dill_load(file=name)
# return o
# =get_or_dill_load_noset
def get_or_dill_load_or_dill_dump_and_set(name,default=None):
'''
#TODO linux /mnt/c redirect
'''
U,T,N,F=py.importUTNF()
gst=U.get_gst(base_gst=True)
path=F.auto_path(name,default=gst)
if '/' in path:
name=T.sub_last(path,'/','')
else:
name=path
o=get(name)
if not o:
o=F.dill_load(file=path)
if not o:
fsg=F.ls(gst)
fs=[f for f in fsg if f.startswith(name) and f.endswith('.dill')]
if not fs:
fs=[f for f in fsg if name in f and f.endswith('.dill')]
if py.len(fs)==1:
o=F.dill_load(file=fs[0])
if not o and default:
f=F.dill_dump(obj=default,file=path)
if f:
print(U.stime(),'dill_dump:',f)
o=default
else:
raise Exception('not o,dill_dump',o,f)
if not o:
return o
# raise EnvironmentError('can not dill_load',name)
else:
return U.set(name,o)
get_dl=get_or_dl=get_or_dill_load=get_or_set_sys_level=get_or_set_system_level=get_or_dl_and_set=get_or_dill_load_set=get_or_dill_load_and_set=get_or_dill_load_or_dill_dump_and_set
# def get_or_dill_load_or_dill_dump(name):
# return
def set_and_dill_dump(name,value):
return set(name,value),F.dill_dump(file=name,obj=value)
set_dp=set_and_dp=dill_dump_and_set=set_and_dill_dump
def get_or_set_and_dill_dump(name,default=None,lazy_default=None):
o=get_or_set(name=name,default=default,lazy_default=lazy_default)
U,T,N,F=py.importUTNF()
print(U.stime(),F.dp(file=name,obj=o),U.len(o))
return o
get_set_dp=get_or_set_dp=get_or_set_and_dill_dump
def set_or_get(name,value,default=SET_NO_VALUE):
# if py.isno(default) or (default==None):
if value or not py.isNo(value) :
return set(name,value)
else:
r=get(name)
if r:
return r
else:
if default==SET_NO_VALUE:
raise py.ArgumentError('if not value, default cannot be {} when get {} == {}'.format( repr(default) ,name,repr(r) ))
return set(name,default)
setget=setGet=set_get=set_or_get
def set_rename(old,new):
v=set_delete(old)
if not v:return v
set(new,v)
return 'U.set_rename {} > {}'.format(old,new)
# return new
setmv=mvset=mv_set=set_move=move_set=rename_set=set_rename
def get_or_set_ka(name,**ka):
return get_or_set(name,default=ka)
def set_ka(name,**ka):
if not ka:raise py.ArgumentError('need ka')
d=get(name)
if d and not py.isdict(d):raise py.EnvironmentError('U.get(%r) is not dict ?'%name,d,ka)
if not py.isdict(d):return get_or_set_ka(name,**ka)
for k,v in ka.items():
d[k]=v
return d
#########################
def one_in(vs,*t):
'''(1,2,3,[t]) or ([vs].[t])
char in s : 这个效率较高
char in list:比s至少慢了几十 上百倍?
'''
if not hasattr(vs, '__iter__'):vs=[vs]# is3 str has __iter__ while is2 not
if len(t)==1:
t=t[0]
elif len(t)>1:
vs.extend(t[:-1])
t=t[-1]
else:raise Exception(one_in.__doc__)
r=[]
for i in vs:
try:
if i in t:r.append(i)
except:pass
return r
#########################
def getPyVersion():
'''return float 2.713
'''
r=T.sub(sys.version,'',' ')
r=r.replace('.','')
r=r[0]+'.'+r[1:]
return float(r)
def platform_system():
'''Traceback (most recent call last):
File "/var/www/contextlib.py", line 21, in <module>
from qgb import U
File "/home/qmm/qgb/U.py", line 356, in <module>
if iswin() or iscyg():
File "/home/qmm/qgb/U.py", line 295, in is_windows
return platform.system().startswith('Windows')
File "/usr/lib/python3.8/platform.py", line 891, in system
return uname().system
File "/usr/lib/python3.8/platform.py", line 857, in uname
processor = _syscmd_uname('-p', '')
File "/usr/lib/python3.8/platform.py", line 613, in _syscmd_uname
output = subprocess.check_output(('uname', option),
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1650, in _execute_child
self._close_pipe_fds(p2cread, p2cwrite,
File "/usr/lib/python3.8/subprocess.py", line 1104, in _close_pipe_fds
with contextlib.ExitStack() as stack:
AttributeError: partially initialized module 'contextlib' has no attribute 'ExitStack' (most likely due to a circular import)
'''
import platform
try:
return platform.system()
except Exception as e:
e
p=py.getattr(sys,'platform','')
if p:return p
if sys.executable.endswith('.exe'):
return 'Windows .exe'
else:
return 'linux qgb_default'
glnix=['nix','linux','darwin']
def isnix():
'''
### Linux (64bit) + WSL
os.name posix
sys.platform linux
platform.system() Linux
sysconfig.get_platform() linux-x86_64
platform.machine() x86_64
platform.architecture() ('64bit', '')
### WINDOWS official python installer 32bit
------------------------- ----- -----
os.name nt nt
sys.platform win32 win32
platform.system() Windows Windows
sysconfig.get_platform() win-amd64 win32
platform.machine() AMD64 AMD64
platform.architecture() ('64bit', 'WindowsPE') ('64bit', 'WindowsPE')
msys2 64bit 32bit
----- ----- -----
os.name posix posix
sys.platform msys msys
platform.system() MSYS_NT-10.0 MSYS_NT-10.0-WOW
sysconfig.get_platform() msys-2.11.2-x86_64 msys-2.11.2-i686
platform.machine() x86_64 i686
platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')
msys2 mingw-w64-x86_64-python3 mingw-w64-i686-python3
----- ------------------------ ----------------------
os.name nt nt
sys.platform win32 win32
platform.system() Windows Windows
sysconfig.get_platform() mingw mingw
platform.machine() AMD64 AMD64
platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')
cygwin 64bit 32bit
------ ----- -----
os.name posix posix
sys.platform cygwin cygwin
platform.system() CYGWIN_NT-10.0 CYGWIN_NT-10.0-WOW
sysconfig.get_platform() cygwin-3.0.1-x86_64 cygwin-3.0.1-i686
platform.machine() x86_64 i686
platform.architecture() ('64bit', 'WindowsPE') ('32bit', 'WindowsPE')
'''
return [i for i in glnix if i in platform_system().lower()]
def is_windows():
p=platform_system().lower()
return p.startswith('windows') or p.startswith('win32')#sys.platform=='win32'
is_win=iswin=isWin=is_windows
def is_linux():return platform_system()=='Linux'
islinux=isLinux=is_linux
def isMacOS():return platform_system()=='darwin'
isMac=is_mac=is_osx=isOSX=ismacos=isMacOS
def is_termux():
return '/com.termux' in sys.executable
istermux=isTermux=is_termux
def is_kivy():
return os.environ['KIVY_ORIENTATION'] or os.environ['P4A_BOOTSTRAP']
def is_vercel():
'''
drwx------ 2 sbx_user1051 990 4.0K Jul 1 14:46 tmp
其他全部是 root
drwxr-xr-x 1 root root 4.0K Jan 1 1970 var
'''
return os.getenv('VERCEL')
def iscyg():
return 'cygwin' in platform_system().lower()
# gipy=None#这个不是qgb.ipy, 是否与U.F U.T 这样的风格冲突?
def is_ipython(raise_exception=False,**ka): # e=False
# global gipy
raise_exception=get_duplicated_kargs(ka,'raise_exception',
'raise_err','raise_error','raiseError','raiseErr','raise_EnvironmentError','EnvironmentError','raiseEnvironmentError',default=raise_exception)
try:
# if not py.modules('IPython'):return py.No()
import IPython
return IPython.get_ipython()
except Exception as e:
if raise_exception:
raise
return py.No(e)
# ipy=False #如果曾经有过实例,现在没有直接返回原来
# f=sys._getframe()
# while f and f.f_globals:# and 'get_ipython' not in f.f_globals.keys()
# try:
# ipy=f.f_globals['get_ipython']()#下个循环没有直接跳出while
# break
# except:
# pass
# f=f.f_back
# return ipy
get_ipy=get_ipython=getipy=isIpy=is_ipy=isipy=is_ipython
def is_ipy_cell():
''' 和 getArgsDict 一样,最多向上找两层,防止影响到意料之外的代码
f.f_back ~= None
'''
ipy=get_ipython()
if not ipy:
return py.No('Not even ipy')
f=sys._getframe().f_back
def check(f):
return f and f.f_code.co_filename.startswith('<ipython-input-')
return check(f) or check(f.f_back)
is_ipy_call=is_ipy_cell
def isrepl():
# i,o=sys.stdin.isatty(),sys.stdout.isatty() # 这样太简单粗暴了,我想要判断上面两层之内是不是用户手动输入
# TODO flask——rpc
return is_ipy_cell()
if i==o:return i
else:
raise Exception('std(in,out) isatty conflit')
isatty=istty=isrepl
########################
if iswin() or iscyg():
try:
from ctypes import wintypes#TODO cygwin ValueError: _type_ 'v' not supported
if __name__.endswith('qgb.U'):from . import Win
else:import Win
setWindowPos,msgbox=Win.setWindowPos,Win.msgbox
pos=cmdPos=setWindowPos
pid=Win.getpid()
except Exception as ei:
# def msgbox(s='',st='title',*a):
# if(a!=()):s=str(s)+ ','+str(a)[1:-2]
# if iswin():windll.user32.MessageBoxA(0, str(s), str(st), 0)
setErr(ei,msg='#Error import Win' )
def find_driver_path(a,reverse=True):
'''from Z to C'''
if len(a)>1 and a[1]==':':a=a[1:]
if not a.startswith(':'):a=':'+a
# try:AZ=T.AZ;exist=F.exist
# except:
AZ=''.join([chr(i) for i in py.range(65,65+26)])
exist=os.path.exists
if reverse:AZ=AZ[::-1]
for i in sys.executable[0]+AZ:
if exist(i+a):return i+a
return ''
driverPath=driver_path=find_driver_path
if iscyg():
def getCygPath():
try:r=getProcessPath()
except:r='G:/QGB/babun/cygwin/'
if 'cygwin' in r:
return T.subLast(r,'','cygwin')+'cygwin\\'
else:
raise EnvironmentError(r)
elif iscyg():# #TODO this is not windows read pid , only in cyg ps, use Win.getpid
pid=os.getpid()
else:# *nix etc.., #TODO:isAndroid
pid=os.getpid()
if isnix():
'''
u1604: IPython repl ok , bash python -c error ?
'''
def is_root():
''' windows 没有 AttributeError: module 'os' has no attribute 'getuid'
'''
return os.getuid()==0
isroot=isRoot=is_root
def sudo(cmd,password=py.No('auto get_or_input')):
'''cmd can use pipe 'id|cut -c 2-22'
'''
if password==0:password='0'
if not password:
password=get_or_input("root.password")
from subprocess import call
# try:
return call("echo {} | sudo -S {}".format(password, cmd), shell=True)
# except:
# from subprocess import PIPE,Popen
# p = Popen(['sudo', '-S'] + cmd, stdin=PIPE, stderr=PIPE,
# universal_newlines=True)
# sudo_prompt = p.communicate(password + '\n')
# return sudo_prompt
# [1]
# 0
# u1604 # /bin/sh: 1: Syntax error: end of file unexpected
def tmux_capture_pane(session=0,max_lines=9999,reverse=False,socket='',capture_pane_args='-J',**ka):
''' unset TMUX
-S 套接字路径
指定服务器套接字的完整替代路径。
如果指定了 -S,则默认套接字目录为
未使用并且任何 -L 标志都将被忽略。
Specify a full alternative path to the server socket.
If -S is specified, the default socket directory is
not used and any -L flag is ignored.
-J : no line wrap
tmux show socket file : lsof -U | grep '^tmux' # socket='/tmp/tmux-1001/default'
'''
U,T,N,F=py.importUTNF()
session=U.get_duplicated_kargs(ka,'session','sess',default=session)
max_lines=U.get_duplicated_kargs(ka,'max_lines','max','m','n','S','s','l',default=max_lines)
reverse=U.get_duplicated_kargs(ka,'reverse','rev','r','R',default=reverse)
a=N.geta()
if not session and a:
if ':' in a:
session=a
else:
session=f'{session}:{a}'
if (not socket) and U.is_root() and U.is_termux():
pt=U.ps(name='tmux: server')[0]
username=pt.username()
if username.startswith('u0_a'):
username=username[4:]
else:
username=''
socket=[f for f in F.ls('/data/data/com.termux/files/usr/var/run/',r=1) if U.all_in(['tmux','default',username],f)][0]
if socket and not socket.startswith('-S'):
socket='-S '+socket.strip()
os.environ['TMUX']=''
rs=U.isipy().getoutput(f'tmux {socket} capture-pane -S -{max_lines} -t {session} {capture_pane_args};tmux {socket} show-buffer')#.format(max_lines=max_lines,session=session,window=a))# 不能用 U.cmd
if reverse:rs=rs[::-1]
return T.EOL.join(rs)
tmux=tmuxc=tmuxcap=tmuxcapture=tmuxCapture=tmux_capture=tmux_capture_pane
def tmux_detach_client_all_skip_max(skip_max_n=1):
'''
!tmux list-clients
/dev/pts/0: 0 [186x45 xterm-256color] (utf8) # ttyd
/dev/pts/3: 0 [109x42 xterm] (utf8) # ssh
tmux detach-client -t /dev/pts/3
'''
U,T,N,F=py.importUTNF()
cs=[]
for s in U.ipy_getoutput('tmux list-clients',return_list=1):
c=T.sub(s,'',':')
d=T.regex_match_named_return_dict(s,r'\s\[(?P<x>\d+)x(?P<y>\d+)\s')
x,y=py.int(d['x']),py.int(d['y'])
cs.append([c,x,y,x*y])
cs=U.sort(cs,col=3,reverse=1)
for row in cs[skip_max_n:]:
U.ipy_getoutput(f'tmux detach-client -t {row[0]}')
row.append(U.stime())
return cs
tmux_dt=tmux_detach=tmux_detach_client=tmux_detach_client_all=tmux_detach_client_all_skip_max
########################## end init #############################################
def pick(*a,return_index=False,**ka):
'''pick(
options: Sequence[~OPTION_T],
title: Union[str, NoneType] = None,
indicator: str = '*',
default_index: int = 0,
multiselect: bool = False,
min_selection_count: int = 0,
screen: Union[ForwardRef('curses._CursesWindow'), NoneType] = None,
)'''
from pick import pick
v,n=pick(*a,**ka)
if return_index:return v,n
return v
select_value=pick
def float_range(start,end,step):
f=start
while f<end:
yield f
f+=step
range_float=float_range
def arithmetic_sequence(a,b,n=4):
d=b-a
r=[a,b]
if n<2:raise py.ArgumentError('n must >2')
for i in py.range(n-2):
r.append(r[-1]+d)
return r
dcsl=dengcha=arithmetic_sequence
def parse_str_auto_type(s):
U=py.importU()
ss=s.strip()
if U.all_in(ss,'.0123456789') and U.unique(ss,ct=1).get('.',0)==1:
try:return py.float(ss)
except:pass
if U.all_in(ss,'0123456789') or ss.lower().startswith('0x'):
try:return py.int(ss)
except:pass
# if (ss.startswith('[') and ss.endswith(']')) or :
T=py.importT()
try:return T.unrepr(s)
except:pass
return s
auto_type=input_auto_type=parse_str_auto_type
def __import__(mod_name):
m=py.__import__(mod_name)
ss=mod_name.split('.')
for s in ss[1:]:
m=py.getattr(m,s)
return m
_import=__import__
def PyFile_FromFd(fd,name="filename",mode='r',buffering=-1,encoding='utf-8'):
'''__builtin__.open 也可以打开 int,但是此时 tell好像不共享 ?
.. c:function:: PyObject* PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)
Create a Python file object from the file descriptor of an already
opened file *fd*. The arguments *name*, *encoding*, *errors* and *newline*
can be ``NULL`` to use the defaults; *buffering* can be *-1* to use the
default. *name* is ignored and kept for backward compatibility. Return
``NULL`` on failure. For a more comprehensive description of the arguments,
please refer to the :func:`io.open` function documentation.
.. warning::
Since Python streams have their own buffering layer, mixing them with
OS-level file descriptors can produce various issues (such as unexpected
ordering of data).
.. versionchanged:: 3.2
Ignore *name* attribute.
PyFile_FromFd() 的最后一个参数被设置成1,用来指出Python应该关闭这个文件。
和open 打开同一个文件,tell 和 seek 自动同步,因为就是同一个文件
两个 PyFile_FromFd 一个是 r utf-8.一个是 rb。可以分别read str 和byte。但是 tell依然共享
'''
import ctypes
f = ctypes.pythonapi.PyFile_FromFd
f.restype = ctypes.py_object
f.argtypes = [ctypes.c_int,
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_int ]
NULL=None
if 'b' in mode:
bencoding=NULL
else:
bencoding=encoding.encode('ascii')
bencoding=ctypes.create_string_buffer(bencoding)
if not py.isbyte(name):name=name.encode(encoding)
name=ctypes.create_string_buffer(name)
if not py.isbyte(mode):mode=mode.encode()
mode=ctypes.create_string_buffer(mode)
return f(fd, name,mode,buffering,bencoding,NULL,NULL,1)
def list_remove_multi_values(a,*vs,skip_not_exists=False):
r=[]
for v in vs:
try:
a.remove(v)
r.append(v)
except Exception as e:
if not skip_not_exists:
r.append(py.No(e))
return r
list_pop_multi_values=list_remove_multi_values
def list_reindex_by_value(alist,*values):
''' 调整顺序 reindex ,
确保 values 全部存在,否则中途出现错误会污染 alist
'''
if not alist:return alist
if not py.islist(alist):
raise py.NotImplementedError('# TODO tuple ,set ,other types....',alist)
for n,v in py.enumerate(values):
if v not in alist:
return py.No('No.%s:%s not in values!'%(n,v),v,values)
vs=[]
for v in values:
alist.remove(v) #return None #TODO other types
vs.append(v)
vs.extend(alist)
return vs
list_reindex=list_reindex_by_value
def new_nd_list(*a,default_value=0):
from copy import deepcopy
r=default_value
for nd in py.reversed(a):
r=[deepcopy(r) for i in py.range(nd)]
return r
new_3d_list=new_nd_list
def new_2d_list(width,height,default_value=0):
''' cols=height rows=width '''
return [[default_value for i in py.range(height)] for j in py.range(width)]
def list2d_swap_row_column(a):
import pandas as pd
return pd.DataFrame(a).T.values.tolist()
transpose_list_xy=swap_xy_list=list2d_swap_row_column
def list_get_multi_indexs(a,*ins):
if py.len(ins)==1 and py.islist(ins[0]):
ins=ins[0]
r=[]
for i in ins:
r.append(a[i])
return r
get_list_elements_by_multi_indexs=list_multi_get=list_get_multi_indexs
def list_del_multi_indexs(a,*ins):
ins=py.sorted(ins,reverse=1)
d={}
for i in ins:
d[i]=a.pop(i)
return d
del_list_multi_indexs=list_del_multi_indexs
def get_multi_list_element_by_index(*a,index=0,**ka):
index=get_duplicated_kargs(ka,'index','i','n',default=index)
r=[]
for y in a:
try:
v=y[index]
except Exception as e:
v=py.No(e)
r.append(v)
return r
def multiprocess_pool(*a,**ka):
'''multiprocess.Pool(
processes=None,
initializer=None,
initargs=(),
maxtasksperchild=None,
)
原生multiprocessing模块在使用 IPython 时有一个主要限制:
此包中的功能要求__main__子模块可以导入该模块。[...]这意味着某些示例,例如multiprocessing.pool.Pool示例将无法在交互式解释器中运行。[来自文档]
幸运的是,有一个multiprocessing的fork 模块 multiprocess,它使用dill代替pickle进行序列化,并方便地克服了这个问题。
只需在您的导入中安装multiprocess和替换:
https://stackoverflow.com/a/65001152/6239815
'''
import multiprocess.pool
return multiprocess.Pool(*a,**ka)
def pprint(*objects, stream=None, indent=1, width=133, depth=None,compact=False,confirm=False,**ka):
'''
pprint(
object,
stream=None,
indent=1,
width=80,
depth=None,
*,
compact=False,
)
'''
confirm=get_duplicated_kargs(ka,'ask','pause','yes','y','kill',default=confirm )
# if py.len(object)==1:object=object[0]
for object in objects: # 默认换行
try:
ipy=py.from_qgb_import('ipy')
return print(ipy.format(object),file=stream)
except:pass
from pprint import pprint as _pprint
_pprint(object=object,stream=stream,indent=indent,width=width,depth=depth,)