-
Notifications
You must be signed in to change notification settings - Fork 3
/
F.py
executable file
·1968 lines (1712 loc) · 59 KB
/
F.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
import sys as _sys;from os import path as _p#endswith 是为了适配qgb处于另外一个包内的情况
if __name__.endswith('qgb.F'):from . import py
else:import py
T=py.importT()
import os as _os
try:
from io import BytesIO
from io import BytesIO as bytesIO
from io import BytesIO as bio
from io import BytesIO as BIO
from pathlib import Path
except:pass
gError=[]
def setErr(ae):
global gError
U=py.importU()
if U.gbLogErr:# U.
if type(gError) is list:gError.append(ae)
elif gError:gError=[gError,ae]
else:gError=[ae]
else:
gError=ae
if U.gbPrintErr:U.pln('#Error ',ae)
def init_module():
global DEFAULT_ENCODING
if DEFAULT_ENCODING is None:
DEFAULT_ENCODING=U.get_or_set('F.read.encoding',lazy_default=lambda:py.No('utf-8'))
###################
class IntSize(py.int):
def __new__(cls, *a, **ka):
#int() argument must be a string, a bytes-like object or a number, not
if py.istr(a[0]) or py.isbyte(a[0]) or py.isnumber(a[0]):
self= py.int.__new__(cls, *a)
else:
self= a[0]
self.ka=ka
return self
def __str__(self):
U,T,N,F=py.importUTNF()
# s=
# repr=U.get_duplicated_kargs(self.ka,'repr','str','s','st','__repr__','__str__',no_pop=True)
# if repr:
# if py.callable(repr):
# return repr(self, **self.ka )
# else:
# return py.str(repr)
# return T.justify(s,**self.ka)+'>'
str_size=U.get_duplicated_kargs(self.ka,'size','str_size','repr_size','s',default=0)
return '<{}>'.format(int_to_size_str(self,str_size=str_size) )
# return
# return '<{}={}>'.format(super().__repr__(),F.ssize(self) )
def __repr__(self):return self.__str__()
################################
def dill_load_file_return_json_str(file):
x=dill_load_file(file=file)
if not x:return x
T=py.importT()
return T.json_dumps(x)
d2js=dill_to_json_str=dill_load_file_return_json_str
def pickle_monkeypatch():
import pickle
sk='pickle._Pickler.save'
if '<function _Pickler.save at' in py.repr(pickle._Pickler.save):
U=py.importU()
fsave=U.set(sk,pickle._Pickler.save)
print(pickle_monkeypatch.__name__,U.stime(),fsave,)
else:
return
fsave=U.get(sk)
def save(self, obj, save_persistent_id=True):
t=type(obj)
if t.__module__=='qgb.U' and 'qgb.U.object_custom_repr.<locals>.QGB_REPR_SUBTYPE' in repr(t):
ts=U.get_obj_hierarchy(obj)
obj=ts[1](obj)
fsave(self, obj,save_persistent_id)
pickle._Pickler.save=save
def gzip_decode(b):
import zlib
import urllib
# f=urllib.request.urlopen(url)
decompressed_data=zlib.decompress(b, 16+zlib.MAX_WBITS)
return decompressed_data
decode_gzip_bytes=gzip_decode
def read_levelDB(db_dir,debug=0):
'''
pip install plyvel-win32
conda install leveldb plyvel #不能用 ## plyvel.DB(db_dir) #进程退出 !!
pip install plyvel 装不上
'''
import plyvel
U,T,N,F=py.importUTNF()
db_dir=F.auto_path(db_dir)
db = U.get_or_set(db_dir,lazy_default=lambda:plyvel.DB(db_dir)) #只能打开一次 不然 IOError: b'IO error:
if db.closed:
db=U.set(db_dir,plyvel.DB(db_dir))
if debug:return db
r={}
with db.iterator() as it:
for k, v in it:
r[k]=v
# pass
return r
read_leveldb=read_levelDB
def get_file_owner_username(filename):
''' Windows : ModuleNotFoundError: No module named 'pwd'
'''
import pwd,os
return pwd.getpwuid(os.stat(filename).st_uid).pw_name
file_owner=file_username=get_file_user=get_file_username=get_file_owner_username
def zip(*fs,zip_filename='',ext='.zip'):
import zipfile,stat,os
if not fs:return fs
if not zip_filename:
f=fs[0]
zip_filename=f+ext
if not zip_filename.lower().endswith(ext):
zip_filename+=ext
with zipfile.ZipFile(zip_filename, 'w') as zipMe:
for file in fs:
if os.path.islink(file):
zipInfo = zipfile.ZipInfo(file)
zipInfo.create_system = 3 # System which created ZIP archive, 3 = Unix; 0 = Windows
unix_st_mode = stat.S_IFLNK | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH
zipInfo.external_attr = unix_st_mode << 16
zipMe.writestr(zipInfo,os.readlink(file))
else:
zipMe.write(file, compress_type=zipfile.ZIP_DEFLATED)
return zipMe
def compress_directory(source,target=py.No('auto use source name save in U.gst'),format='zip'):
''' shutil.make_archive file: NotADirectoryError: [WinError 267] 目录名称无效。: './U.py'
shutil.make_archive(
base_name,
format,
root_dir=None,
base_dir=None,
verbose=0,
dry_run=0,
owner=None,
group=None,
logger=None,
)
'''
import shutil
U,T,N,F=py.importUTNF()
if not source.endswith('/'):source+='/'
if not target:
target=T.sub_last(F.get_dirname_from_full_path(source),'/','/')
if not target:
target=T.file_legalized(source)
target=auto_path(target)
if target.lower().endswith('.zip') and target[-5]!='/':
target=target[:-4]
return shutil.make_archive(target, format, source) #return target
zip_dir=zip_directory=compress_directory
def open(file,mode='r',**ka):
'''py.open(
file,
mode='r',
buffering=-1,
encoding=None,
errors=None,
newline=None,
closefd=True,
opener=None,
)
'''
U,T,N,F=py.importUTNF()
mode=U.get_duplicated_kargs(ka,'mode','mod','m',default=mode)
if py.isfile(file):
#if file.closed==False:
return file
elif py.istr(file):
return py.open(file,mode=mode,**ka)
else:
raise py.ArgumentUnsupported(file,ka)
def test_long_filename():
'''
245
246
247
248
249 #FileNotFoundError Windows 10
'''
F=py.importF()
v='a234567890b234567890c234567890d234567890e234567890f234567890g234567890h234567890i234567890j234567890k234567890l234567890m234567890n234567890o234567890p234567890q234567890r234567890s234567890t234567890u234567890v234567890w234567890x234567890y234567890z23456789'# len(v)==259
p=F.mkdir(U.gst+'fn')
U.cd(p)
for n in range(245,260):
print(n)
with open(v[:n],'w') as f:f.write(str(n))
with open(p+v[:n],'w') as f:f.write(str(n))
#249 两个同样 #FileNotFoundError
# for n in range(245,260):
# print(n)
def sub_head(f,a,b=b''):
# br=
if not py.isbyte(a):
a=a.encode('utf-8')
U,T,N,F=py.importUTNF()
return F.write(f,T.sub(F.read_bytes(f),a,b))
sub=sub_head
def replace(f,ba,bb,encoding='utf-8'):
F=py.importF()
if not py.isbytes(ba):ba=ba.encode(encoding)
if not py.isbytes(bb):bb=bb.encode(encoding)
br= F.read_bytes(f).replace(ba,bb)
return F.write(f,br)
def expandUser(file='',user=''):
'''always return endswith /
import os, pwd
pwd.getpwuid(os.getuid()).pw_dir
'''
import os
h=os.path.expanduser('~'+user)
h=auto_path(h)
# if not r.endswith('/'):r=r+'/'
T=py.importT()
return T.replace_once(file,'~',h)
expand_user=expanduser=expandUser
def getHomeFromEnv():
import os
U=py.importU()
if U.isLinux():
name='HOME'
elif U.isWin():
name='USERPROFILE'
else:
raise EnvironmentError('#TODO system case')
r=U.getEnv(name)
r=autoPath(r)
if not r.endswith('/'):r=r+'/'
return r
home=gethome=get_home=getHome=getHomeFromEnv
def include(file,keyword):
if py.isbyte(keyword):mod='rb'
else:mod='r'
try:
with py.open(file,mod) as f:
for i in f:
if keyword in i:return True
except Exception as e:
return py.No(e)
return False
def stat(path, dir_fd=None, follow_symlinks=True):
U=py.importU()
IntSize,FloatTime,IntOct=U.IntSize,U.FloatTime,U.IntOct
import os
try:
if isinstance(path,os.stat_result):
s=path
else:
s=os.stat(path=path, dir_fd=dir_fd, follow_symlinks=follow_symlinks)
# return [
# path,
# IntSize(s.st_size),
# FloatTime(s.st_atime),
# FloatTime(s.st_mtime),
# FloatTime(s.st_ctime),
# IntOct (s.st_mode ),
# ]
except Exception as e:
return py.No(e)
r={}
for i in py.dir(s):
if not i.startswith('st_'):continue
v=getattr(s,i,py.No('Error getattr') )
if i=='st_size':r[i]=IntSize(v);continue
if i=='st_mode':r[i]=IntOct(v) ;continue
if i.endswith('time'):
r[i]=FloatTime(v)
continue
r[i]=v
return r
def repr_dill_load(obj):
''' 不用考虑文件问题,以后要统一 序列化系列函数,
但是这个函数序列化后是字符串,不能 autoArgs 是否是file参数
'''
def repr_dill_dump(obj):
'''#TODO not dill basic type : number,bytes,str, ... (all ast.literal_eval)
'''
return
def basic_dump(obj):
return py.repr(obj)
def basic_load(sobj):
T=py.importT()
return T.unrepr(sobj)
def deSerialize(obj=None,file=None):
'''The protocol version of the pickle is detected automatically, so no
protocol argument is needed. Bytes past the pickled object's
representation are ignored.
'''
if not py.isbyte(obj) and not file:raise py.ArgumentError('need bytes or file=str ')
import pickle
if py.istr(obj):
file=obj
obj=None
U.log('autoArgs file=%s'%file)
if py.isbyte(obj):
return pickle.loads(obj)
else:
file=autoPath(file)
with py.open(file,'rb') as f:
return pickle.load(f)
ds=pickle_load=unSerialize=unserialize=deserialize=deSerialize
def serialize(obj,file=None,protocol=0):
'''if not file: Return the pickled representation of the object as a bytes object.
'''
F=py.importF()
try:
import dill
return F.dill_dump(obj,file=file)
except Exception as e:
pass
import pickle
if file:
file=autoPath(file)
with py.open(file,'wb') as f:
pickle.dump(obj=obj,file=f,protocol=protocol)
return file
else:
return pickle.dumps(obj=obj,protocol=protocol)
s=obj_dump=dump=pickle_dump=serialize
def dill_load_file(file,dill_ext='.dill'):
import dill
dill.settings['ignore']=False #KeyError: 'ignore'
file=auto_path(file,ext=dill_ext)
try:
with py.open(file,'rb') as f:
return dill.load(f)
except Exception as e:#TODO all load save py.No
return py.No(file,e)
dl=dill_read=read_dill=dill_load=dill_load_file
def dill_load_bytes(bytes):
import dill
return dill.loads(bytes)
dls=dill_loads=dill_load_byte=dill_load_bytes
def dill_dump_bytes(obj,file=None,protocol=None,dill_ext='.dill'):
'''
#TODO file=0 Not write '../0.dill'
dill.dump(obj, file, protocol=None, byref=None, fmode=None, recurse=None)
dill.dumps(obj, protocol=None, byref=None, fmode=None, recurse=None)
ValueError: pickle protocol must be <= 4
r=request.get ...
F.readableSize(len(F.dill_dump(protocol=None,obj=r) ) )#'14.192 KiB'
F.readableSize(len(F.dill_dump(protocol=0,obj=r) ) ) #'15.773 KiB'
F.readableSize(len(F.dill_dump(protocol=1,obj=r) ) ) #'19.177 KiB'
F.readableSize(len(F.dill_dump(protocol=2,obj=r) ) ) #'18.972 KiB'
F.readableSize(len(F.dill_dump(protocol=3,obj=r) ) ) #'14.192 KiB'
F.readableSize(len(F.dill_dump(protocol=4,obj=r) ) ) #'13.694 KiB'
dill还包括几个pickle错误检测工具,在dill.detect module.
['at', 'baditems', 'badobjects', 'badtypes', 'children', 'code', 'dis', 'errors', 'freevars', 'getmodule', 'globalvars', 'iscode', 'isframe', 'isfunction', 'ismethod', 'istraceback', 'nestedcode', 'nestedglobals', 'outermost', 'parent', 'parents', 'reference', 'referredglobals', 'referrednested', 'trace', 'varnames', ...]
'''
import dill
from pickle import PicklingError
if file:
if py.istr(obj) and py.len(obj)<333 and '.dill' in obj:
if not py.istr(file) or '.dill' not in file:
file,obj=obj,file
file=auto_path(file,ext=dill_ext)
with py.open(file,'wb') as f:
try:
dill.dump(obj=obj,file=f,protocol=protocol)
except PicklingError as ep:
if 'qgb.U.object_custom_repr.<locals>.QGB_REPR_SUBTYPE' in ep.args[0]:
pickle_monkeypatch()
dill.dump(obj=obj,file=f,protocol=protocol)
else:
return py.No(ep)
return file
else:
return dill.dumps(obj=obj,protocol=protocol)
dp=dumps=dill_write=write_dill=dill_dump=dill_dumps=dill_dump_bytes
def dill_dump_string(obj,**ka):
U=py.importU()
encoding=U.get_duplicated_kargs(ka,'encoding','encode','coding')
if not encoding:
encoding=U.get_or_set('dill_string.encoding',default='latin')
return dill_dump_bytes(obj).decode(encoding)
dill_dump_str=dill_dump_string
def dill_load_string(s,**ka):
U=py.importU()
encoding=U.get_duplicated_kargs(ka,'encoding','encode','coding')
if not encoding:
encoding=U.get_or_set('dill_string.encoding',default='latin')
return dill_load_bytes(s.encode(encoding) )
dill_load_str=dill_load_string
TRY_MAX_LAYER=5
def try_dill_dump_recursively(obj,*a,):
global U
if not U:U=py.importU()
if py.len(a)>TRY_MAX_LAYER:return
try:
b=dill_dump_bytes(obj)
return (*a,U.size(b))
except Exception as e:
if py.islist(obj) or py.istuple(obj) or py.isset(obj):
r=[]
for n,v in py.enumerate(obj):
r.append([n,try_dill_dump_recursively(v,*a,n)])
return r
elif py.isdict(obj):
d={}
for n,(k,v) in py.enumerate( obj.items()):
d[n]=try_dill_dump_recursively(kv,*a,n)
return d
r=[]
for n,k,v in U.dir(obj):
r.append([k,try_dill_dump_recursively(v,*a,k)])
tryDillDumpRecursively=recursive_try_dill_dump=try_dill_dump_recursively
def test_dir_recursively(obj,*a):
U=py.importU()
if py.len(a)>TRY_MAX_LAYER:return
r=U.dir(obj)
for n,k,v in r:
r[n][2]=test_dir_recursively(v,*a,k) or v
return r
recursive_test_dir=test_dir_recursively
def recursive_test_dp(r):
U=py.importU()
if py.isdict(r) or py.getattr(r,'items',0):
r=[[n,k,v] for n,(k,v) in py.enumerate(r.items()) ]
if py.islist(r) or py.isdict(r):
pass
else:return r
for n,k,v in r:
try:
b=dill_dump_bytes(v)
r[n][2]=U.size(b)
except Exception as e:
r[n][2]=recursive_test_dp(v)
return r
def load(file,):
''' '''
def write(file,obj,):
''' '''
def chmod777(file,mode=0o777,):
import os
os.chmod(file, mode)
chmod=chmod777
def getMode(file):
import os
try:
r= oct(os.stat(file).st_mode)
if r[:5]!='0o100':raise Exception('不是100代表什么?',r)
return r[-3:]
except Exception as e:
return py.No(e)
getmode= getMode
def copy_with_src_dir_struct(abs_src_dir,abs_dst_dir,symlinks=False, ignore=None):
import shutil
U,T,N,F=py.importUTNF()
if U.isWin():raise NotImplementedError()
if abs_src_dir[-1] != '/':abs_src_dir+='/'
if not F.exist(abs_src_dir):return F.exist(abs_src_dir)
if abs_dst_dir[-1] != '/':abs_dst_dir+='/'
if not F.exist(abs_dst_dir):return F.exist(abs_dst_dir)
if not abs_dst_dir.endswith(abs_src_dir):
# if abs_src_dir.startswith('')
abs_dst_dir+=abs_src_dir
abs_dst_dir=abs_dst_dir.replace('//','/')
return shutil.copytree(abs_src_dir,abs_dst_dir, symlinks=symlinks,ignore=ignore,)
copy_src_dir_struct=copy_with_src_dir_struct
def copy(src,dst,src_base='',skip=''):
r''' src : sFilePath , list ,or \n strs
dst:sPath
return skip_list, copyed_list
'''
from shutil import copy as _copy
U,T,N,F=py.importUTNF()
if py.istr(skip):skip=[skip]
if not py.istr(dst):raise py.ArgumentError('dst must be str')
if py.istr(src):
if '\n' in src:
src=src.splitlines()
return copy(src,dst)
if src[-1] in ['/','\\']:
src=F.ls(src,r=1)
else:
dst_dir=F.get_dirname_from_full_path(dst)
F.mkdir(dst_dir)
try:
return _copy(src,dst)
except Exception as e:
return py.No(e)
if not src_base:
dl=U.unique(U.len(*src),ct=1)
min=py.min(*dl)
f=[i for i in src if py.len(i)==min][0]
if f[-1] in ['/','\\']:f=f[:-1]
# Path(f).absolute().parent.absolute().__str__()
src_base=f[:py.len(T.sub_last(f.replace('\\','/'),'','/') )+1]
src_base_len=py.len(src_base)
print('src_base: %r'%src_base,'len(src)==%s'%py.len(src))
while dst[-1] not in ['/','\\']:
dst=U.input('not dir! rewrite dst:',default=dst)
if py.iterable(src):
fns=[]
skips=[]
for i in src:
if U.one_in(skip,i):
skips.append(i)
continue
# fn=getName(i)
# if fn in fns:
# fn=T.fileName(i)
fn=i[src_base_len:]
if fn[-1] in ['/','\\']:
mkdir(dst+fn)
else:
_copy(i,dst+fn)
fns.append(fn)
if skips:return skips,fns
return fns
raise py.ArgumentUnsupported(src)
cp=copy
def modPathInSys(mod=None):
if mod:
if not py.istr(mod):mod=mod.__file__
else:mod=__file__
mod=mod.replace('\\','/')
inPath=False
if os.path.isabs(mod):
for i in sys.path:
i=i.replace('\\','/')
if i and mod.startswith(i):
if not i.endswith('/'):i+='/'
i+='qgb'
if mod.startswith(i):inPath=True
else:
raise NotImplementedError('__file__ not abs')
return inPath
def lineCount(a):
def blocks(files, size=65536):
while True:
b = files.read(size)
if not b: break
yield b
with py.open(a, "r") as f:
return sum(bl.count("\n") for bl in blocks(f))
def getPath(asp):
asp=asp.replace('\\','/')
if asp.endswith('/'):return asp
else:
if isDir(asp):return asp+'/'
else:
# _p.dirname('.../qgb/')# 'G:/QGB/babun/cygwin/lib/python2.7/qgb'
# _p.dirname('.../qgb')# 'G:/QGB/babun/cygwin/lib/python2.7'
return _p.dirname(asp)+'/'
def getPaths(a):
r''' a:str
'''
U=py.importU()
if U.iswin():
sp=a.replace('\\','/').split('/')
rlist=[]
def append(r):
if r and r not in rlist:rlist.append(r)
r=''
for i,v in enumerate(sp):
if len(v)>1 and v[-2] in T.AZ and v[-1]==':':
append(r)
r=v[-2:]+'/'
continue
for j in v:
if j not in T.PATH_NAME:
append(r)
r=''
continue
if r and v:
if isdir(r+v):r=r+v+'/'
else:
append(r)
r=''
continue
return rlist
else:
raise NotImplementedError('*nux')
def get_filename_from_full_path(a):
''' if a.endswith('/'):return ''
def name(
'''
a=a.replace('\\','/')
if '/' not in a:return a
else:
# import T
return T.subr(a,'/','')
fileName=filename=get_name=getname=getName=getNameFromPath=getFilename=get_filename=get_filename_from_full_path
# filename=fileName=getname=getName=name
def getNameWithoutExt(a):
''' see getNameFromPath
'''
a=getNameFromPath(a)
if '.' in a:
return T.subr(a,'','.')
else:return a
def auto_find_file(head,ext='',r='Default auto accroding to the head'):
'''r :recursion
return str
# TODO # ext=?ext* '''
if not py.type(ext)==py.type(head)==py.str or head=='':
return ''
if len(ext)>0 and not ext.startswith('.'):ext='.'+ext
head=head.lower();ext=ext.lower()
head=head.replace('\\','/')
if '/' in head:
if py.type(r) is py.str:
r=True
else:
r=False
ap='.'
if _p.isabs(head):
ap=dir(head)
if not isExist(ap):
if head.endswith(ext):return head
else:return head+ext
# import F
ls=[i.lower() for i in list(ap,r=r)]
if head+ext in ls:return head+ext
# import U
# U.pprint(ls)
for i in ls:
if i.startswith(head) and i.endswith(ext):return i
for i in ls:
if head in i and ext in i:return i
# if inMuti(ext,'*?'):ext=ext.replace('*')
if not head.endswith(ext):head+=ext
return head
autof=auto_find_file
def new(a):
'''will overwrite'''
try:
f=py.open(a,'w')
f.write('')
f.close()
return f.name
except Exception as e:
setErr(e)
return False
def isDir(ast):
'''#TODO:
'''
if not py.istr(ast):ast=py.str(ast)
if not ast:return False
ast=ast.replace('\\','/')
if exist(ast):
return _p.isdir(ast)
else:
if ast.endswith('/'):return True
else: return False
isPath=isdir=isDir
# if not ast.replace('.','').strip():return True # (不是 点和空格 返回 T)
# return ('/' in ast) or ('\\' in ast)
# return _p.sep in ast
# def is
def bin(a,split=''):
'''
bin(number, /)
F.bin(1.0)=='0b00111111100000000000000000000000' # (大端)
'''
import struct
if py.isint(a):
return py.bin(a)
r='0b'
if py.isfloat(a):
r=r+split.join(py.bin(i).replace('0b', '').rjust(8, '0') for i in struct.pack('!f', a))
elif py.isbytes(a):
r=r+split.join(py.bin(i).replace('0b', '').rjust(8, '0') for i in a)
else:
raise py.ArgumentUnsupported('#TODO type',a)
return r
def int_to_bytes(a):
T=py.importU().T
a=T.intToStr(a)
if py.len(a)%2==1:
a='0'+a
return hexToBytes(a)
i2b=intToBytes=int_to_byte=int_to_bytes
def byte_to_int(a):
return py.ord(a)
b2i=byte_to_int
def bytes_to_hex(a,split=''):
'''如果 len(split)是奇数,肯定返回 (奇数+偶数)=奇数
偶=》偶
'''
if py.is3():
# ord=lambda b:py.int.from_bytes(b,'big')
ord=lambda i:i
else:
ord=py.ord
r=split.join( [DIH[ord(i)] for i in a] )
return r
b2h=bytesToHex=bytes_to_hex
def string_to_hex(a,encoding='utf-8',split=' '):
if py.is_bytes(a):
return bytes_to_hex(a,split=split)
else:
return bytes_to_hex(a.encode(encoding),split=split)
s2h=str_hex=str_to_hex=string_to_hex
def hexToBytes(a,split='',ignoreNonHex=True):
a=a.upper();r=b''
if ignoreNonHex:a=''.join([i for i in a if i in '0123456789ABCDEF'])
it=2
if len(split)>0:it+=len(split)
if it==2 and len(a) % it!=0:return ()
if it>2:
a=a.split(split)
if len(a[-1]) == 0:a=a[:-1]
for i in a:
r+=py.byte(DHI[ i ])
return r
for i in range(py.int(py.len(a)/2 )):
r+=py.byte(DHI[a[i*2:i*2+2]])
return r
h2b=hexToBytes
def writeIterable(file,data,end='\n',overwrite=True,encoding=None):
U=py.importU()
if not encoding:encoding=U.encoding
file=autoPath(file)
if overwrite:new(file)
if py.is2():f=py.open(file,'a')
else: f=py.open(file,'a',encoding=encoding)
for i in data:
f.write(py.str(i)+end)
f.close()
return f.name
def write(file,data,mod='w',encoding='utf-8',mkdir=False,autoArgs=True,pretty=True,seek=None):
'''py3 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
py2 open(name[, mode[, buffering]])
pretty=True Format a Python object into a pretty-printed representation.
'''
U=py.importU()
try:
if autoArgs:
if py.istr(data) and py.len(file)>py.len(data)>0:
if '.' in data and '.' not in file and isFileName(data):
file,data=data,file
U.warring('F.write fn,data but seems data,fn auto corrected(v 纠正')
except:pass
# try:
file=autoPath(file)
if not encoding:encoding=U.encoding
if mkdir:makeDirs(file,isFile=True)
# if 'b' not in mod and py.isbytes(data):mod+='b'# 自动检测 data与 mod 是否匹配
if 'b' not in mod: #强制以 byte 写入
mod+='b'
f=py.open(file,mod)
#f.write(强制unicode) 本来只适用 py.is3() ,但 py2 中 有 from io import open
if py.isint(seek):
f.seek(seek)
# with open(file,mod) as f:
if py.isbyte(data):#istr(data) or (py.is3() and py.isinstance(data,py.bytes) ) :
f.write(data)
elif (py.is2() and py.isinstance(data,py.unicode)) :
f.write(data.encode(encoding))
elif (py.is3() and py.istr(data)):
# if 'b' in mod.lower():
f.write(data.encode(encoding))
# else:f.write(data)#*** UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in
else:
# if py.is2():print >>f,data
# else:
if pretty:
data=U.pformat(data)
U.pln(data,file=f)
f.close()
return f.name
# except Exception as e:
# setErr(e)
# return False
gb_write_auto_filename_len=True
def write_auto_filename(*a,**ka):
all_args=py.importU().getArgsDict()
# py.pdb()()
# return all_args
U=py.importU()
T=py.importT()
name=U.get_duplicated_kargs(ka,'name',default=None)
ext=U.get_duplicated_kargs(ka,'extension','ext',default='.txt')
if ext and not ext.startswith('.'):ext='.'+ext
sp=mkdir(U.gst+write_auto_filename.__name__)
rf=[]
for k,v in all_args.items():
if py.istuple(v) and py.len(v)==1:
v=v[0]
fn='{}{}'.format(sp,T.filename_legalized(k))
if gb_write_auto_filename_len:
len=U.len(v)
if py.isint(len):
fn+='={}{}'.format(len,ext)
f=write(fn ,v,autoArgs=False)
rf.append(f)
return rf
writeA=write_auto_args=write_args=write_auto_filename
def insert_head_line(file,data,char_index=0):
''' 没有很好的办法,除了 先全部读出再写入
'''
raise NotImplementedError()
# f = fileinput.input(file, inplace=1)
# for xline in f:
# if f.isfirstline():
# print line_to_prepend.rstrip('\r\n') + '\n' + xline,
# else:
# print xline,
return
line_pre_adder=insert=insert_head_line
def append(file,data):
'''builtin afile.write() No breakLine'''
return write(file,data,mod='a')
def detect_file_encoding(file,confidence=0.7,default=py.No('not have default encoding'),buffer_size=9999,p=True,**ka):
U,T,N,F=py.importUTNF()
p=U.get_duplicated_kargs(ka,'print_file_encoding','print_detect_encoding','print',default=p,no_pop=True)
if py.istr(file):
with py.open(file,'rb') as f:
b=f.read(buffer_size)
elif py.isfile(file):
if 'b' not in file.mode:raise py.ArgumentError("'b' not in file.mode",file)
i=file.tell()
b=file.read(buffer_size)
file.seek(i)
else:raise py.ArgumentError('need str or file')
c= T.detect(b,confidence=confidence,default=default)
if p:print(file,c) #TODO U.get_or_set('detect_file_encoding.p',True)
return c
detect=detectEncoding=detect_encoding=detect_file_encoding
DEFAULT_ENCODING=None
def read(file,encoding='utf-8',mod='r',return_filename=False,print_detect_encoding=False,**ka):
'''if return_filename:
return content,f.name
1 not is 2
^
SyntaxError: invalid syntax
'''
file=autoPath(file)
if not encoding and print_detect_encoding:
U=py.importU()
_pde=U.get_duplicated_kargs(ka,'print_encoding','p_encoding','p','pde','pEncoding','p_decode')
if not _pde is U.GET_DUPLICATED_KARGS_DEFAULT: #记住绝对不能用 ==
# print_detect_encoding=_pde
print_detect_encoding=False
if not return_filename:
U=py.importU()
return_filename=U.get_duplicated_kargs(ka,'returnFile','rf','rfn','return_file','return_name',)
if py.is2():
f=py.open(file,mod)
s=f.read()
f.close()
else:#is3
#utf-8 /site-packages/astropy/coordinates/builtin_frames/__init__.py {'confidence': 0.73, 'encoding': 'Windows-1252'
if encoding:
try:
f=py.open(file,mod,encoding=encoding)
s=f.read()
f.close()
except:encoding=''
if not encoding:
U,T,N,F=py.importUTNF()
r2=T.detect_and_decode(F.read_byte(file),confidence=0.9,default='utf-8',return_encoding=True)
if not r2:return r2
U.set('r2',r2)
encoding,s=r2
if print_detect_encoding:print(file,encoding)
if return_filename:
return s,f.name
else:
return s
# except Exception as e:
# return f,e
# if 'f' in py.dir() and f:f.close()
# return ()
def read_multi_files_return_bytes_list(*fs,max_size=8*1024*1024,return_all_bytes=False):
r=[]
def append(a):