cli.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. """
  2. Module version for monitoring CLI pipes (`... | python -m tqdm | ...`).
  3. """
  4. import logging
  5. import re
  6. import sys
  7. from ast import literal_eval as numeric
  8. from .std import TqdmKeyError, TqdmTypeError, tqdm
  9. from .version import __version__
  10. __all__ = ["main"]
  11. log = logging.getLogger(__name__)
  12. def cast(val, typ):
  13. log.debug((val, typ))
  14. if " or " in typ:
  15. for t in typ.split(" or "):
  16. try:
  17. return cast(val, t)
  18. except TqdmTypeError:
  19. pass
  20. raise TqdmTypeError(val + ' : ' + typ)
  21. # sys.stderr.write('\ndebug | `val:type`: `' + val + ':' + typ + '`.\n')
  22. if typ == 'bool':
  23. if (val == 'True') or (val == ''):
  24. return True
  25. elif val == 'False':
  26. return False
  27. else:
  28. raise TqdmTypeError(val + ' : ' + typ)
  29. try:
  30. return eval(typ + '("' + val + '")')
  31. except Exception:
  32. if typ == 'chr':
  33. return chr(ord(eval('"' + val + '"'))).encode()
  34. else:
  35. raise TqdmTypeError(val + ' : ' + typ)
  36. def posix_pipe(fin, fout, delim=b'\\n', buf_size=256,
  37. callback=lambda float: None, callback_len=True):
  38. """
  39. Params
  40. ------
  41. fin : binary file with `read(buf_size : int)` method
  42. fout : binary file with `write` (and optionally `flush`) methods.
  43. callback : function(float), e.g.: `tqdm.update`
  44. callback_len : If (default: True) do `callback(len(buffer))`.
  45. Otherwise, do `callback(data) for data in buffer.split(delim)`.
  46. """
  47. fp_write = fout.write
  48. if not delim:
  49. while True:
  50. tmp = fin.read(buf_size)
  51. # flush at EOF
  52. if not tmp:
  53. getattr(fout, 'flush', lambda: None)()
  54. return
  55. fp_write(tmp)
  56. callback(len(tmp))
  57. # return
  58. buf = b''
  59. len_delim = len(delim)
  60. # n = 0
  61. while True:
  62. tmp = fin.read(buf_size)
  63. # flush at EOF
  64. if not tmp:
  65. if buf:
  66. fp_write(buf)
  67. if callback_len:
  68. # n += 1 + buf.count(delim)
  69. callback(1 + buf.count(delim))
  70. else:
  71. for i in buf.split(delim):
  72. callback(i)
  73. getattr(fout, 'flush', lambda: None)()
  74. return # n
  75. while True:
  76. i = tmp.find(delim)
  77. if i < 0:
  78. buf += tmp
  79. break
  80. fp_write(buf + tmp[:i + len(delim)])
  81. # n += 1
  82. callback(1 if callback_len else (buf + tmp[:i]))
  83. buf = b''
  84. tmp = tmp[i + len_delim:]
  85. # ((opt, type), ... )
  86. RE_OPTS = re.compile(r'\n {8}(\S+)\s{2,}:\s*([^,]+)')
  87. # better split method assuming no positional args
  88. RE_SHLEX = re.compile(r'\s*(?<!\S)--?([^\s=]+)(\s+|=|$)')
  89. # TODO: add custom support for some of the following?
  90. UNSUPPORTED_OPTS = ('iterable', 'gui', 'out', 'file')
  91. # The 8 leading spaces are required for consistency
  92. CLI_EXTRA_DOC = r"""
  93. Extra CLI Options
  94. -----------------
  95. name : type, optional
  96. TODO: find out why this is needed.
  97. delim : chr, optional
  98. Delimiting character [default: '\n']. Use '\0' for null.
  99. N.B.: on Windows systems, Python converts '\n' to '\r\n'.
  100. buf_size : int, optional
  101. String buffer size in bytes [default: 256]
  102. used when `delim` is specified.
  103. bytes : bool, optional
  104. If true, will count bytes, ignore `delim`, and default
  105. `unit_scale` to True, `unit_divisor` to 1024, and `unit` to 'B'.
  106. tee : bool, optional
  107. If true, passes `stdin` to both `stderr` and `stdout`.
  108. update : bool, optional
  109. If true, will treat input as newly elapsed iterations,
  110. i.e. numbers to pass to `update()`. Note that this is slow
  111. (~2e5 it/s) since every input must be decoded as a number.
  112. update_to : bool, optional
  113. If true, will treat input as total elapsed iterations,
  114. i.e. numbers to assign to `self.n`. Note that this is slow
  115. (~2e5 it/s) since every input must be decoded as a number.
  116. null : bool, optional
  117. If true, will discard input (no stdout).
  118. manpath : str, optional
  119. Directory in which to install tqdm man pages.
  120. comppath : str, optional
  121. Directory in which to place tqdm completion.
  122. log : str, optional
  123. CRITICAL|FATAL|ERROR|WARN(ING)|[default: 'INFO']|DEBUG|NOTSET.
  124. """
  125. def main(fp=sys.stderr, argv=None):
  126. """
  127. Parameters (internal use only)
  128. ---------
  129. fp : file-like object for tqdm
  130. argv : list (default: sys.argv[1:])
  131. """
  132. if argv is None:
  133. argv = sys.argv[1:]
  134. try:
  135. log_idx = argv.index('--log')
  136. except ValueError:
  137. for i in argv:
  138. if i.startswith('--log='):
  139. logLevel = i[len('--log='):]
  140. break
  141. else:
  142. logLevel = 'INFO'
  143. else:
  144. # argv.pop(log_idx)
  145. # logLevel = argv.pop(log_idx)
  146. logLevel = argv[log_idx + 1]
  147. logging.basicConfig(level=getattr(logging, logLevel),
  148. format="%(levelname)s:%(module)s:%(lineno)d:%(message)s")
  149. d = tqdm.__init__.__doc__ + CLI_EXTRA_DOC
  150. opt_types = dict(RE_OPTS.findall(d))
  151. # opt_types['delim'] = 'chr'
  152. for o in UNSUPPORTED_OPTS:
  153. opt_types.pop(o)
  154. log.debug(sorted(opt_types.items()))
  155. # d = RE_OPTS.sub(r' --\1=<\1> : \2', d)
  156. split = RE_OPTS.split(d)
  157. opt_types_desc = zip(split[1::3], split[2::3], split[3::3])
  158. d = ''.join(('\n --{0} : {2}{3}' if otd[1] == 'bool' else
  159. '\n --{0}=<{1}> : {2}{3}').format(
  160. otd[0].replace('_', '-'), otd[0], *otd[1:])
  161. for otd in opt_types_desc if otd[0] not in UNSUPPORTED_OPTS)
  162. help_short = "Usage:\n tqdm [--help | options]\n"
  163. d = help_short + """
  164. Options:
  165. -h, --help Print this help and exit.
  166. -v, --version Print version and exit.
  167. """ + d.strip('\n') + '\n'
  168. # opts = docopt(d, version=__version__)
  169. if any(v in argv for v in ('-v', '--version')):
  170. sys.stdout.write(__version__ + '\n')
  171. sys.exit(0)
  172. elif any(v in argv for v in ('-h', '--help')):
  173. sys.stdout.write(d + '\n')
  174. sys.exit(0)
  175. elif argv and argv[0][:2] != '--':
  176. sys.stderr.write(f"Error:Unknown argument:{argv[0]}\n{help_short}")
  177. argv = RE_SHLEX.split(' '.join(["tqdm"] + argv))
  178. opts = dict(zip(argv[1::3], argv[3::3]))
  179. log.debug(opts)
  180. opts.pop('log', True)
  181. tqdm_args = {'file': fp}
  182. try:
  183. for (o, v) in opts.items():
  184. o = o.replace('-', '_')
  185. try:
  186. tqdm_args[o] = cast(v, opt_types[o])
  187. except KeyError as e:
  188. raise TqdmKeyError(str(e))
  189. log.debug('args:' + str(tqdm_args))
  190. delim_per_char = tqdm_args.pop('bytes', False)
  191. update = tqdm_args.pop('update', False)
  192. update_to = tqdm_args.pop('update_to', False)
  193. if sum((delim_per_char, update, update_to)) > 1:
  194. raise TqdmKeyError("Can only have one of --bytes --update --update_to")
  195. except Exception:
  196. fp.write("\nError:\n" + help_short)
  197. stdin, stdout_write = sys.stdin, sys.stdout.write
  198. for i in stdin:
  199. stdout_write(i)
  200. raise
  201. else:
  202. buf_size = tqdm_args.pop('buf_size', 256)
  203. delim = tqdm_args.pop('delim', b'\\n')
  204. tee = tqdm_args.pop('tee', False)
  205. manpath = tqdm_args.pop('manpath', None)
  206. comppath = tqdm_args.pop('comppath', None)
  207. if tqdm_args.pop('null', False):
  208. class stdout(object):
  209. @staticmethod
  210. def write(_):
  211. pass
  212. else:
  213. stdout = sys.stdout
  214. stdout = getattr(stdout, 'buffer', stdout)
  215. stdin = getattr(sys.stdin, 'buffer', sys.stdin)
  216. if manpath or comppath:
  217. from importlib import resources
  218. from os import path
  219. from shutil import copyfile
  220. def cp(name, dst):
  221. """copy resource `name` to `dst`"""
  222. if hasattr(resources, 'files'):
  223. copyfile(str(resources.files('tqdm') / name), dst)
  224. else: # py<3.9
  225. with resources.path('tqdm', name) as src:
  226. copyfile(str(src), dst)
  227. log.info("written:%s", dst)
  228. if manpath is not None:
  229. cp('tqdm.1', path.join(manpath, 'tqdm.1'))
  230. if comppath is not None:
  231. cp('completion.sh', path.join(comppath, 'tqdm_completion.sh'))
  232. sys.exit(0)
  233. if tee:
  234. stdout_write = stdout.write
  235. fp_write = getattr(fp, 'buffer', fp).write
  236. class stdout(object): # pylint: disable=function-redefined
  237. @staticmethod
  238. def write(x):
  239. with tqdm.external_write_mode(file=fp):
  240. fp_write(x)
  241. stdout_write(x)
  242. if delim_per_char:
  243. tqdm_args.setdefault('unit', 'B')
  244. tqdm_args.setdefault('unit_scale', True)
  245. tqdm_args.setdefault('unit_divisor', 1024)
  246. log.debug(tqdm_args)
  247. with tqdm(**tqdm_args) as t:
  248. posix_pipe(stdin, stdout, '', buf_size, t.update)
  249. elif delim == b'\\n':
  250. log.debug(tqdm_args)
  251. write = stdout.write
  252. if update or update_to:
  253. with tqdm(**tqdm_args) as t:
  254. if update:
  255. def callback(i):
  256. t.update(numeric(i.decode()))
  257. else: # update_to
  258. def callback(i):
  259. t.update(numeric(i.decode()) - t.n)
  260. for i in stdin:
  261. write(i)
  262. callback(i)
  263. else:
  264. for i in tqdm(stdin, **tqdm_args):
  265. write(i)
  266. else:
  267. log.debug(tqdm_args)
  268. with tqdm(**tqdm_args) as t:
  269. callback_len = False
  270. if update:
  271. def callback(i):
  272. t.update(numeric(i.decode()))
  273. elif update_to:
  274. def callback(i):
  275. t.update(numeric(i.decode()) - t.n)
  276. else:
  277. callback = t.update
  278. callback_len = True
  279. posix_pipe(stdin, stdout, delim, buf_size, callback, callback_len)