-
Notifications
You must be signed in to change notification settings - Fork 1
/
pipTerminal.py
1204 lines (1164 loc) · 55.1 KB
/
pipTerminal.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
#!python3
"""
Pythonista3 Console Terminal.
Version: 2.1.0
Author: DarkRix.
"""
import base64, code, console, concurrent.futures, io, lib2to3.main, os, re, requests, shutil, socket, ssl, sys, urllib.error, urllib.request, urllib.parse, platform, qrcode, tempfile, time, tarfile, zipfile
from PIL import Image
from objc_util import ObjCClass
ssl._create_default_https_context = ssl._create_unverified_context
class QRCodeView(object):
def __init__(self, url):
self.url = url
self.filename = 'tmpQR.png'
self.tmpFolder = tempfile.gettempdir()
self.tempPath = os.path.join(self.tmpFolder, self.filename)
qrcode.make(self.url).save(self.tempPath)
def __enter__(self):
return self.tempPath
def __exit__(self, _, __, ___):
os.remove(self.tempPath)
class ImageLoad(object):
def __init__(self):
self.ImageData = None
self.Image = Image
Image.Image.tostring = self.tostring
def tostring(self):
return self.ImageData.tobytes()
def open(self, fp):
try:
self.ImageData = self.Image.open(fp).convert('RGBA')
return self.Image.open(fp).convert('RGBA')
except:
self.ImageData = self.Image.open(fp)
return self.Image.open(fp)
class pipTerminal(object):
def __init__(self):
self.Command_DIRNAME = ['{}@{}'.format(os.getenv('USER'), platform.node()), '', '']
self.BackupSTDOUT = sys.stdout
self.is_Exits = True
self.HOME_DIC = os.getcwd()
self.printed_STDOUT = [None]
try:
os.makedirs(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin'), exist_ok=True)
os.makedirs(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'bin'), exist_ok=True)
shutil.copytree(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'bin'), os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin'), dirs_exist_ok=True)
shutil.rmtree(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'bin'))
os.makedirs(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'bin'), exist_ok=True)
except:
pass
def _2to3(self, pyArgs):
try:
sys.argv[1:] = pyArgs
except:
pass
try:
lib2to3.main.main('lib2to3.fixes')
except:
pass
def SystemLogo(self):
console.clear()
console.set_color(255, 0, 0) # red
return "{}\n| - pyTerminal v2.0.8 on Python {}\t\t\t|\n| - Author: DarkRix.\t\t\t\t\t\t|\n| - Show All Command: help\t\t\t\t\t|\n{}\n\n".format("-"*41, platform.python_version(), "-"*41)
def pbcopy(self, text: str): # Copy String
if type(text) == str: # text file...
ObjCClass('UIPasteboard').generalPasteboard().setString(text)
else: # Image file...
ObjCClass('UIPasteboard').generalPasteboard().setImage_(ObjCClass('UIImage').imageWithData_(text))
def pbpaste(self): # Paste
if ObjCClass('UIPasteboard').generalPasteboard().string() is not None:
return ObjCClass('UIPasteboard').generalPasteboard().string().UTF8String().decode()
else:
return ''
def copyFiles(self, FileName, dest):
try:
if os.path.isfile(os.path.join(os.getcwd(), FileName)):
shutil.copy(FileName, dest)
elif os.path.isdir(os.path.join(os.getcwd(), FileName)):
shutil.copytree(FileName, dest)
except:
pass
def detect_file(self, file):
if file.split('.')[-1].lower() == 'py':
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'cpp':
console.set_color()
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'c':
console.set_color()
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'java':
console.set_color()
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'plist':
console.set_color()
console.set_color(0, 10, 255)
return file
elif file.split('.')[-1].lower() == 'json':
console.set_color()
console.set_color(0, 10, 255)
return file
elif file.split('.')[-1].lower() == 'jpg':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'jpeg':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'png':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'bmp':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'gif':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'tiff':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'rgb':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'xbm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'pbm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'pgm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'ppm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'xbm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'rast':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'zip':
console.set_color()
console.set_color(255, 1, 0)
return file
elif file.split('.')[-1].lower() == 'rar':
console.set_color()
console.set_color(255, 1, 0)
return file
elif file.split('.')[-1].lower() == 'tar':
console.set_color()
console.set_color(255, 1, 0)
return file
elif file.split('.')[-1].lower() == 'bz2':
console.set_color()
console.set_color(255, 1, 0)
return file
elif file.split('.')[-1].lower() == 'gz':
console.set_color()
console.set_color(255, 1, 0)
return file
elif file.split('.')[-1].lower() == 'md':
console.set_color()
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'MD':
console.set_color()
console.set_color(0, 102, 0)
return file
elif file.split('.')[-1].lower() == 'mp4':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'm4v':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'avi':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'webm':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'flv':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'wmv':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'mov':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'm4a':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'mp3':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'ogg':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'aac':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'flac':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'aiff':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'wav':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'wma':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'asf':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'oga':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'alac':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'ape':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'mac':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'tta':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'mka':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'mkv':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'aif':
console.set_color()
console.set_color(255, 0, 0)
return file
elif file.split('.')[-1].lower() == 'aifc':
console.set_color()
console.set_color(255, 0, 0)
return file
elif os.path.islink(os.path.join(os.getcwd(), file)):
console.set_color()
console.set_color(255, 0, 255)
return file
elif os.path.isdir(os.path.join(os.getcwd(), file)):
console.set_color()
console.set_color(0, 0, 205)
return file
else:
console.set_color()
return file
def delete_Files(self, Name):
try:
if os.path.isfile(os.path.join(os.getcwd(), Name)):
os.remove(Name)
elif os.path.islink(os.path.join(os.getcwd(), Name)):
os.unlink(os.path.join(os.getcwd(), Name))
elif os.path.isdir(os.path.join(os.getcwd(), Name)):
shutil.rmtree(Name)
except Exception as e:
print(e)
def argument_help(self, Args):
if Args[1] == '--help':
Args[1] = '-h'
if Args[1] == '-h' and Args[0] == 'cat':
print("Usage: cat [-h] [files [files ...]]")
if Args[1] == '-h' and Args[0] == 'cd':
print("Usage: cd [-h] [dir]\n\nChange the Current working directory.")
if Args[1] == '-h' and Args[0] == 'cp':
print("Usage: cd [-h] [dir]\n\nChange the Current working directory.")
if Args[1] == '-h' and Args[0] == 'echo':
print("Usage: echo [-h]\n\nPrint All arguments to stdout, separated by space")
if Args[1] == '-h' and Args[0] == 'delclip':
print('Delete Clipboard')
if Args[1] == '-h' and Args[0] == 'showip':
print('Show you are Local & Global iP Adress')
if Args[1] == '-h' and Args[0] == 'git':
print('Usage: git clone <url> [path] - clone a remote repository')
if Args[1] == '-h' and Args[0] == 'la':
print("Usage: la [-h] [-l] [files [files ...]]")
if Args[1] == '-h' and Args[0] == 'ls':
print("Usage: ls [-h] [-l] [files [files ...]]")
if Args[1] == '-h' and Args[0] == 'ln':
print("Usage: ln [-h] lhs rhs\n\nCreate Symblic Link.")
if Args[1] == '-h' and Args[0] == 'mkdir':
print("Usage: mkdir [-h] [-p] dir [dir ...]\n\nCreate a new directory.\nThe parent directory must specified.")
if Args[1] == '-h' and Args[0] == 'mv':
print("Usage: mv [-h] src [src ...] dest\n\nMove(Rename) a file or directory to a new name, or into a new directory.")
if Args[1] == '-h' and Args[0] == 'ping':
print("Usage: ping [-h] [iP]\nDestination\n\nSend ping to network hosts.")
if Args[1] == '-h' and Args[0] == 'rm':
print("Usage: rm [-h] paths [paths ...]")
if Args[1] == '-h' and Args[0] == 'python':
print("Usage: python [-h] [file]\n\nPython Interactive Shell.")
if Args[1] == '-h' and Args[0] == 'py':
print("Usage: py [-h] [file]\n\nPython Interactive Shell.")
if Args[1] == '-h' and Args[0] == 'python3':
print("Usage: python3 [-h] [file]\n\nPython Interactive Shell.")
if Args[1] == '-h' and Args[0] == 'py3':
print("Usage: py3 [-h] [file]\n\nPython Interactive Shell.")
if Args[1] == '-h' and Args[0] == 'wget':
print("Usage: wget [-h] [url]\n\nA simple File Download.")
if Args[1] == '-h' and Args[0] == 'unzip':
print('Usage: unzip [-h] [file]')
if Args[1] == '-h' and Args[0] == 'zip':
print('Usage: zip [-h] [OutPutFileName] [Target]')
if Args[1] == '-h' and Args[0] == 'qrcode':
print('Usage: qrcode [-h] [URL]')
def git_clone(self, gitArgs):
try:
gitPATH = gitArgs[1]
except IndexError:
gitPATH = os.getcwd()
except:
gitPATH = os.getcwd()
if len(gitArgs) > 0:
rURL = gitArgs[0]
if rURL.endswith('.git'):
rURL = rURL[:-4]
UserName, ProjectName = re.match('https://github.com/(.+)/(.+)', rURL).groups()[0:2]
gitFileName = gitPATH + '/' + ProjectName
fURL = 'https://github.com/{USER}/{PROJECT}/archive/master.zip'.format(USER=UserName, PROJECT=ProjectName)
try:
RESPONSE_DATA = urllib.request.urlopen(urllib.request.Request(fURL, headers={'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; en-la) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 YJApp-ANDROID jp.co.yahoo.android.yjtop/13.91.1','Connection': 'keep-alive','Accept-Encoding': 'identity'})).read()
master_name = 'master'
except urllib.error.URLError:
reURL = 'https://github.com/{}/{}'.format(UserName, ProjectName)
FFdata = urllib.request.urlopen(urllib.request.Request(reURL, headers={'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; en-la) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 YJApp-ANDROID jp.co.yahoo.android.yjtop/13.91.1','Connection': 'keep-alive','Accept-Encoding': 'identity'})).read()
Pattern = '{}/{}/tree/(.*?)/'.format(UserName, ProjectName)
master_name = re.findall(Pattern, str(FFdata))[-1]
ffURL = 'https://codeload.github.com/{}/{}/zip/{}'.format(UserName, ProjectName, master_name)
RESPONSE_DATA = urllib.request.urlopen(urllib.request.Request(ffURL, headers={'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; en-la) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36 YJApp-ANDROID jp.co.yahoo.android.yjtop/13.91.1','Connection': 'keep-alive','Accept-Encoding': 'identity', 'HOSTS': 'github.com'})).read()
with zipfile.ZipFile(io.BytesIO(RESPONSE_DATA), 'r') as Fzip:
Fzip.extractall(gitPATH+'/.')
vName = gitFileName + '-' + master_name
if os.path.exists(vName):
os.rename(vName, gitFileName)
print('Done')
def listdir(self, arg, pwd):
hOME = os.getenv('HOME')
if arg == 'long':
listdirs = sorted(os.listdir())
len_dir_lists = len(listdirs)
for lis in range(len_dir_lists):
if os.path.islink(os.path.join(pwd, listdirs[lis])):
try:
print('[%s] %s -> %s' % (time.strftime("%Y-%m-%d", time.localtime(os.stat(os.path.join(pwd, listdirs[lis])).st_mtime)),self.detect_file(listdirs[lis]), os.path.realpath(os.path.join(pwd, listdirs[lis])).replace(hOME, '~')))
except:
continue
console.set_color()
else:
try:
print('[%s] %s' % (time.strftime("%Y-%m-%d", time.localtime(os.stat(os.path.join(pwd, listdirs[lis])).st_mtime)),self.detect_file(listdirs[lis])))
except:
continue
console.set_color()
elif arg == None:
try:
listdirs = sorted(os.listdir())
len_dir_list = len(listdirs)
for li in range(len_dir_list):
print(self.detect_file(listdirs[li]))
console.set_color()
except Exception as E:
print(E)
def list_stash_bin(self):
sh_bin_list = sorted(os.listdir(os.path.join(os.getenv('HOME'), 'Documents', 'stash_extensions', 'bin')))
for DIR_PATH in range(len(sh_bin_list)):
try:
if os.path.isdir(sorted(os.path.join(os.getenv('HOME'), 'Documents', 'stash_extensions', 'bin', sh_bin_list[DIR_PATH]))):
del sh_bin_list[DIR_PATH]
except:
pass
try:
if sh_bin_list[DIR_PATH].split('.')[-1].lower() == 'py':
sh_bin_list[DIR_PATH] = sh_bin_list[DIR_PATH].replace('.py','')
except:
pass
return ', '.join(sh_bin_list)
def list_other_cmd(self):
list = sorted(os.listdir(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin')))
for d in range(len(list)):
try:
if os.path.isdir(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin', list[d])):
del list[d]
except:
pass
return ', '.join(list)
def ping(self, host):
_p = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_p.settimeout(1)
f_time = time.time()
try:
_p.connect((host, 80))
except socket.timeout:
pass
except Exception as ERR:
if '22' in str(ERR) or 'argument' in str(ERR):
pass
if 'refused' not in str(ERR):
raise(ERR)
e_time = time.time()
_p.close()
ping_result = 'PING to {HOST} Time: {TIME}ms'.format(HOST=host, TIME=round(((e_time - f_time) * 1000), 2))
return ping_result
def readfile(self, Name):
if Name.endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff', '.rgb', '.pgm', '.pbm', '.ppm', '.xbm')):
rfile = ImageLoad().open(Name)
self.printed_STDOUT[0] = rfile
return '3'
else:
rfile = open(Name, 'rb').read()
self.printed_STDOUT[0] = rfile
return '0'
def run_stash_bin(self, cmdName, Sargs):
try:
stash_bin_path = os.path.join(os.getenv('HOME'), 'Documents', 'stash_extensions', 'bin')
Rcommand_name = cmdName + '.py'
RfileName = os.path.join(stash_bin_path, Rcommand_name)
RFile_read = open(RfileName, 'r', encoding='utf-8').read()
sys.argv[1:] = Sargs
try:
exec(RFile_read)
except:
pass
except FileNotFoundError:
pass
except Exception as E:
print('ERROR: {}'.format(E))
def run_other_cmd(self, cmd_name, args):
try:
cmd_bin = os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin')
fileNa = os.path.join(cmd_bin, cmd_name)
_read = open(fileNa, 'r', encoding='utf-8').read()
sys.argv[1:] = args
try:
exec(_read)
except:
pass
except FileNotFoundError:
self.run_stash_bin(cmd_name, args)
except Exception as E:
print('ERROR: {ERR}'.format(ERR=E))
def Symbolic_Link(self, Src, Dest):
try:
if os.path.isfile(Dest):
print('{DEs} Already Exists'.format(DEs=Dest))
pass
if os.path.islink(Dest):
print('{DEst} Already Linked'.format(DEs=Dest))
pass
except:
pass
try:
os.symlink(Src, Dest)
except Exception as E:
print('Error: {ERR}.'.format(ERR=E))
def wget(self, URL, filename=''):
user_agent = {'User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.0; en-la; Nexus Build/JPG991) AppleWebKit/511.2 (KHTML, like Gecko) Version/5.0 Mobile/11S444 YJApp-ANDROID jp.co.yahoo.android.yjtop/4.01.1.5'}
if filename == '':
output_fileName = urllib.parse.unquote(urllib.parse.unquote(URL.split('/')[-1]))
else:
output_fileName = filename
try:
ur = urllib.request.urlopen(urllib.request.Request(URL, headers=user_agent))
md = ur.info()
try:
fs = int(md["Content-Length"])
except (IndexError, ValueError, TypeError):
fs = 0
print("Save as: {File} ".format(File=output_fileName))
print("({Size} bytes)".format(Size=fs if fs else "???"))
with open(output_fileName, 'wb') as f:
fs_dl = 0.0
blsz = 8192
while True:
_b = ur.read(blsz)
if not _b:
break
fs_dl += len(_b)
f.write(_b)
except:
try:
print('downloading.....')
uu = requests.get(URL, headers=user_agent)
try:
File_size = int(uu.headers['Content-Length'])
except (IndexError, ValueError, TypeError):
File_size = 0
if uu.headers['Content-Type'] == 'application/json':
with open(output_fileName, 'w') as F:
F.write(uu.json())
print('save as {}'.format(output_fileName))
print("({} bytes)".format(File_size if File_size else "???"))
else:
with open(output_fileName, 'wb') as Fb:
Fb.write(uu.content)
print('Save as: {}'.format(output_fileName))
print("({} bytes)".format(File_size if File_size else "???"))
except Exception:
print('Error. URL: {}'.format(URL))
def help_tar(self):
print('tar [-h] [-j] [-z] [-x] [file [files ...]]')
print('Support Archive Type: tar.gz or tar.')
print('This command is extract only.')
def TarArgument(self, ARGS):
try:
if 'x' in ARGS[1][1:]:
if 'z' in ARGS[1][1:]:
try:
tExtract_ALL(os.path.join(os.getcwd(), ARGS[2][0:]), ARGS[1][1:])
except:
pass
elif 'j' in ARGS[1][1:]:
try:
tExtract_ALL(os.path.join(os.getcwd(), ARGS[2][0:]), ARGS[1][1:])
except:
pass
elif ARGS[1][1:] == '--help':
self.help_tar()
elif 'h' in ARGS[1][1:]:
self.help_tar()
else:
self.help_tar()
except IndexError:
self.help_tar()
except KeyboardInterrupt:
sys.exit(0)
except:
pass
def ExtractMems(self, mem, ext):
for tf in mem:
for pt in ext:
if tf.name == pt or tf.name.startswith(pt):
yield tf
def tExtract_ALL(self, FName, tArgs, mems=None, Dir='./'):
if 'z' in tArgs[0]:
print('Reading gzip file')
tar = tarfile.open(FName, 'r:gz')
elif 'j' in tArgs[0]:
print('Reading bz2 file')
tar = tarfile.open(FName, 'r:bz2')
if mems:
tar.extractall(path=Dir, members=self.ExtractMems(tar, mems))
else:
tar.extractall(path=Dir)
tar.close()
print('Archive Extracted')
def ZIPExtractor(self, zFileName):
if not os.path.isfile(zFileName):
print('{}: No such File...'.format(zFileName))
else:
try:
pk_Check = open(zFileName, 'rb').read(2)
except:
pk_Check = ''
if pk_Check != b'PK':
print('{}: Dose not appear to be a ZIPFile.'.format(zFileName))
if os.path.basename(zFileName).lower().endswith('.zip'):
ALPath = os.path.splitext(os.path.basename(zFileName))[0]
else:
ALPath = os.path.basename(zFileName) + '_UnZIPPED'
ALPath = os.path.join(os.path.dirname(zFileName), ALPath)
if (os.path.exists(ALPath)) and not (os.path.isdir(ALPath)):
print('{}: Destination is not a Directory.'.format(ALPath))
elif not os.path.exists(ALPath):
os.makedirs(ALPath, exist_ok=True)
try:
ZIPfp = open(zFileName, 'rb')
ZipF = zipfile.ZipFile(ZIPfp)
DIR_NAME = [os.path.join(os.path.dirname(_z), '') for _z in ZipF.namelist()]
COMMON_DIR = os.path.commonprefix(DIR_NAME or ['/'])
if not COMMON_DIR.endswith('/'):
COMMON_DIR = os.path.join(os.path.dirname(COMMON_DIR), '')
for zNa in ZipF.namelist():
zData = ZipF.read(zNa)
Fn = zNa
if COMMON_DIR:
if Fn.startswith(COMMON_DIR):
Fn = Fn.split(COMMON_DIR, 1)[-1]
elif Fn.startswith('/' + COMMON_DIR):
Fn = Fn.split('/' + COMMON_DIR, 1)[-1]
Fn = Fn.lstrip('/')
Fn = os.path.join(ALPath, Fn)
DIRf = os.path.dirname(Fn)
if not os.path.exists(DIRf):
os.makedirs(DIRf, exist_ok=True)
if Fn.endswith('/'):
if not os.path.exists(Fn):
os.makedirs(Fn, exist_ok=True)
else:
Fp = open(Fn, 'wb')
try:
Fp.write(zData)
finally:
Fp.close()
print(Fn)
except:
print('{}: ZIP File is Corrupt'.format(zFileName))
def ZipArchiveCreate(self, ziPFilename, IPath):
REL_ROOT = os.path.abspath(os.path.dirname(ziPFilename))
with zipfile.ZipFile(ziPFilename, 'w', zipfile.ZIP_DEFLATED) as OutPutsZip:
if os.path.isfile(IPath):
print(IPath)
ARCHiveName = os.path.relpath(IPath, REL_ROOT)
OutPutsZip.write(IPath, arcname=ARCHiveName)
elif os.path.isdir(IPath):
for Root, Dir, Files in os.walk(IPath):
TH_RELROOT = os.path.relpath(Root, REL_ROOT)
OutPutsZip.write(Root, arcname=TH_RELROOT)
print(TH_RELROOT)
for _Fi in Files:
Fi_Name = os.path.join(Root, _Fi)
if os.path.isfile(Fi_Name):
print(Fi_Name)
ARCHIVE_NAME = os.path.join(TH_RELROOT, _Fi)
OutPutsZip.write(Fi_Name, arcname=ARCHIVE_NAME)
def delelemnts(self, element):
while True:
try:
if '' in element:
element.remove('')
else:
break
except:
break
return element
def Argument_Paser(self, Args):
console.set_color()
try:
try:
self.argument_help(Args)
except IndexError:
pass
try:
if Args[0] == 'help':
try:
print('[Default commands]:\nhelp, 2to3, cat, cd, echo, env, git(clone only), la, ls, ln, mkdir, open, ping, rm, tar, uznip, wget, zip, python, python3, qrcode, pbcopy, pbpaste, delclip, showip, exit\n\n[Third Party commands]:\n' + self.list_other_cmd() + '\n\n[Stash Extensions Commands]:\n' + self.list_stash_bin())
except:
try:
print('[Default commands]:\nhelp, 2to3, cat, cd, echo, env, git(clone only), la, ls, ln, mkdir, open, ping, rm, tar, uznip, wget, zip, python, python3, qrcode, pbcopy, pbpaste, delclip, showip, exit\n\n[Third Party commands]:\n' + self.list_other_cmd())
except:
print('[Default commands]:\nhelp, 2to3, cat, cd, echo, env, git(clone only), la, ls, ln, mkdir, open, ping, rm, tar, uznip, wget, zip, python, python3, qrcode, pbcopy, pbpaste, delclip, showip, exit\n')
elif Args[0] == 'cat':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
ViewFile = self.readfile(Args[1])
if ViewFile[0] == '0':
try:
print(self.printed_STDOUT[0].decode())
except:
print('Error: Read Text File?')
elif ViewFile[0] == '3':
print('{}'.format(console.show_image(Args[1])).split('None')[0])
else:
pass
except:
pass
elif Args[0] == '2to3':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
self._2to3(Args[1:])
else:
pass
except:
pass
elif Args[0] == 'pbcopy':
self.pbcopy(Args[1])
elif Args[0] == 'pbpaste':
self.pbpaste()
elif Args[0] == 'delclip':
self.pbcopy('')
elif Args[0] == 'showip':
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
user_agent = {'User-Agent': 'Mozilla/5.0 (Linux; U; Android 8.0; en-la; Nexus Build/JPG991) AppleWebKit/511.2 (KHTML, like Gecko) Version/5.0 Mobile/11S444 YJApp-ANDROID jp.co.yahoo.android.yjtop/4.01.1.5'}
s.connect(('8.8.8.8', 80))
print('Local iP: {}\nGlobal iP: {}'.format(s.getsockname()[0], concurrent.futures.ThreadPoolExecutor().submit(urllib.request.urlopen, urllib.request.Request('http://checkip.amazonaws.com', headers=user_agent)).result().read().decode(errors='ignore').split('\n')[0]))
except:
pass
elif Args[0] == 'cd':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if '$' in Args[1] and '/' in Args[1]:
Arg1 = Args[1].replace('$', os.getenv(Args[1].split('$')[1].split('/')[0]))
Args[1] = Args.replace(Args[1].split('$')[1].split('/')[0], '')
try:
if Args[1][0] == '$':
try:
os.chdir(os.getenv(Args[1][1:]))
except Exception as E:
print('ERROR:{}'.format(E))
else:
try:
os.chdir(Args[1])
except Exception as E:
print('ERROR:{}'.format(E))
except IndexError:
try:
os.chdir(self.HOME_DIC)
except Exception as E:
print('ERROR:{}'.format(E))
if Args[1] == '' or Args[1] == ' ':
try:
os.chdir(self.HOME_DIC)
except Exception as E:
print('ERROR:{}'.format(E))
except:
pass
else:
pass
except:
try:
os.chdir(self.HOME_DIC)
except Exception as E:
print('ERROR:{}'.format(E))
elif Args[0] == 'cp':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if not '/' in Args[2]:
self.copyFiles(os.path.join(os.getcwd(),Args[1]),os.path.join(os.getcwd(), Args[2]))
else:
self.copyFiles(os.path.join(os.getcwd(),Args[1]), Args[2])
else:
pass
except:
pass
elif Args[0] == 'echo':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
try:
if Args[1][0] == '$':
env_data = os.getenv(Args[1][1:])
if not env_data is None:
print(env_data)
except:
pass
else:
pass
except IndexError:
print('')
except:
pass
elif Args[0] == 'env':
try:
for im, vl in os.environ.items():
console.set_color(255, 0, 0)
print('{}'.format(im), end=': ')
console.set_color()
print(vl)
except:
pass
elif Args[0] == 'git':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if Args[1] == 'clone':
self.git_clone(Args[2:])
else:
print('git is clone only')
else:
pass
except:
pass
elif Args[0] == 'la' or Args[0] == 'ls':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if Args[1] == '-l':
self.listdir('long', os.getcwd())
else:
self.listdir(None, None)
else:
pass
except IndexError:
self.listdir(None, None)
except:
pass
elif Args[0] == 'ln':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if Args[1] == '-s':
try:
if not '/' in Args[2] and not '/' in Args[3]:
self.Symbolic_Link(os.path.join(os.getcwd(), Args[2]), os.path.join(os.getcwd(), Args[3]))
else:
self.Symbolic_Link(Args[2], Args[3])
except:
pass
else:
try:
if not '/' in Args[1]:
self.Symbolic_Link(os.path.join(os.getcwd(), Args[1]), Args[2])
else:
self.Symbolic_Link(Args[1], Args[2])
except:
pass
else:
pass
except:
pass
elif Args[0] == 'pip':
try:
if not os.path.exists(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin', 'pip')):
with open(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin', 'pip'), 'w') as pipF:
pipF.write("# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom pip._internal.cli.main import main\nif __name__ == '__main__':\n sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])\n sys.exit(main())")
cmd_bin_path = os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', '_bin')
fileNa = os.path.join(cmd_bin_path, 'pip')
_read = open(fileNa, 'r', encoding='utf-8').read()
sys.argv[1:] = Args[1:]
try:
exec(_read)
except:
pass
if os.path.exists(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'lib', 'python3.1', 'site-packages')):
shutil.copytree(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'lib', 'python3.1', 'site-packages'), os.path.join(os.getenv('HOME'), 'Documents', 'site-packages'), dirs_exist_ok=True)
shutil.rmtree(os.path.join(os.getenv('HOME'), 'Documents', 'site-packages', 'lib'))
self.__init__()
except:
pass
elif Args[0] == 'mkdir':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
if Args[1] == '-p':
os.makedirs(Args[2], exist_ok=True)
else:
os.makedirs(Args[1], exist_ok=True)
else:
pass
except:
pass
elif Args[0] == 'qrcode':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
with QRCodeView(Args[1]) as QR:
print('{}'.format(console.show_image(QR)).split('None')[0])
else:
pass
except:
pass
elif Args[0] == 'mv':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
try:
shutil.move(Args[1], Args[2])
except IndexError:
pass
except Exception as E:
print(E)
else:
pass
except:
pass
elif Args[0] == 'open':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
try:
console.quicklook(Args[1])
except Exception as E:
print(E)
else:
pass
except:
pass
elif Args[0] == 'ping':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
try:
for _P in range(3):
print(self.ping(Args[1]))
time.sleep(1)
except:
pass
else:
pass
except:
pass
elif Args[0] == 'pwd':
try:
path = os.getcwd()
except Exception as E:
path = E
print(path)
elif Args[0] == 'rm':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
try:
if '$' in Args[1] and '/' in Args[1]:
Arg1 = Args[1].replace('$', os.getenv(Args[1].split('$')[1].split('/')[0]))
Args[1] = Args.replace(Args[1].split('$')[1].split('/')[0], '')
if Args[1][0:] == './*':
try:
for _rm in range(len(os.listdir('./'))):
self.delete_Files(os.listdir()[_rm])
except:
pass
else:
try:
self.delete_Files(Args[1])
except:
pass
except IndexError:
try:
self.delete_Files(Args[1])
except Exception as E:
print(E)
else:
pass
except:
pass
elif Args[0] == 'tar':
try:
if not Args[1] == '-h' or not Args[1] == '--help' or not '-h' in Args[1] or not '--help' in Args[1]:
self.TarArgument(Args)
else:
self.help_tar()
except:
pass
elif Args[0] == 'unzip':