-
Notifications
You must be signed in to change notification settings - Fork 2
/
python.txt
4402 lines (3575 loc) · 130 KB
/
python.txt
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
# -*- mode: python;-*-
##############
### Python ###
##############
##############
### random ###
##############
# python RNG
import random
random.seed(42)
# random float
import random
# between 0 and 1
random.random()
# in a desired range
random.uniform(0, 100)
# generate a random integer in a given range, including the upper limit
from random import randint
randint(0, 9)
# generate 20 numbers in the range of 1...10
import numpy as np
np.random.randint(10, size=20)
# same
import random
a = [random.randint(1, 10) for _ in range(20)]
# select a random item from a list
random.choice([0, 1, 2])
# save / restore rng states - python, pytorch, numpy
py_rng_state = random.getstate()
pt_rng_state = torch.get_rng_state()
np_rng_state = numpy.random.get_state()
random.setstate(py_rng_state)
torch.set_rng_state(pt_rng_state)
numpy.random.set_state(np_rng_state)
#############
### regex ###
#############
# debug regex in real time - very useful for complex regex!
https://regex101.com/
https://www.debuggex.com/
https://pythex.org/
# Flags
re.I re.IGNORECASE ignore case
re.M re.MULTILINE make begin/end {^, $} consider each line
re.S re.DOTALL make . match newline too
re.U re.UNICODE make {\w, \W, \b, \B} follow Unicode rules
re.L re.LOCALE make {\w, \W, \b, \B} follow locale
re.X re.VERBOSE allow comments in regex, requires /s for spaces
()?iLmsux) set flags within regex
# Groups
# (...) capturing group
# (?P<Y>...) capturing group named Y
# (?:...) non-capturing group
# \Y match the Yth captured group
# (?P=Y) match the named group Y
# (?#...) comment
# Assertions
^ start of string
\A start of string, ignores m flag
$ end of string
\Z end of string, ignores m flag
\b word boundary
\B non-word boundary
(?=...) positive lookahead
(?!...) negative lookahead
(?<=...) positive lookbehind
(?<!...) negative lookbehind
(?()|) conditional
# Replacement
\g<0> Insert entire match
\g<Y> Insert match Y (name or number)
\Y Insert group numbered Y
# identifiers
isalnum()
isalpha()
isascii()
isdecimal()
isdigit()
isidentifier()
islower()
isnumeric() # checks if string is /^\d+$/
isprintable()
isspace()
istitle()
isupper()
# e.g.:
"1".isdigit() # True
"a".isdigit() # False
# replace lowercase with upcase letter
# perl: $text =~ s/(\w)/ucfirst($1)/e
# pyth: text = re.sub(r'^(\w)', lambda x: x.group(0).upper(), text)
# note that group(0) is the whole matched string,
# use group(1) for \1, etc. for r'(\w)(\s)'
# but much simpler with: text.capitalize()
# multiline replace, matching beginning of each line
buf = re.sub(r'^.*\r', '', buf, 0, re.M)
# count=0 can be omitted to replace all occurrences
# use captured groups: 5 => 5_t:
buf = re.sub(r'(\d)', r'\1_t', buf)
# find if a string contains a substring
re.search("\db", "a1bc") # <re.Match object; span=(1, 3), match='1b'>
# same but requires the full string regex and the result is the full string
re.match(".*\db.*", "a1bc") # <re.Match object; span=(0, 4), match='a1bc'>
# replacement function
def my_replace(match):
match = match.group()
return match + str(match.index('e'))
re.sub(r'@\w+', my_replace, 'quick @red fox @lame') # 'quick @red2 fox @lame4'
#
# or via lambda
# e.g. to do a lookup, access the matched string via group() directly
lookup = {'1': 'one', '2': 'two', '3': 'three'}
s = "1 testing 2 3"
re.sub(r'\d', lambda x: lookup[x.group()], s)
# match and assign to variables (assumption - the match works) - e.g. url split
match = re.findall(r'^(.*?//)([\w\.:]+)(.*)$', url)
if match: prot, domain, path = match[0]
# regex split with pattern
# 1. split: foo=1 z>=5
words = re.split(r'[>=<]+', text)
# 2: split by comma with potential spaces
words = re.split(r' *, *', text)
# a complex split with a variable size delimeter (\b was the key to solving it)
# convert: ["c<1.2.3", "aa==1.3", "bb>=2.4.1"]
# to : {'c': '<1.2.3', 'aa': '==1.3', 'bb': '>=2.4.1'}
x = ["c<1.2.3","aa==1.3", "bb>=2.4.1"];
y = {k:v for k,v in (re.split(r"(?=\b[=<>].+)", d, 2) for d in x) }
# or: with findall
{ k:v for k,v in list(re.findall(r"^([^=<>]+)([=<>]{,2}.*)", d, 2)[0] for d in x) }
# replace characters
s = s.replace('f', 'F')
# remove trailing and leading spaces.
s = s.strip()
# remove a set of characters from the two sides only:
'www.example.com'.strip('cmowz.') # 'example'
'#... Section 3.2.1 Issue #32 ...'.strip('.#! ') # 'Section 3.2.1 Issue #32'
#
# The outermost leading and trailing chars argument values are stripped from the
# string. Characters are removed from the leading end until reaching a string
# character that is not contained in the set of characters in chars. A similar
# action takes place on the trailing end
#
# use lstrip and rstrip to do same only on the left or only on the right of the string.
# escape pattern:
re.escape(pat)
# e.g.:
match = re.findall(rf'torch\s+: {re.escape(torch.__version__)}', buf)
# remove punctuation
#
import string
regex = re.compile(f'[{ re.escape(string.punctuation) }]')
regex.sub('', s)
# e.g. convert a string with punctuation, mixed cases, uneven whitespace into
# clean lowercase words (far from being complete)
regex = re.compile(f'[{ re.escape(string.punctuation) }]')
def text2words(s):
return (regex.sub('', s)
.strip()
.lower()
.replace(r'\n', ' ')
.replace(r'\r', ' ')
.split(' ')
)
# remove stop words (case insensitive)
stop_words = ['the', 'a', 'in', 'to']
stopwords_re = re.compile(fr'\b(?:{ "|".join(stop_words) })\b', re.I)
s = "The main feature in a tank"
s = re.sub(stopwords_re, '', s)
s = re.sub(r'\s+', ' ', s) # remove multiple spaces
s = s.strip() # edges
s # 'main feature tank'
# given a string - lowercase, remove punctuation, remove stopwords, unescape
# html encodings, remove http urls and convert to words
import re, string, urllib, html
stop_words = ['the', 'a', 'in', 'to', 'of', 'and', 'i', 'is', 'on', 'for', 'you', 'it',
'with', 'by', 'that', 'at', 'this', 'from', 'are', 'be', 'up']
regex2remove = re.compile(f'[{ re.escape(string.punctuation) }]')
regex2space = re.compile('http\S+|\W+|[\n\r/#\|\?\-,]', re.I)
regexstopwords = re.compile(fr'\b(?:{ "|".join(stop_words) })\b', re.I)
def text2words(s):
s = s.lower()
s = urllib.parse.unquote(s) # unescape %20, etc.
s = html.unescape(s) # unescape &, etc.
s = re.sub(regex2remove, '', s) # remove
s = re.sub(regex2space, ' ', s) # to space
s = re.sub(regexstopwords, '', s) # remove stopwords
s = re.sub(r'\s+', ' ', s) # remove multiple spaces
return s.lower().strip().split(' ')
text2words("foo%20bar http://x.to You and Me now!!!") # ['foo', 'bar', 'me', 'now']
# XXX? equivalent of:
# cat file | perl -pe 's/OLD/NEW/'
# cat file | python -c "import sys,re;[sys.stdout.write(re.sub('OLD', 'NEW', l)) for l in sys.stdin]"
# to split text correctly for the command line arguments and not just by whitespace
import shlex;
print(shlex.split("squeue --user=$(getent group six | cut -d: -f4) -o \"%.16i %.9P %R\""))
# ['squeue', '--user=$(getent', 'group', 'six', '|', 'cut', '-d:', '-f4)', '-o', '%.16i %.9P %R']
### string contains checks
#
# anywhere in the string
if "the" in x
#
# case sensitive "ends with"
x.endswith('csv')
# case insensitive "ends with"
x.lower().endswith('csv')
#
# starts with
x.startswith('The')
#
# to search in a substring delimited by start/end indices
x.startswith(search_string, start, end)
x.endswith( search_string, start, end)
# find a common substring in an array of strings
# works for long strings including multiline ones
# from https://www.geeksforgeeks.org/longest-common-substring-array-strings/
def findstem(arr):
n = len(arr)
s = arr[0]
l = len(s)
res = ""
for i in range(l):
for j in range(i + 1, l + 1):
# generating all possible substrings of our reference string arr[0] i.e s
stem = s[i:j]
k = 1
for k in range(1, n):
# Check if the generated stem is common to all words
if stem not in arr[k]:
break
# If current substring is present in all strings and its length is greater than current result
if (k + 1 == n and len(res) < len(stem)):
res = stem
return res
arr = ["grace", "graceful", "disgraceful", "gracefully"]
stems = findstem(arr)
print(stems) # grace
###########
### env ###
###########
import os
# set (always a string)
os.environ['MYVAR'] = "foo"
# returns str val for the env var. If not set None is returned, or the fallback value if provided
# read and have a fallback value if it's not set, returns str val (None is returned w/o default)
val = os.environ.get('MYVAR')
val = os.environ.get('MYVAR', 'fallback val')
# check if env var exists
if 'HOME' in os.environ: ...
# to pass custom env setting to a subprocess command:
process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', 'rsync://username@foobar.com::'], stdout=subprocess.PIPE)
# or platform-independent:
env = {'RSYNC_PASSWORD':'foobar'}
my_env = {**os.environ, **env}
subprocess.Popen(cmd, env=my_env)
# another way to expand PATH:
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
#############
### hacks ###
#############
# one liners which can't be coded normally in one liners because of :
# delegate \n injection to shell:
python -c "$(echo -e "a='True'\nif a : print(1)")"
# same with exec:
python -c "import torch; exec('with torch.cuda.device(0):\n x = torch.ones(10000,10000)')"
#############
### paths ###
#############
# env variable PYTHONPATH
PYTHONPATH="$PWD/code" python ...
# dynamic solution and also include a possibly preset env var PYTHONPATH (and dump the paths)
PYTHONPATH=`pwd`/src:$PYTHONPATH python -c 'import sys; print(sys.path)'
# show:
import os
os.environ['PYTHONPATH']
if "FOO" in os.environ:
# get current file's directory - ala perl's FindBin
import os
bindir = os.path.abspath(os.path.dirname(__file__))
# or
import pathlib
bindir = str(pathlib.Path(__file__).resolve().parent)
#
# which then can be added to python paths:
import sys
sys.path.insert(0, bindir) # take precedence
sys.path.append(bindir) # add at the end
# for going multiple levels up, pathlib is the easiest - have to remember str()
import sys
from pathlib import Path
# 3 is how many parents up
git_repo_path = Path(__file__).resolve().parents[3] / "src"
sys.path.insert(1, str(git_repo_path))
# can check to insert only once:
if str(git_repo_path) not in sys.path:
sys.path.insert(0, str(git_repo_path))
# dump sys.path
import sys
print("\n".join(sys.path))
# another way with ensuring not to insert it more than once:
import sys
from pathlib import Path
root_repo_path = Path(__file__).resolve().parents[2].as_posix()
if root_repo_path not in sys.path:
sys.path.insert(0, root_repo_path)
# to insert a bunch of paths towards the front at once
# here at 2nd position, pushing 3rd position and others out
sys.path[1:1] = [path1, path2]
# get parent.parent of the current file
pathlib.Path(__file__).resolve().parents[1]
# get the current directory's full path:
import os
os.path.realpath('.')
# pathlib way:
import pathlib, sys
pathlib.Path.cwd()
# split path into dirname and filename
import os
path = "/tmp/foo/bar.py"
dirname, filename = os.path.split(path)
# or:
dirname = os.path.dirname(path) # /tmp/foo
filename = os.path.basename(path) # bar.py
# get the full path to the directory a Python file is contained in:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
# list contents of a directory
names = sorted(os.listdir(path))
# or
list(Path(path).iterdir())
# or with glob
list(Path(path).glob('*'))
# recursive
list(Path(path).rglob('*'))
# get caller's __file__
import inspect, os
caller__file__ = inspect.stack()[1][1]
# now can get the base dir of the caller's file
def get_file_base_dir():
# returns the full path to the caller's file location
# this function caller's __file__
caller__file__ = inspect.stack()[1][1]
return os.path.abspath(os.path.dirname(caller__file__))
# to import modules relative to the current jupyter notebook's parent dir:
import os, sys
nb_dir = os.path.split(os.getcwd())[0]
if nb_dir not in sys.path: sys.path.append(nb_dir)
# extract filename from path (crossplatform)
import ntpath
ntpath.basename("a/b/c.txt") # c.txt
# or
from pathlib import Path
p = Path("a/b/c.txt")
print(p.stem) # c
print(p.name) # c.txt
print(p.suffix) # .txt
# copy files - including metadata, permissions, and can use
# destination dir as the second argument
from shutil import copy2
copy2(f_in, f_out)
copy2(file, dir)
# find where a given module was imported from
import sys
print(sys.modules['fastai'])
# find the path of the file where a class was defined
import inspect
inspect.getfile(self.__class__) # adjust to the desired class
# find who called import - can be tricky to find the right frame - there are like 5 import frames
# a.py:
import b
# b.py:
import inspect
print(inspect.stack()[6][1])
# then:
python a.py #
a.py
# probably the easiest is to insert garbage into the target module and get the full traceback on error
# rename pathlib paths (e.g. change or add extension)
# $path =~ 's|$|.bak|'
fname = Path(...)
fname_bak = fname.parent/f"{fname.name}.bak"
# path exists
import os.path
# dir or file
os.path.exists(file_path)
# check if file
os.path.isfile(file_path)
# check if directory
os.path.isdir(dir_path)
# same with pathlib
from pathlib import Path
path = Path(file_path)
path.exists()
path.is_file()
path.is_dir()
# touch file
Path(path).touch()
# unlink / remove file
Path(path).unlink(missing_ok=True)
os.remove(path)
os.unlink(path)
# unlink/remove a dir and its contents
shutil.rmtree(tmp_dir, ignore_errors=True)
# rename files
import os
os.rename('a.txt', 'b.kml')
# check if one path is a subdir of another
# https://stackoverflow.com/a/37095733/9201239
import os
def path_is_parent(parent_path, child_path):
# Smooth out relative path names, note: if you are concerned about symbolic
# links, you should use os.path.realpath too
parent_path = os.path.abspath(parent_path)
child_path = os.path.abspath(child_path)
# Compare the common path of the parent and child path with the common path
# of just the parent path. Using the commonpath method on just the parent
# path will regularise the path name in the same way as the comparison that
# deals with both paths, removing any trailing path separator
return parent_path == os.path.commonpath([parent_path, child_path])
p = "/tmp/xx/"
c1 = "/tmp/xx/yy"
c2 = "/tmp/xx1/yy"
path_is_parent(p, c1) # True
path_is_parent(p, c2) # False
# mkdir -p
from pathlib import Path
path = "tmp/foobar"
Path(path).mkdir(parents=True, exist_ok=True)
# or
import os
os.makedirs(path, exist_ok=True)
# check if one files has been modified after another file
if os.path.getmtime(src) < os.path.getmtime(dst):
print(f"{src} is newer than {dst}")
# check if program / executable exists
import shutil
def cmd_exists(cmd):
return shutil.which(cmd) is not None
# glob
import glob
glob.glob('./[0-9].*') # ['./1.gif', './2.txt']
### tmp file/dir creation ###
# create a named tmp file
import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
f.close()
tmp_file = f.name
#... use it and unlink it when done...
os.unlink(tmp_file)
# to create it at a specific path, instead of /tmp/ (or whatever default tmp dir is)
f = tempfile.NamedTemporaryFile(delete=False, dir=path)
# create a temporary file and write some data to it
fp = tempfile.TemporaryFile()
fp.write(b'Hello world!')
fp.close() # close the file, it will be removed
# create a temporary file using a context manager
with tempfile.TemporaryFile() as fp:
fp.write(b'Hello world!')
#######################
### multiprocessing ###
#######################
# execute a job in parallel using multiprocessing (no threads due to GIL)
import multiprocessing
num_workers=4
def do_work(item):
print(f"processing item={item}")
pool = multiprocessing.Pool(num_workers)
pool.map(do_work, range(10))
pool.close()
pool.join()
# threads-based polling daemon
import psutil
import threading
process = psutil.Process()
def cpu_mem_used(self):
"""get resident set size memory for the current process"""
return process.memory_info().rss
def peak_monitor_func(self):
cpu_mem_used_peak = -1
while True:
cpu_mem_used_peak = max(self.cpu_mem_used(), cpu_mem_used_peak)
# can't sleep or will not catch the peak right (this comment is here on purpose)
# time.sleep(0.001) # 1msec
if not peak_monitoring:
break
peak_monitoring = True
peak_monitor_thread = threading.Thread(target=peak_monitor_func)
peak_monitor_thread.daemon = True
peak_monitor_thread.start()
### open files monitors
# - open_files from psutil shows only a small subset of files
# - lsof shows them all
import psutil
import os
def report_open_files(pid=None):
proc = psutil.Process(pid)
total = len(proc.open_files())
print(f"Total opened files: {total}")
def launch_open_files_monitor_2():
import multiprocessing
pid = os.getpid()
num_workers=1
def do_work(id):
proc = psutil.Process(pid)
while True:
total = len(proc.open_files())
print(f"Total opened files: {total}")
pool = multiprocessing.Pool(num_workers)
pool.map(do_work, [1])
pool.close()
pool.join()
def launch_open_files_monitor(pid=None):
import psutil
import threading
import time
parent = psutil.Process(pid).parent().parent()
import subprocess
def open_files(pid, recursive=True):
out = subprocess.check_output(['lsof', '-Fn', '-ap', str(pid)], encoding='utf8', stderr=subprocess.DEVNULL)
files = set(out.strip().split('\n'))
# e.g. filter out only /dev/shm files
shm = [f for f in files if "/dev/shm" in f]
#x = "\n".join(shm)
#print(x)
return len(shm)
# or show them all
x = "\n".join(files)
print(x)
return len(files)
def do_work():
while True:
#time.sleep(0.001) # 1msec
#cnts = [len(child.open_files()) for child in parent.children(recursive=True)]
cnts = [open_files(child.pid) for child in parent.children(recursive=True)]
print(f"{len(cnts)} children: {cnts}")
peak_monitor_thread = threading.Thread(target=do_work)
peak_monitor_thread.daemon = True
peak_monitor_thread.start()
########################
### context managers ###
########################
# show how to deal with conditional context managers, including null context manager and supporting older python
def autocast_smart_context_manager(self):
if self.use_amp:
if version.parse(torch.__version__) >= version.parse("1.10"):
ctx_manager = autocast(dtype=self.amp_dtype)
else:
ctx_manager = autocast()
else:
ctx_manager = contextlib.nullcontext() if sys.version_info >= (3, 7) else contextlib.suppress()
return ctx_manager
with autocast_smart_context_manager(self):
do_something()
##################
### decorators ###
##################
# deal with a decorator that didn't exist in earlier versions of some library
try:
from torch.distributed.elastic.multiprocessing.errors import record
except ImportError:
def record(fn): # noop
return fn
@record
def main():
do_something()
#############
### print ###
#############
# multiple independent processes (not launched from python parent process)
import fcntl
def printflock(*args, **kwargs):
""" print in multiprocess env so that the outputs from different processes don't get interleaved """
with open(__file__, "r") as fh:
fcntl.flock(fh, fcntl.LOCK_EX)
try:
builtins.print(*args, **kwargs)
finally:
fcntl.flock(fh, fcntl.LOCK_UN)
# print to stdout and other filehandles via normal print (tee-functionality)
# https://stackoverflow.com/a/16551730/9201239
import sys
class multifile(object):
def __init__(self, files):
self._files = files
def __getattr__(self, attr, *args):
return self._wrap(attr, *args)
def _wrap(self, attr, *args):
def g(*a, **kw):
for f in self._files:
res = getattr(f, attr, *args)(*a, **kw)
return res
return g
# for a tee-like behavior, use like this:
sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
# all these forms work:
print 'abc'
print >>sys.stdout, 'line2'
sys.stdout.write('line3\n')
# another version where one can massage the data before it's sent into either filehandle
# this one strips \r codes from tqdm inside write()
class Tee:
""" helper class to tee print's output into a file.
Usage:
sys.stdout = Tee(filename)
print(foo) # console + file
"""
def __init__(self, filename):
self.stdout = sys.stdout
self.file = open(filename, "a")
def __getattr__(self, attr):
return getattr(self.stdout, attr)
def write(self, msg):
self.stdout.write(msg)
# strip tqdm codes
self.file.write(re.sub(r"^.*\r", "", msg, 0, re.M))
def flush(self):
self.stdout.flush()
self.file.flush()
# could make it into an object that restores sys.stdout at some point
class Tee:
""" helper class to tee print's output into a file.
Usage:
tee = Tee(filename)
print(foo) # console + file
tee.close() # restores sys.stdout
"""
def __init__(self, filename):
self.stdout = sys.stdout
self.file = open(filename, "a")
sys.stdout = self
def __del__(self):
self.close()
def close(self):
if self.stdout != None:
sys.stdout = self.stdout
self.stdout = None
if self.file != None:
self.file.close()
self.file = None
# could make it a context-manager with adding:
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
####################
### program flow ###
####################
# exit program (on error)
import sys
print("This is error message")
sys.exit()
# or (more messy but with trace)
raise ValueError("This is error message")
###################
### arg parsing ###
###################
# fire
# click https://click.palletsprojects.com/en/6.x/
# crude
if len(sys.argv) == 2 and os.path.exists(sys.argv[1]):
fn = sys.argv[1]
else:
print("Usage error: expecting a csv file as the only argument")
print("Usage: python program.py input.csv")
sys.exit()
# argparse (built-in)
import argparse
parser = argparse.ArgumentParser()
# flag option (no value)
parser.add_argument('-l', '--linestring', action="store_true", help="connect dots")
# flag option with value and default
parser.add_argument('-n', '--name', default="My Grid", help="project name",)
# required positional argument
parser.add_argument('input', help='csv input file')
# optional positional argument
parser.add_argument('output', nargs='?', help='kml output file (optional)')
# multiple arguments
parser.add_argument('--ids', type=int, nargs='+')
args = parser.parse_args()
# args.name, args.input, etc.
# dump the Namespace object nicely formatted
from pprint import pprint
pprint(vars(args))
# print back the original command line arguments (almost exactly as before the shell parsed it)
import sys
import shlex
print(sys.executable, " ".join(map(shlex.quote, sys.argv)))
# here is a much more advanced version with env vars and nicely wrapped lines
import os
import shlex
import sys
def get_orig_cmd(max_width=80, full_python_path=False):
"""
Return the original command line string that can be replayed nicely and wrapped for 80 char width
Args:
- max_width: the width to wrap for. defaults to 80
- full_python_path: whether to replicate the full path or just the last part (i.e. `python`). default to `False`
"""
cmd = []
# deal with critical env vars
env_keys = ["CUDA_VISIBLE_DEVICES"]
for key in env_keys:
val = os.environ.get(key, None)
if val is not None:
cmd.append(f"{key}={val}")
# python executable (not always needed if the script is executable)
python = sys.executable if full_python_path else sys.executable.split("/")[-1]
cmd.append(python)
# now the normal args
cmd += list(map(shlex.quote, sys.argv))
# split up into up to MAX_WIDTH lines with shell multi-line escapes
lines = []
current_line = ""
while len(cmd) > 0:
current_line += f"{cmd.pop(0)} "
if len(cmd) == 0 or len(current_line) + len(cmd[0]) + 1 > max_width - 1:
lines.append(current_line)
current_line = ""
return "\\\n".join(lines)
##################
### files / IO ###
##################
# write to file:
with open("test.py", "w") as f: f.write("Hi")
# append to file
with open("test.py", "a") as f: f.write("Hi")
# when input contains \n characters use mode='rb' (e.g. when wc -l gives a different number of lines than python ``splitlines``
len(tuple(open(file, "rb")))
# or:
with open(file, mode="rb") as f:
lines = f.read().decode("utf8").split("\n")
# get file size in Bytes
os.path.getsize(path)
# in MBytes
os.path.getsize(path) >> 20
# run a command and slurp output into lines
import subprocess
cmd = f"ls -l /tmp".split()
out = subprocess.run(cmd, stdout=subprocess.PIPE).stdout.decode('utf-8').splitlines()
# slurp file in one line, stripping newlines
[line.strip() for line in open(filename)]
# slurp via pipe:
ls -al | python -c "import sys; print sys.stdin.readlines()"
# another
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
# detect/skip binary files when manipulating text files
import os
with open(filename, "rb") as fh:
# logic to ignore binary files
chunk = fh.read(1024)
if b"\x00" in chunk: # found null byte - must be a binary! skip
# print("this is a binary file: skipping")
return
else:
# roll back to start
fh.seek(0, os.SEEK_SET)
# start normal reading and processing
### mmap
# mmap read
with open(PATH, "r") as fh:
mm = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
for idx, line in enumerate(iter(mm.readline, b"")):
#print(f"read {len(line)} chars")
total_read += len(line)
# change content in the file / replace
with open(file) as r:
text = r.read().replace(this_str, that_str)
with open(file, "w") as w:
w.write(text)
# same with pathlib
from pathli2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)
##################
### subprocess ###
##################
import signal, sys, subprocess
processes = []
# pass SIGINT/SIGTERM to children if the parent is being terminated
def sigkill_handler(signum, frame):
print(f"Parent got kill signal={signum}")
for process in processes:
print(f"Killing subprocess {process.pid}")
process.kill()
print(f"Exiting")
sys.exit(0)
signal.signal(signal.SIGINT, sigkill_handler)
signal.signal(signal.SIGTERM, sigkill_handler)
for cmd in cmds:
process = subprocess.Popen(cmd, ...)
print(f"CREATED PROCESS: {process.pid}")
processes.append(process)
# run command and get output
import subprocess
result = subprocess.run(['ls', '-1'], capture_output=True, text=True)
if result.status == 0:
print(result.stderr)
print(result.stdout)