-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPython.py
1647 lines (1269 loc) · 49.8 KB
/
Python.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
# version 3.8
================================================================================
Basics =========================================================================
================================================================================
# Python is interpreted, dynamic language.
# Supports object-oriented style.
# Can be used in interactive mode.
# Python doesnt use curly braces for code blocks. It uses
# tabs|spaces indentation.
# Doesnt need a semicolon on line end. But semicolon uses to separate
# several statements in one line.
# One statement can be splitted to multiple lines by adding "\" symbol
# at each line end.
# To make script file executable:
# add shebang at first line:
#!/usr/bin/env python3
# set executable permission for file
================================
Modules
# Import module:
import package1, package2.module2, ...
from package import module
from package.module import member1, member2
# Reimport module:
reload(module_name)
# To make subdir to be a package need to put empty "__init__.py" file
# to this dir.
# When package imported, this file implicitly executed, and the objects
# it defines are bound to names in the package’s namespace.
# src/
# __init__.py
# main.py
# ...
# package/
# __init__.py
# file1.py
# ...
# sub/
# __init__.py
# file2.py
# ...
# So, in main.py it can be imported:
# from src.package import file1;
# from src.package.sub import file2;
# from src.package.file1 import SomeFunc;
# dependencies
# specify module's dependencies in requirements.txt
# Install deps lister in requirements.txt:
pip install -r requirements.txt
# Search for avaialble versions:
pip index versions <package>
================================
Variables
# Assignment
name = "public variable"
_name = "private variable"
a, b, c = 1, 2, "c" # multiple assignment
a, b = (one, two) # destructuring
# Delete variable
del name
# Check identity
a is b
a is not b
dir([obj]) : list # get list of names of variables in current scope
# or attributes of given object
globals(): dict # get dict of global variables
================================
Types
# Mutable objects passes by reference, primitives - by value.
bool # True, False
# in logical context any non-zero and non-empty value
# interpretes as True
int
float
complex
str
list
tuple
set
dict
None # null value
# Get type:
type(obj) : type # "<class 'typeName'>"
# All types inherited from object.
Type conversion:
int(x, base)
hex(x)
oct(x)
float(x)
complex(x, imag)
str(obj, encoding="utf-8")
bytes(obj [, encoding])
list(iterable)
tuple(iterable)
set(iterable)
dict(iterable)
================================
Operators
** # power
~
+a, -a
*, /
% # modulus
// # integer division
+, -
>>, <<
&, ^, |
<=, <, >, >=
==, !=
=
is, is not
in, not in
not
and
or
================================
Control statements
if expr:
# code
if (expr):
# code
elif expr:
# code
else:
#code
valOnTrue if expr else valOnFalse # ternar operator
while expr:
# code
for item in iterable:
# code
break # to break loop
continue # to break current iteration of loop
pass # empty statement, does nothing (e.g. for stubs)
================================
Functions
# Define:
def func(arg1, arg2 = defVal, *args, **kwargs):
"optional documentation string"
val1 = args[0] # args is a tuple
val2 = kwargs[key] # kwargs is a dict
...
def nestedFunc():
nonlocal arg1 # to access parent func scope
global globVar # to access global scope
...
return expr
# Call:
func("a")
func("a", "b")
func("a", "b", 1, 2, 3)
# Get reference:
f = func
f("a")
Lambda
# Lambda contains only one expression
lmb = lambda a, b: a + b # returns automatically
================================
OOP
isinstance(obj, type) : bool
issubclass(sub_type, super_type) : bool
Type attributes:
__doc__ : str # documentation string
__module__ : str # module name (path)
__name__ : str # class name when imported
# "__main__" when called from command line
__bases__ : tuple # tuple of parent types
Builtin methods that can be overriden:
__init__(self [, *args]) # constructor
# Typename(*args)
__del__(self) # destructor
# del obj
__repr__(self) : str # "official" string representation
# repr(obj)
__str__(self) : str # "informal" string representation
# str(obj)
__bytes__(self) : bytes
# bytes(obj)
__lt__(self, other) : bool # "rich comparison" methods
__le__(self, other) : bool
__eq__(self, other) : bool
__ne__(self, other) : bool
__gt__(self, other) : bool
__ge__(self, other) : bool
class Parent:
"optional documentation string " \
"blah blah"
staticF = "static field"
def __init__(self, f):
# constructor
print("Parent constructor")
self.f = f
def setF(self, f):
print("Parent.setF", f)
self.f = f
def getF(self):
return self.f
@classmethod
def staticMethod(cls, stf):
# @classmethod - with required first argument
# @staticmethod - can have 0 arguments
print("staticMethod", stf)
cls.staticF = stf
def __del__(self):
# destructor
print(self.__class__, " destroyed")
class Child (Parent):
__privF = "private field"
def __init__(self):
print("Child constructor")
super().__init__("child")
def setF(self, f):
print("Child.setF", f)
self.f = f
def __str__(self):
return "Child (f='%s')" % (self.f)
def callParent(self):
Parent.setF(self, "f")
p = Parent("parent")
print(Parent.staticF)
Parent.staticMethod("f");
p.staticMethod("f2")
c = Child()
print(c.getF())
c.setF("child2")
================================
Debug
# import pdb
pdb.run(statement [, globals][, locals]) # exec statement in
# interactive debugger
pdb.runcall(func [, *args]) : obj # call function in debugger
pdb.set_trace() # enter debugger at curr stack frame
pdb.pm() # enter post-mortem debugging (sys.last_traceback)
pdb.post_mortem([traceback]) # using given traceback or currently
# handled exception
# commands:
p # print
pp # pretty print
n # step to next line
s # step into
c # continue
q # exit
================================================================================
Environment ====================================================================
================================================================================
Exit program:
sys.exit()
Environment variables:
os.getenv(key [, defVal]) : str
================================
Command line arguments
# import sys
sys.argv : list # list of arguments [scriptname, arg1, arg2, ...]
getopt # To parse commang line arguments
# import getopt
getopt.getopt(argv, opts [, longopts]) : tuple
# argv - command line arguments without first (scriptname),
# e.g. sys.argv[1:]
# opts - str of short option letters, e.g. "X:Y:" (-Xval1 -Y val2)
# longopts - list of long options, e.g. ["opt1=",
# "opt2="] (--opt1=val1 --opt2 val2)
# ":" and "=" means that value required for this option
# returns 2-tuple contains list of found key-value tuples
# and list of free arguments that are left
# Ex:
argv = sys.argv[1:]
# ["-Bb", "-A", "-C", "c", "--lA=la", "--lB", "f"]
opts, args = getopt.getopt(argv, "AB:C:", ["lA=", "lB"])
# opts = [('-B', 'b'), ('-A', ''), ('-C', 'c'),
# ('--lA', 'la')];
# args = ['f']
for k, v in opts:
if k == "-A":
# process A ...
elif k == "-B":
# process B ...
# ...
argparse
# import argparse
argparse.ArgumentParser()
add_argument(name,
type=str, required=False, default=None, help='')
# name - string like '--flag_name'
parse_args() : args
parse_known_args() : (args, rest)
# Ex:
parser = argparse.ArgumentParser()
parser.add_argument(
'--model_file',
type=str,
required=True,
help='Path to .ckpt file')
args, unparsed = parser.parse_known_args()
================================
Handle interruption
# import signal
signal.SIGINT : int
signal.SIGTERM : int
...
signal.signal(int, func(int, frame))
================================
Run subprocess
# import subprocess
subprocess.PIPE : int # special value that can be used as the
# stdin, stdout, stderr args to indicate that a pipe to the
# standard stream should be opened
subprocess.call(args_list) : int # run subprocess and return returncode
subprocess.check_output(args_list) : bytes # raise error if returncode != 0
subprocess.run(args,
input=None,
stdout=None, stderr=None,
cwd=None) : CompletedProcess
# run command (using Popen) and return results
# CompletedProcess:
cmd : str
returncode : int
stdout : None|bytes
stderr : None|bytes
Popen
# from subprocess import Popen
Popen(args,
stdin=None, stdout=None, stderr=None,
cwd=None)
cmd : str
returncode : int
stdin : None|BufferedWriter
stdout : None|BufferedReader
stderr : None|BufferedReader
communicate([bytes], timeout=None) : bytes
# write input, read output and return
# can raise TimeoutExpired if timeout specified
poll() : None|int # check if process has terminated
wait(timeout=None) : int
send_signal(int)
terminate()
kill()
================================================================================
Exceptions =====================================================================
================================================================================
# Catch:
try:
# ...
except ExceptionSub as e:
# ...
print(e.args) # tuple of arguments that was passed to exception
# constructor
except (*Exceptions):
# ...
except:
# ...
raise # re-raise exception
else:
# if try executed without exception
try:
# ...
except:
# ...
finally:
# ...
# Raise:
raise ExceptionClass(arg)
BaseException # base exception class
SystemExit # raises by sys.exit()
KeyboardInterrupt
GeneratorExit
Exception # base class for all builtin non-system-exiting and for
# user-defined exceptions
AssertionError
ImportError
StopIteration # raises by next() function when sequence end reaches
ArithmeticError
BufferError
LookupError
EOFError
RuntimeError
Warning
...
# Stacktrace:
# import traceback
traceback.format_exc([limit]) : str
================================================================================
Math ===========================================================================
================================================================================
abs(n) : number
round(fl [, n]) : int # round fl to n digits after point
min(*numbers) : number
max(*numbers) : number
sum(iterable [, start]) : number
================================
math package
# import math
math.inf
math.nan
math.floor(fl) : int
math.ceil(fl) : int
math.log(n) : number
math.log10(n) : number
math.pow(n, m) : number
math.sqrt(n) : number
math.modf(fl) : tuple # separate float to fractional and integer parts
================================
random package
# import random
random.choice(sequence) : val # select random element from list
random.randrange(start, stop, step) : number # select random num
# from range
random.random() : float # [0; 1)
random.uniform(n1, n2) : float # [n1; n2)
random.shuffle(list)
================================================================================
Strings ========================================================================
================================================================================
s = "string"
s = 'string'
s = """multiline
string\n"""
s = "line one " \
"line two"
s1 + s2 # concat
s * n # repeat n times
"%s %d %02d %f %1.2f %o %x %#x" % (*values) # format
f"some str {expr}" # string interpolation
# since v3.6
char = str[i]
substr = str[iFrom:iTo]
substr = str[iFrom:iTo:step]
# for example: 'qwerty'[::-1] - reversed string
substr in s # check for membership
substr not in s
# special chars:
\b, \f, \n, \r, \t, \v, \s
# raw string:
r"some \nstring"
# bytes:
b"some bytes" # only ascii
b.decode(encoding="utf-8") : str
chr(code) : str # get char by charcode
ord(char) : int # get charcode by char
len(s) : int
min(s) : char
max(s) : char
================================
String methods:
count(str [, i_from, i_to]) : int # number of occurences
startswith(prefix [, i_from, i_to]) : bool
endswith(suffix [, i_from, i_to]) : bool
find(str [, i_from, i_to]) : int
replace(old, new [, limit]) : str
strip([chars]) : str # remove leading and trailing whitespaces
isalpha() : bool
isalnum() : bool
isdigit() : bool
isspace() : bool
islower() : bool
lower() : str
isupper() : bool
upper() : str
swapcase() : str # invert case
capitalize() : str
title() : str # each word capitalized
join(seq) : str # this string is a separator
split(separ [, limit])
# e.g.: "a b c d".split(" ", 2) == ['a', 'b', 'c d']
encode(encoding="utf-8") : bytes
format(**values)
# ex: 'your name is: {name}'.format(name='Eric')
================================
Regex
# import re
re.U # UNICODE
re.S # DOTALL ("." will match all include newlines)
re.I # IGNORECASE
re.L # LOCALE (locale-aware)
re.M # MULTILINE
re.compile(pattern, flags=0) : pattern
re.escape(str) : str
re.match(pattern, str, flags=0) : match|None # match beginning of string
# pattern - regex string or pattern object
# match:
.group(index) : str
# 0 - full match, from 1 - groups
.groups() : tuple
re.fullmatch(pattern, str, flags=0) : match|None # match whole string
re.search(pattern, str, flags=0) : match|None # first occurence
re.findall(pattern, str, flags=0) : list<str>
re.finditer(pattern, str, flags=0) : iterator<match>
re.sub(pattern, repl, str, limit=0, flags=0) : str # replace
re.split(pattern, str) : list<str>
Pattern:
match(str [, start_pos, end_pos]) : match|None
fullmatch(str [, start_pos, end_pos]) : match|None
search(str [, start_pos, end_pos]) : match|None
findall(str [, start_pos, end_pos]) : list<str>
finditer(str [, start_pos, end_pos]) : iterator<match>
sub(repl, str, limit=0) : str
start([group]) : int
end([group]) : int
# Ex:
r = re.compile(r'([a-zа-я]{3})', re.I|re.U)
f = r.findall("abc def Йцу") # ['abc', 'def', 'Йцу']
================================
Template # To format string with placeholders
# import string.Template
Template(format_str)
substitute(keyw_args) : str
safe_substitute(keyw_args) : str # not raise error if value not found
# Ex:
t = Template("some ${key} string")
t.substitute(key="short") # "some short string"
================================
Base64
# import base64
base64.b64encode(bytes) : str
base64.b64decode(str) : bytes
================================================================================
Collections ====================================================================
================================================================================
# list, tuple, dictionary
# Any collection can contain elements of different types
================================
List
lst = [item1, ...]
lst1 + lst2 # concat
lst * n # repeat n times
item = lst[index]
slice = lst[iFrom:iTo]
slice = lst[iFrom:iTo:step]
lst[index] = newitem
del lst[index]
obj in lst # check for membership
obj not in lst
len(lst) : int
min(lst) : obj
max(lst) : obj
List methods:
append(obj)
extend(seq) # append contents of seq to this
insert(index, obj)
remove(obj) # first occurence
pop([index]) : obj # get and remove
sort(key=lambda(v) : v)
reverse()
index(obj) : int
count(obj) : int
================================
Tuple
# Tuple is a read-only List
tp = (item1, ...)
tp1 + tp2 # concat
tp * n # repeat n times
item = tp[index]
slice = tp[nFrom:nTo]
obj in tp # check for membership
obj not in tp
len(tp) : int
min(tp) : obj
max(tp) : obj
================================
Dict
mp = {"key1": val1, ...}
val = mp[key] # throws KeyError if does not exists
mp[key] = newval
del mp[key]
key in mp # check for membership
key not in mp
len(mp) : int
Dict methods:
clear()
copy() : dict
fromkeys(seq [, defVal]) : dict
get(key [, defVal]) : obj
setdefault(key [, defVal]) : obj
update(dict2) # append dict2's pairs to this
items() : dict_items # key-value pairs (tuples)
# use iter(seq) func to create iterator from dict_keys, dict_values
# or dict_items
keys() : dict_keys
values() : dict_values
================================
Set
s = set(iterable)
s = {val1, val2, ...}
v in s
v not in s
len(s) : int
Set methods:
add(obj)
remove(obj)
discard(obj) # remove if exists
pop(obj) : obj
clear()
union(seq) : set # disjunction
update(seq) # disjunction
intersection(seq) : set # conjunction
intersection_update(seq)
difference(seq) : set # subtraction
difference_update(seq)
symmetric_difference(seq) : set
symmetric_difference_update(seq)
issubset(set) : bool
issuperset(set) : bool
================================
Looping
for item in seq:
...
for item in sorted(seq):
...
for item in reversed(seq):
...
for i, v in enumerate(seq):
...
for k, v in dict.items():
...
================================
Iterators
# To create iterator object from any sequence:
iter(seq) : iterator
# to iterate on iterator:
next(iterator) : obj
# Generator is a function that makes its argument iterable using yield
# statement
# Ex:
def reverse(obj):
for index in range(obj.count()-1, -1, -1):
yield obj.getSomeItem(index)
# Generator expression:
(expr for item in iterable) # creates iterator
filter(func(v) : bool, iterable) : iterator
map(func(v) : obj, iterable) : iterator
zip(*iterables) : iterator
range(nFrom, nTo [, step]) : iterator # [nFrom; nTo)
================================
Comprehension
# Iterate by sequence and generate new list:
[expr for item in iterable]
# new dict:
{key_expr: val_expr for item in iterable}
# Comprehension + filter:
[expr for item in iterable if expr]
# Ex:
{str(v) for v in arr} # create set of stringified items
================================
JSON
# import json
json.dumps(obj, indent=None, ensure_ascii=True, allow_nan=True,
sort_keys=False) : str
json.dump(obj, file_p, indent=None, ensure_ascii=True, allow_nan=True,
sort_keys=False) # write to file opened in text mode
json.loads(json_str) : obj
json.load(file_p) : obj
================================================================================
Date & Time ====================================================================
================================================================================
time package
# import time
time.timezone : int # timezone delta in seconds
time.tzname : tuple
time.time() : float # timestamp
time.localtime() : time_struct
time.localtime(timestamp) : time_struct
.tm_year
.tm_mon # 1-12
.tm_mday # 1-31
.tm_wday # 0-6
.tm_hour # 0-23
.tm_min # 0-59
.tm_sec # 0-59
.tm_yday # 1-366
.tm_isdst # 0,1,-1
time.gmtime(timestamp) : time_struct
time.asctime(time_struct) : str
time.mktime(time_struct) : float
time.strftime(fmt, time_struct) : str
time.strptime(timestr, fmt) : time_struct
time.sleep(dur) # suspend thread for dur seconds (float)
================================================================================
IO, Files ======================================================================
================================================================================
File
open(filename [, mode, buffering, encoding]) : File
# mode - r (read, default), r+ (read, write), rb (read, binary),
# w (rewrite, create non-existing), w+ (rewrite, read, create),
# a (append, create), a+ (read, append, create)
# buffering - 0 (no buffer), 1 (line buffer), >1 (spec buff size),
# -1 (system default)
# encoding - encoding name str, like "utf-8"
File object
closed : bool
mode : str
name : str # path
read([limit]) : data # data - string or binary
readline([limit]) : data
readlines([limitHint]) : list # read as list of strings
write(data) : int
writelines(seq)
tell() : int # get current position
seek(offset [, where]) : int
# where - 0 (from start), 1 (curr pos), 2 (end)
close()
================================
os, os.path packages
# import os
os.path.exists(path) : bool
os.path.isfile(path) : bool
os.path.isdir(path) : bool
os.path.islink(path) : bool
os.path.abspath(path) : str
os.path.relpath(path [, base]) : str
os.path.isabs(path) : bool
os.path.join(*parts) : str
os.path.normpath(path) : str
os.path.split(path) : tuple # for "/d1/d2" - ("d1", "d2"),
# but for "/d1/d2/" - ("d1/d2", "")
os.path.basename(path) : str # second half from split()
os.path.dirname(path) : str # first half from split()
os.path.getatime(path) : float # last access timestamp
os.path.getmtime(path) : float # last modified timestamp
os.path.getctime(path) : float # creation timestamp
os.rename(path, newPath)
os.remove(filepath)
os.rmdir(dirpath) # must be empty
os.mkdir(dirname [, mode=0o777])
os.makedirs(dirpath [, mode=0o777, exist_ok=False])
os.listdir(dirpath) : list # list of names
os.chdir(dirpath)
os.getcwd() : str
os.chmod(path, mode)
================================
shutil module
# import shutil
shutil.copy(src, dst) # copy file
shutil.copytree(src, dst [, symlinks=False]) # copy dir recursive
# if symlinks = true symlinks will be copied as symlinks instead of
# copying linked files
shutil.move(src, dst) # move file|dir
================================
Glob # Searching files by unix-shell-like pattern
# import glob
glob.glob(pattern [, recursive]) : list
# where pattern - string like "./**/*.ext" (finds all .ext files
# in all subdirectories)
glob.iglob(pattern [, recursive]) : iterator
================================
Standart IO
Console # Read (write) from (to) stdin (stdout) by default
input(prompt) : str
print(*values, sep=' ', end='\n')
STDIN, STDOUT, STDERR # even if redirected
# import sys
sys.stdin.read(minSize) : str # until EOF reached
sys.stdout.write(str)
sys.stderr.write(str)
================================================================================
Socket =========================================================================
================================================================================
# import socket
socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
bind(addr)
# addr - tuple (ip, portnumber)
# if ip is empty string INADDR_ANY will be used
listen([backlog])
accept() : (socket, addr)
connect(addr)
close()
detach() : int # detach file descriptor
recv([bufsize] [, flags]) : bytes # read up to bufsize bytes
# returns empty if socket closed by other side