Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Path: tqdm / _main.py
Views: 658
1
from ._tqdm import tqdm, TqdmTypeError, TqdmKeyError
2
from ._version import __version__ # NOQA
3
import sys
4
import re
5
__all__ = ["main"]
6
7
8
def cast(val, typ):
9
# sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n')
10
if typ == 'bool':
11
if (val == 'True') or (val == ''):
12
return True
13
elif val == 'False':
14
return False
15
else:
16
raise TqdmTypeError(val + ' : ' + typ)
17
try:
18
return eval(typ + '("' + val + '")')
19
except:
20
if (typ == 'chr'):
21
return chr(ord(eval('"' + val + '"')))
22
else:
23
raise TqdmTypeError(val + ' : ' + typ)
24
25
26
def posix_pipe(fin, fout, delim='\n', buf_size=256,
27
callback=lambda int: None # pragma: no cover
28
):
29
"""
30
Params
31
------
32
fin : file with `read(buf_size : int)` method
33
fout : file with `write` (and optionally `flush`) methods.
34
callback : function(int), e.g.: `tqdm.update`
35
"""
36
fp_write = fout.write
37
38
buf = ''
39
tmp = ''
40
# n = 0
41
while True:
42
tmp = fin.read(buf_size)
43
44
# flush at EOF
45
if not tmp:
46
if buf:
47
fp_write(buf)
48
callback(1 + buf.count(delim)) # n += 1 + buf.count(delim)
49
getattr(fout, 'flush', lambda: None)() # pragma: no cover
50
return # n
51
52
while True:
53
try:
54
i = tmp.index(delim)
55
except ValueError:
56
buf += tmp
57
break
58
else:
59
fp_write(buf + tmp[:i + len(delim)])
60
callback(1) # n += 1
61
buf = ''
62
tmp = tmp[i + len(delim):]
63
64
65
# ((opt, type), ... )
66
RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^\s,]+)')
67
# better split method assuming no positional args
68
RE_SHLEX = re.compile(r'\s*--?([^\s=]+)(?:\s*|=|$)')
69
70
# TODO: add custom support for some of the following?
71
UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
72
73
# The 8 leading spaces are required for consistency
74
CLI_EXTRA_DOC = r"""
75
Extra CLI Options
76
-----------------
77
delim : chr, optional
78
Delimiting character [default: '\n']. Use '\0' for null.
79
N.B.: on Windows systems, Python converts '\n' to '\r\n'.
80
buf_size : int, optional
81
String buffer size in bytes [default: 256]
82
used when `delim` is specified.
83
"""
84
85
86
def main():
87
d = tqdm.__init__.__doc__ + CLI_EXTRA_DOC
88
89
opt_types = dict(RE_OPTS.findall(d))
90
91
for o in UNSUPPORTED_OPTS:
92
opt_types.pop(o)
93
94
# d = RE_OPTS.sub(r' --\1=<\1> : \2', d)
95
split = RE_OPTS.split(d)
96
opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
97
d = ''.join('\n --{0}=<{0}> : {1}{2}'.format(*otd)
98
for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
99
100
__doc__ = """Usage:
101
tqdm [--help | options]
102
103
Options:
104
-h, --help Print this help and exit
105
-v, --version Print version and exit
106
107
""" + d.strip('\n') + '\n'
108
109
# opts = docopt(__doc__, version=__version__)
110
if any(v in sys.argv for v in ('-v', '--version')):
111
sys.stdout.write(__version__ + '\n')
112
sys.exit(0)
113
elif any(v in sys.argv for v in ('-h', '--help')):
114
sys.stdout.write(__doc__ + '\n')
115
sys.exit(0)
116
117
argv = RE_SHLEX.split(' '.join(sys.argv))
118
opts = dict(zip(argv[1::2], argv[2::2]))
119
120
tqdm_args = {}
121
try:
122
for (o, v) in opts.items():
123
try:
124
tqdm_args[o] = cast(v, opt_types[o])
125
except KeyError as e:
126
raise TqdmKeyError(str(e))
127
# sys.stderr.write('\ndebug | args: ' + str(tqdm_args) + '\n')
128
except:
129
sys.stderr.write('\nError:\nUsage:\n tqdm [--help | options]\n')
130
for i in sys.stdin:
131
sys.stdout.write(i)
132
raise
133
else:
134
delim = tqdm_args.pop('delim', '\n')
135
buf_size = tqdm_args.pop('buf_size', 256)
136
if delim == '\n':
137
for i in tqdm(sys.stdin, **tqdm_args):
138
sys.stdout.write(i)
139
else:
140
with tqdm(**tqdm_args) as t:
141
posix_pipe(sys.stdin, sys.stdout,
142
delim, buf_size, t.update)
143
144